Firebase推送通知点击后弹窗异常,无法显示通知文本
嘿,我看你碰到的问题是点击Firebase推送的通知后,MainActivity总是走到else分支,没法弹出显示通知内容的对话框对吧?咱们来一步步搞定这个问题:
问题根源分析
你当前的代码里,PendingIntent只设置了Intent.FLAG_ACTIVITY_NEW_TASK,但如果MainActivity已经存在于任务栈中,这个flag不会更新Intent里的额外数据(也就是你传的notifmsg)。而且当Activity被复用的时候,系统不会重新调用onCreate(),而是调用onNewIntent(),这时候你原来的onCreate()逻辑就拿不到新的通知数据了,自然就走到else分支了。
解决方案步骤
1. 更新PendingIntent的Flag
修改你创建PendingIntent的代码,加上PendingIntent.FLAG_UPDATE_CURRENT,确保新的Intent数据能覆盖旧的:
Intent intent = new Intent(this, MainActivity.class); intent.putExtra("notifmsg", remoteMessage.getNotification().getBody()); // 合并FLAG_ACTIVITY_NEW_TASK和FLAG_UPDATE_CURRENT PendingIntent pi = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK | PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pi);
这个flag的作用是:如果当前已经存在这个PendingIntent,就更新它内部的Intent内容,保证传递的notifmsg是最新的通知文本。
2. 重写MainActivity的onNewIntent()方法
当MainActivity已经处于栈顶或者被复用的时候,系统会调用onNewIntent()而不是onCreate(),所以我们需要在这里处理新的Intent数据:
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); // 把当前Activity的Intent替换成新的Intent setIntent(intent); // 这里处理通知数据,和onCreate()里的逻辑一致 String notifmsg = getIntent().getStringExtra("notifmsg"); if (notifmsg != null) { new SweetAlertDialog(this) .setTitleText("Hello Readers!") .setContentText(notifmsg) .show(); } }
3. 优化MainActivity的启动模式(可选但推荐)
在AndroidManifest.xml里给MainActivity设置singleTop启动模式,这样当Activity已经在栈顶时,系统会复用它而不是创建新实例,配合onNewIntent()使用更高效:
<activity android:name=".MainActivity" android:launchMode="singleTop"> <!-- 你的其他配置,比如intent-filter等 --> </activity>
验证修改后的效果
做完上面的修改后,再推送测试通知:
- 如果MainActivity还没打开,点击通知会启动Activity,
onCreate()里能拿到notifmsg,弹出显示通知内容的对话框; - 如果MainActivity已经在后台或者前台,点击通知会触发
onNewIntent(),同样能拿到最新的通知文本并弹出对应的对话框。
这样就不会再走到else分支啦!
内容的提问来源于stack exchange,提问作者Shubham Tunwal

