安卓系统不会主动阻止 FCM(Firebase Cloud Messaging)通知,但是在某些情况下,可能会出现通知被系统阻止的情况。
以下是一种解决方法的代码示例,可以通过设置通知通道(Notification Channel)来提高通知的可靠性,并避免被系统阻止:
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
public class NotificationHelper {
private static final String CHANNEL_ID = "FCM_CHANNEL_ID";
private static final String CHANNEL_NAME = "FCM_CHANNEL_NAME";
public static void createNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
}
}
在你的应用程序的入口点(例如 Application 类的 onCreate 方法)中,调用 createNotificationChannel
方法来创建通知通道:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
NotificationHelper.createNotificationChannel(this);
}
}
这样,当你发送 FCM 通知时,可以使用指定的通道 ID,以确保通知可以正常显示而不被系统阻止:
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.support.v4.app.NotificationCompat;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getNotification() != null) {
showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
}
private void showNotification(String title, String message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NotificationHelper.CHANNEL_ID)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.drawable.ic_notification);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
}
}
通过设置通知通道,可以确保 FCM 通知在安卓系统上的可靠性,并避免被系统阻止。