Firebase后台通知:修改默认启动Activity及无数据通知跳转配置咨询
嘿,这俩问题都是FCM开发里经常碰到的场景,我给你拆解清楚:
1. 应用处于后台时,如何通过Firebase通知修改默认启动Activity?
这里得分FCM的几种消息类型来处理,不同类型的消息在后台的逻辑不一样:
用纯数据消息自定义通知:
如果你的消息只有data字段(没有notification字段),不管应用在前台还是后台,消息都会直接送到FirebaseMessagingService的onMessageReceived方法里。这时候你可以完全自己把控通知的样式和跳转逻辑,指定要打开的Activity:// 示例:在FirebaseMessagingService子类中实现 override fun onMessageReceived(remoteMessage: RemoteMessage) { super.onMessageReceived(remoteMessage) // 构建跳转到目标Activity的Intent val targetIntent = Intent(this, YourTargetActivity::class.java) targetIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK) // 创建PendingIntent,确保点击通知能唤起目标页面 val pendingIntent = PendingIntent.getActivity( this, 0, targetIntent, PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE ) // 组装通知内容 val notification = NotificationCompat.Builder(this, "your_notification_channel_id") .setContentTitle(remoteMessage.data["title"]) .setContentText(remoteMessage.data["body"]) .setSmallIcon(R.drawable.ic_notification_icon) .setContentIntent(pendingIntent) .build() // 显示通知 val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(System.currentTimeMillis().toInt(), notification) }用混合消息+click_action配置:
如果想保留系统默认的通知样式(不想自己手动构建),可以发送同时包含notification和data的混合消息,然后在消息payload里设置click_action字段,再在Manifest里给目标Activity配置对应的意图过滤器:
首先是消息payload示例:{ "notification": { "title": "新通知提醒", "body": "点击查看详情", "click_action": "OPEN_MY_TARGET_ACTIVITY" }, "data": { "content_id": "67890" }, "to": "你的设备推送token" }然后在
AndroidManifest.xml里给目标Activity添加intent-filter:<activity android:name=".YourTargetActivity"> <intent-filter> <action android:name="OPEN_MY_TARGET_ACTIVITY" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity>这样后台收到通知后,点击就会直接打开
YourTargetActivity,而不是默认的启动页。
2. 当应用处于后台,Firebase仅发送含标题和文本的无数据通知时,能否指定打开的Activity并修改默认启动的Activity?
直白说:不行,但有间接的 workaround。
因为纯通知消息(只有notification字段,没有data)在应用后台时,完全由Android系统的通知服务处理,不会经过你的FirebaseMessagingService。系统会默认打开应用的启动Activity(就是Manifest里标记了ACTION_MAIN和LAUNCHER的那个页面),你没法直接指定其他Activity。
那怎么绕开这个限制?可以在默认启动Activity里做跳转判断:
当启动Activity被打开时,检查intent的extras,如果包含FCM相关的字段(比如google.message_id、google.sent_time),就说明是从通知点击过来的,这时候直接跳转到目标Activity,然后关闭启动页:
// 在默认启动Activity的onCreate方法里添加逻辑 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val extras = intent.extras if (extras != null && extras.containsKey("google.message_id")) { // 跳转到目标Activity val intent = Intent(this, YourTargetActivity::class.java) startActivity(intent) finish() // 关闭启动页,避免用户返回时看到 } }
但这个方法是“曲线救国”,不是直接打开目标Activity,而是先经过启动页再跳转。如果想要直接打开目标Activity,还是得给消息加上data字段,或者改成纯数据消息,用第一个问题里的方法。
内容的提问来源于stack exchange,提问作者Mohamed hassan

