Android 8中Firebase推送通知不显示问题求助
解决Firebase推送通知不显示及
NotificationCompat.Builder过时问题 嘿,作为Android新手遇到这个问题太正常啦!你看到new NotificationCompat.Builder(this);被划掉,是因为这个构造方法在Android O(API 26)之后就被弃用了——从Android 8.0开始,系统要求所有通知必须关联一个通知渠道(Notification Channel),没有渠道的通知是不会显示的,这也是你推送通知没出来的核心原因。
咱们一步步来修复:
第一步:创建通知渠道
先在你的FirebaseMessagingService类里添加一个创建通知渠道的方法,这个方法会在API 26及以上版本中创建必要的渠道:
private void createNotificationChannel() { // 仅在API 26+时执行,因为通知渠道是Android 8.0新增的 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = "推送通知渠道"; // 渠道名称,用户在设置里能看到 String description = "接收Firebase推送的通知渠道"; // 渠道描述 int importance = NotificationManager.IMPORTANCE_DEFAULT; // 通知重要性,决定提示方式 NotificationChannel channel = new NotificationChannel("HOPE_NOTIFICATION_CHANNEL", name, importance); channel.setDescription(description); // 注册渠道到系统,一旦注册就不能修改重要性等核心属性,只能更新描述 NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } }
第二步:更新通知构建代码
把原来过时的NotificationCompat.Builder替换成支持渠道的新版本构造方法,并且在发送通知前确保渠道已经创建:
修改你的sendNotification方法,完整代码如下:
@Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); // 先创建通知渠道(首次调用时创建,后续调用不会重复创建) createNotificationChannel(); sendNotification(remoteMessage.getNotification().getBody()); } private void sendNotification(String messageBody){ Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Android 12+要求PendingIntent必须指定IMMUTABLE或MUTABLE标记 PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); // 使用带渠道ID的Builder构造方法,不再直接传Context NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "HOPE_NOTIFICATION_CHANNEL"); notificationBuilder.setSmallIcon(R.drawable.ic_launcher_background); notificationBuilder.setContentTitle("Hope"); notificationBuilder.setContentText(messageBody); notificationBuilder.setAutoCancel(true); notificationBuilder.setSound(defaultSoundUri); notificationBuilder.setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, notificationBuilder.build()); }
额外注意点
- 小图标问题:Android 8.0+要求通知小图标必须是透明背景的单色图标,如果你的
ic_launcher_background是带颜色的,可能会显示成白色方块,建议换成符合要求的图标。 - Android 13+权限:如果你的应用目标SDK是33及以上,需要在
AndroidManifest.xml中添加POST_NOTIFICATIONS权限,并在运行时请求用户授权,否则通知也无法显示:<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> - 渠道ID一致性:创建渠道时的
HOPE_NOTIFICATION_CHANNEL和构建通知时传入的渠道ID必须完全一致,否则通知会找不到对应渠道。
这样修改后,你的Firebase推送通知应该就能正常显示啦,而且过时的警告也会消失~
内容的提问来源于stack exchange,提问作者Mnotfo Dlamini
相关产品推荐
相关产品推荐

