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

FCM自定义通知APP关闭时失效,求解决方案及Service用法

FCM自定义通知在APP关闭时显示默认通知的解决方案

核心原因

FCM消息分为两种类型:

  • 通知消息:包含notification字段,APP前台时会触发onMessageReceived,后台/关闭时由系统直接显示默认通知,不会走到你的自定义逻辑。
  • 数据消息:仅包含data字段,无论APP处于前台、后台还是关闭状态(进程未被彻底杀死),都会触发onMessageReceived,完全由你的代码控制通知展示。

你的问题就出在发送的是通知消息,导致APP关闭时系统接管了通知展示。

解决方案

1. 切换为纯数据消息发送

服务器端发送FCM消息时,只填充data字段,不要包含notification字段。示例请求格式:

{
  "to": "目标设备的FCM令牌",
  "data": {
    "title": "你的自定义标题",
    "body": "你的自定义内容",
    "type": "通知类型标识",
    "imageUrl": "可选的图片URL"
  },
  "priority": "high" // 高优先级确保消息及时送达
}

2. 修改onMessageReceived处理数据消息

将原来依赖remoteMessage.getNotification()的逻辑,改为读取data字段中的内容:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Map<String, String> data = remoteMessage.getData();
    if (!data.isEmpty()) {
        Log.e("@@@TAG", "onMessageReceived: " + data.toString());
        try {
            String title = data.get("title");
            String body = data.get("body");
            String type = data.get("type");
            String imageUrl = data.get("imageUrl");
            
            // 调用自定义通知方法,注意处理字段为空的情况
            showNotification(
                title != null ? title : "默认标题",
                body != null ? body : "默认内容",
                type != null ? type : "",
                imageUrl != null ? imageUrl : ""
            );
        } catch (Exception e) {
            Log.e("@@@TAG", "onMessageReceived Exception : " + e.getMessage());
            e.printStackTrace();
        }
    }
}

3. 确保FirebaseMessagingService正确注册

在AndroidManifest.xml中确认你的Service配置正确:

<service
    android:name=".你的FirebaseMessagingService子类名称"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

关于Service的疑问

你完全可以通过Service实现需求,你当前使用的FirebaseMessagingService本身就是Google提供的用于处理FCM消息的Service。当发送数据消息时,即使APP关闭,系统会自动唤醒这个Service执行onMessageReceived方法,进而调用你的showNotification展示自定义通知,不需要额外自定义Service。

额外注意事项

  • 权限处理:Android 13及以上需要动态申请POST_NOTIFICATIONS权限,确保你的代码中已经完成权限申请逻辑。
  • 厂商后台限制:国内主流厂商(小米、华为、OPPO等)有严格的后台进程管理机制,需引导用户开启APP的「自启动权限」「后台弹出权限」,否则APP被彻底杀死后可能无法接收并处理消息。
  • 通知渠道:你的代码中已经创建了通知渠道,确保在Android 8.0及以上设备上渠道配置正确(比如IMPORTANCE_HIGH保证通知能弹出)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 15:39:53