Capacitor中自定义FirebaseMessagingService无法触发调用的问题
问题分析
Capacitor的PushNotifications插件已在其Android Manifest中注册了MessagingService并监听com.google.firebase.MESSAGING_EVENT,而Android系统只会触发第一个匹配该Intent Action的服务,导致你自定义的ShufflechatFirebaseMessagingService被阻塞,无法收到回调。
解决方案
通过继承Capacitor自带的MessagingService,替换原有服务注册,既保留Capacitor前台通知的JS逻辑,又能添加自定义的后台/关闭状态处理。
步骤1:编写自定义Service
继承Capacitor的MessagingService,重写onMessageReceived方法,先执行Capacitor原有逻辑,再处理后台场景:
package de.myDomainHere; import com.capacitorjs.plugins.pushnotifications.MessagingService; import com.capacitorjs.plugins.pushnotifications.PushNotificationsPlugin; import com.google.firebase.messaging.RemoteMessage; import android.util.Log; public class ShufflechatFirebaseMessagingService extends MessagingService { private static final String TAG = "shuffleNotifServ"; @Override public void onCreate(){ super.onCreate(); Log.i(TAG, "自定义Firebase消息服务已启动"); } @Override public void onMessageReceived(RemoteMessage remoteMessage) { // 先调用Capacitor原生逻辑,保证前台时JS能接收通知更新UI super.onMessageReceived(remoteMessage); // 应用关闭/后台时,PushNotificationsPlugin实例为空,此时处理纯数据通知 if (PushNotificationsPlugin.getPushNotificationsInstance() == null) { Log.i(TAG, "处理后台/关闭状态消息: " + remoteMessage.getData()); // 在这里添加你的本地通知逻辑,比如触发系统本地通知 showCustomLocalNotification(remoteMessage); } } private void showCustomLocalNotification(RemoteMessage remoteMessage) { // 示例:构建并显示本地通知 // 从remoteMessage.getData()中提取标题、内容等字段 String title = remoteMessage.getData().get("title"); String content = remoteMessage.getData().get("body"); // 使用Android NotificationManager实现本地通知,代码略 // 确保已申请POST_NOTIFICATIONS权限 } }
步骤2:修改Android Manifest
在你的App Manifest中,注册自定义Service并替换Capacitor的默认服务:
- 先添加tools命名空间到根manifest标签:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
- 在application标签内注册自定义Service,使用
tools:node="replace"覆盖插件中的服务:
<service android:name="de.myDomainHere.ShufflechatFirebaseMessagingService" android:exported="false" tools:node="replace"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
关键说明
tools:node="replace"会让Android Manifest合并时,用你的自定义Service替换Capacitor插件中的同名Intent服务,确保系统触发你的服务。- 继承Capacitor的
MessagingService后,super.onMessageReceived()会保留原有逻辑,保证前台时JS能收到通知更新UI。 - 当
PushNotificationsPlugin.getPushNotificationsInstance() == null时,说明WebView未初始化(应用关闭/后台),此时可安全处理纯数据通知,比如触发本地通知。
验证方法
- 重新构建并安装应用。
- 发送纯数据通知,关闭应用后查看Logcat是否有
shuffleNotifServ的日志输出。 - 前台运行应用时,确认JS仍能正常接收通知更新UI。
内容的提问来源于stack exchange,提问作者traxx2012
相关产品推荐
相关产品推荐

