You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 17:50:44