Firebase推送通知点击时获取Intent参数:前台运行场景问题
解决SingleTask模式下Firebase通知Extras无法获取的问题
这个坑我之前做推送功能时踩过好几次!当Activity设置为singleTask后,确实不会走onCreate,但系统会把新的Intent通过onNewIntent()传递过来,咱们只要抓住这个核心点就能解决问题,下面是具体的方案:
1. 重写onNewIntent()接收新Intent
这是最关键的一步,当你的Activity已经在栈中存在时,点击通知触发的新Intent会直接进入这个方法。一定要调用setIntent(intent)更新当前Activity的Intent,不然后续调用getIntent()拿到的还是旧数据!
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); // 必须更新Intent,否则getIntent()会返回旧的历史数据 setIntent(intent); // 在这里处理通知携带的Extras handleNotificationExtras(intent.getExtras()); } private void handleNotificationExtras(Bundle extras) { if (extras == null) return; // 取出你需要的自定义数据,比如推送内容、跳转参数等 String pushContent = extras.getString("push_content"); String targetPage = extras.getString("target_page"); // 执行你的业务逻辑,比如更新UI、跳转指定页面 updateUIWithPushData(pushContent); }
2. 在onResume()中补充处理
因为onNewIntent()执行后会紧接着触发onResume(),所以在onResume()里也调用一次处理方法,能覆盖所有场景——不管是首次启动Activity(走onCreate+onResume),还是后台被唤起(走onNewIntent+onResume):
@Override protected void onResume() { super.onResume(); // 处理当前Intent的Extras,确保首次启动也能拿到数据 handleNotificationExtras(getIntent().getExtras()); }
3. 确保PendingIntent的Flag设置正确
在Firebase的MessagingService里构建通知时,PendingIntent的Flag一定要用对,不然可能出现Extras不更新的情况:
@Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); // 取出推送的自定义数据 Map<String, String> pushData = remoteMessage.getData(); Intent targetIntent = new Intent(this, YourTargetActivity.class); // 将数据存入Intent targetIntent.putExtras(new Bundle(pushData)); // 设置Intent的Flag,配合singleTask模式 targetIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); // 构建PendingIntent,关键是FLAG_UPDATE_CURRENT + FLAG_IMMUTABLE PendingIntent pendingIntent = PendingIntent.getActivity( this, 0, // 如果需要多个独立的PendingIntent,可以用动态请求码(比如System.currentTimeMillis()) targetIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE // 适配Android 12+ ); // 构建并显示通知的常规操作 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "your_channel_id") .setSmallIcon(R.drawable.ic_notification) .setContentTitle(remoteMessage.getNotification().getTitle()) .setContentText(remoteMessage.getNotification().getBody()) .setContentIntent(pendingIntent) .setAutoCancel(true); NotificationManagerCompat.from(this).notify((int) System.currentTimeMillis(), notificationBuilder.build()); }
这里解释下两个Flag的作用:
FLAG_UPDATE_CURRENT:如果之前已经存在相同的PendingIntent,会更新它的Extras,避免拿到旧数据FLAG_IMMUTABLE:Android 12及以上版本要求必须设置这个Flag(如果不需要修改Intent内容),否则会抛出异常
额外注意点
- 如果需要同时显示多条通知,不要用固定的通知ID(比如0),建议用
System.currentTimeMillis()作为ID,避免新通知覆盖旧的 - 如果你的Activity是在后台被唤起,记得检查应用的通知权限,确保通知能正常触发PendingIntent
内容的提问来源于stack exchange,提问作者BRDroid
相关产品推荐
相关产品推荐

