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

FCM通知点击跳转异常:打开MainActivity而非NotificationActivity

FCM通知点击跳转错误:打开MainActivity而非NotificationActivity的解决方法

问题情况

  • 需求:点击FCM推送生成的通知时,打开指定的NotificationActivity并显示推送内容
  • 异常:通过MyFirebaseMessagingService生成的FCM通知,点击后默认启动MainActivity;但应用内按钮触发的通知能正常跳转至NotificationActivity

核心原因

FCM推送分为通知消息和数据消息两种类型:

  • 若推送payload包含notification字段(通知消息),当应用处于后台时,FCM会直接由系统展示通知,不会触发MyFirebaseMessagingService的onMessageReceived方法,此时系统会默认启动应用的启动页(即配置了LAUNCHER的MainActivity),忽略你代码中自定义的PendingIntent。
  • 只有当应用处于前台时,通知消息才会进入onMessageReceived,此时你的自定义通知逻辑才会生效。

解决方案

1. 改用数据消息发送推送

将推送的payload改为仅包含data字段,移除notification字段。这样无论应用处于前台还是后台,FCM都会将消息传递到onMessageReceived方法,你的自定义通知逻辑会完全生效。

示例推送payload(JSON格式):

{
  "data": {
    "title": "您的推送标题",
    "body": "您的推送内容详情"
  },
  "to": "目标设备的FCM令牌"
}

对应修改MyFirebaseMessagingService的onMessageReceived方法,从data字段中获取推送数据:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // 从data字段提取推送标题和内容
    String title = remoteMessage.getData().get("title");
    String message = remoteMessage.getData().get("body");
    
    if (title != null && message != null) {
        showNotification(getApplicationContext(), title, message);
    }
}

2. 优化PendingIntent的Flag(可选)

为了避免Activity栈的影响,确保跳转行为符合预期,可以调整Intent的Flag设置:

Intent intent = new Intent(context, NotificationActivity.class);
intent.setAction("OPEN_NOTIFICATION_ACTIVITY");
intent.putExtra("notification_title", title);
intent.putExtra("notification_body", message);
// 清除现有栈并创建新栈,确保直接打开目标页面
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

如果需要保留应用栈结构,可以使用FLAG_ACTIVITY_SINGLE_TOP,并在NotificationActivity中重写onNewIntent方法来处理新的推送数据:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // 从新Intent中获取推送数据并更新UI
    String title = intent.getStringExtra("notification_title");
    String body = intent.getStringExtra("notification_body");
    // 更新页面展示内容
}

3. 确认Manifest配置(无需修改,仅检查)

你的现有AndroidManifest.xml配置无误,确保NotificationActivity的intent-filter和导出属性正确即可:

<activity
    android:name=".NotificationActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="OPEN_NOTIFICATION_ACTIVITY" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 04:28:12