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

服务器端发FCM指定设备通知无弹窗,需客户端实现MESSAGING_EVENT吗?

为什么你的FCM通知客户端没弹出?

首先直接给你答案:是的,当你发送纯Data类型的FCM消息时,客户端必须实现com.google.firebase.MESSAGING_EVENT对应的处理逻辑,否则系统不会自动弹出通知。

这里得给你掰扯清楚FCM两种消息类型的区别,这是问题的核心:

  • Notification消息:这种是FCM自带的标准通知格式,只要你在服务器端用setNotification()构建消息,FCM SDK会自动在客户端处理,直接弹出通知,不需要你写额外代码(当然前提是客户端已经正确集成了FCM)。
  • Data消息:这种是完全自定义的内容,FCM只会把消息原封不动传递到你的应用,不会主动触发通知弹窗——所有的展示逻辑都得你自己在客户端写代码实现。

看你现在的服务器代码,你用的是putData()来设置标题和内容,属于纯Data消息,所以客户端如果没做处理,自然看不到通知。

给你两种解决办法:

办法一:客户端实现消息处理逻辑

你需要在客户端创建一个继承自FirebaseMessagingService的服务类,重写onMessageReceived方法来手动构建并显示通知:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // 从Data里取出你发送的标题和内容
        String title = remoteMessage.getData().get("title");
        String body = remoteMessage.getData().get("body");
        
        // 构建通知(记得替换成你自己的图标和渠道ID)
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "notification_channel_id")
                .setSmallIcon(R.drawable.ic_notification_icon)
                .setContentTitle(title)
                .setContentText(body)
                .setPriority(NotificationCompat.PRIORITY_HIGH);

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        
        // Android 8.0及以上必须创建通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("notification_channel_id",
                    "App Notifications",
                    NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }
        
        // 显示通知
        notificationManager.notify(System.currentTimeMillis(), builder.build());
    }
}

然后在AndroidManifest.xml里注册这个服务,也就是添加com.google.firebase.MESSAGING_EVENT的intent filter:

<service
    android:name=".MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

办法二:服务器端改成发送Notification消息

如果你不想折腾客户端代码,可以直接在服务器端把消息改成Notification类型,这样客户端不需要额外处理,系统会自动弹出通知:

Message message = Message.builder()
        .setNotification(Notification.builder()
                .setTitle("Title")
                .setBody("Body")
                .build())
        .setToken(fcmToken)
        .build();
FirebaseMessaging.getInstance().sendAsync(message).get();

内容的提问来源于stack exchange,提问作者Marco

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:49:54