You need to enable JavaScript to run this app. 原生Android集成Firebase FCM后台点击通知重复启动问题
优惠活动
大模型
产品
解决方案
定价
更多

原生Android集成Firebase FCM后台点击通知重复启动问题

安卓FCM后台通知点击重启问题修复方案

问题根源

  • Intent配置的FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK标志位会清空应用已存在的任务栈,强制重新创建新任务,导致后台点击通知时重启应用走启动页流程。
  • 若你使用的是FCM通知类型消息,应用后台时系统会默认处理通知投递,点击事件触发系统默认的启动页Intent,你自定义的PendingIntent仅在应用前台时生效。

修复步骤

  1. 替换Intent标志位,移除清空任务栈的配置,保留原有任务栈的同时复用已存在的Activity实例:
    如需AActivity已在栈顶时直接复用,不在栈顶则将其置顶,替换原有Flag为Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK即可。如果需要应用后台时直接把原有任务栈切到前台,再打开AActivity,可以额外添加Intent.FLAG_ACTIVITY_REORDER_TO_FRONT。
  2. 适配Android 12及以上版本的PendingIntent标志位,新增PendingIntent.FLAG_IMMUTABLE避免高版本系统报错。
  3. (推荐)将FCM推送改为纯数据类型消息,所有通知的创建、点击逻辑都由你自己的FirebaseMessagingService控制,完全规避系统默认的启动页跳转逻辑。
  4. 如不想修改推送类型,可在BActivity的onCreate方法中新增判断:如果启动Intent携带FCM通知的相关参数,直接跳转到AActivity后finish当前BActivity,避免用户感知到启动页跳转。

修改后的代码示例

intent = new Intent(this, AActivity.class);            
// 替换原有标志位,保留任务栈、复用已存在的AActivity实例
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
// 适配Android 12+ 新增FLAG_IMMUTABLE
int pendingFlag = PendingIntent.FLAG_UPDATE_CURRENT;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
    pendingFlag |= PendingIntent.FLAG_IMMUTABLE;
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, pendingFlag);

String channelId = "com.a.b";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle(title)
        .setContentText(message)
        .setAutoCancel(true)
        .setPriority(NotificationCompat.PRIORITY_HIGH)
        .setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(channelId, "com.a.b-MESSAGED", NotificationManager.IMPORTANCE_DEFAULT);
    manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());

补充注意点

如果AActivity配置了singleTop/singleTask启动模式,需要重写onNewIntent方法更新Intent实例,才能正常获取到通知携带的Extras参数:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    // 在这里处理新的Extras参数
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 02:45:04