Firebase实时数据库推数据时触发Android通知实现求助
在Firebase Messaging的onMessageReceived中显示通知的实现方案
1. 先创建通知渠道(Android 8.0+ 强制要求)
Android 8.0及以上版本必须配置通知渠道才能正常显示通知,在你的FirebaseMessagingService子类中添加以下方法:
private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence channelName = "数据推送通知"; String channelDesc = "接收数据库新增数据时的通知渠道"; int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel("DATA_PUSH_CHANNEL_ID", channelName, importance); channel.setDescription(channelDesc); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } }
2. 在onMessageReceived中构建并弹出通知
直接在重写的onMessageReceived方法里完成通知的构建与显示:
@Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); // 先初始化通知渠道 createNotificationChannel(); // 获取推送的标题和内容,也可从remoteMessage的data字段取自定义数据 String notifyTitle = remoteMessage.getNotification().getTitle(); String notifyContent = remoteMessage.getNotification().getBody(); // 配置通知点击后的跳转意图 Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE ); // 构建通知实例 NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "DATA_PUSH_CHANNEL_ID") .setSmallIcon(R.drawable.ic_notify_icon) // 替换为你的通知图标 .setContentTitle(notifyTitle) .setContentText(notifyContent) .setAutoCancel(true) // 点击通知后自动消失 .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent); // 显示通知 NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(1001, builder.build()); // 1001为通知ID,可自定义 }
3. 必要配置检查
- 确认你的FirebaseMessagingService已在AndroidManifest.xml中注册:
<service android:name=".YourFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
- 如果应用处于后台时想自定义通知样式,发送推送消息时要使用
data字段而非notification字段,否则系统会自动生成默认通知。
内容的提问来源于stack exchange,提问作者user20289129
相关产品推荐
相关产品推荐

