Android应用前台时FCM不同数据通知的跳转处理
实现不同通知跳转不同页面的具体方案
嘿,刚好做过类似的需求,给你一步步拆解实现方法——你已经导入了必要的类,那咱们直接上干货:
1. 给Cloud Functions的通知Payload加类型标识
首先在你发送通知的Cloud Functions代码里,给两种通知分别加上区分字段,比如type。比如第二条通知的payload可以这么写:
// Cloud Functions里发送第二条通知的代码片段 const payload = { data: { title: "邀请已发送", body: "你的邀请已成功发送给对方", type: "invitation_sent" // 关键标识,用来区分通知类型 // 其他你需要的业务字段 } };
注意:如果用
notification字段的话,当App在后台时,系统会直接展示通知,不会走onMessageReceived方法。所以建议统一用data字段传所有内容,这样不管前台后台都能完整拿到通知数据,自定义跳转逻辑。
2. 在客户端解析通知类型,创建对应PendingIntent
在你的FirebaseMessagingService的onMessageReceived方法里,先解析出type字段,然后根据类型创建跳转到「已发送邀请页」的PendingIntent:
// 假设你的已发送邀请页是InvitationSentActivity val type = remoteMessage.data["type"] val pendingIntent = when(type) { "invitation_sent" -> { // 创建跳转到InvitationSentActivity的Intent val intent = Intent(this, InvitationSentActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK // Android 12+建议用FLAG_IMMUTABLE,避免安全风险 PendingIntent.getActivity( this, 1002, // 请求码要和第一个通知的不一样,防止PendingIntent被覆盖 intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) } "other_notification" -> { // 原来第一条通知的PendingIntent逻辑,直接复用你之前的代码就行 ... } else -> { // 默认跳转逻辑,比如回到App主页 val intent = Intent(this, MainActivity::class.java) PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE) } }
重点提醒:请求码(requestCode)必须和第一个通知的不同,否则两个PendingIntent会互相覆盖,导致跳转逻辑混乱。
3. 构建通知并绑定PendingIntent
接下来把创建好的pendingIntent设置到Notification里,和你之前创建第一个通知的逻辑类似:
val notificationBuilder = NotificationCompat.Builder(this, INVITATION_CHANNEL_ID) .setContentTitle(remoteMessage.data["title"]) .setContentText(remoteMessage.data["body"]) .setSmallIcon(R.drawable.ic_invitation_notification) .setContentIntent(pendingIntent) // 绑定对应的跳转Intent .setAutoCancel(true) // 点击后自动清除通知 val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // Android O及以上需要创建通知渠道,这个你应该已经处理过了 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( INVITATION_CHANNEL_ID, "邀请通知", NotificationManager.IMPORTANCE_DEFAULT ) notificationManager.createNotificationChannel(channel) } // 通知ID也要和第一个通知区分开,比如用2,避免两个通知重叠覆盖 notificationManager.notify(2, notificationBuilder.build())
4. 关键注意事项
- Manifest注册页面:确保
InvitationSentActivity已经在AndroidManifest.xml里正确注册,比如:<activity android:name=".InvitationSentActivity" android:exported="false" /> <!-- 不需要外部打开的话,设为false更安全 --> - 后台通知适配:如果App被杀死后要正常跳转,必须用
datapayload发送通知,不能用notification字段——否则系统展示通知时,点击会默认跳转到App启动页,不会触发你自定义的PendingIntent。 - PendingIntent Flags适配:Android 12及以上必须指定
FLAG_IMMUTABLE或FLAG_MUTABLE,如果你的Intent不需要动态修改内容,优先用FLAG_IMMUTABLE,更符合安全规范。
这样处理后,点击第二条带type: "invitation_sent"标识的通知,就能直接跳转到「已发送邀请页」啦!
内容的提问来源于stack exchange,提问作者Lahari Areti
相关产品推荐
相关产品推荐

