应用程序启动时不会调用 FirebaseMessagingService

mar*_*337 7 android firebase firebase-cloud-messaging

我想使用 FirebaseMessagingService 处理来自服务器的推送通知。onCreate但一开始并没有调用函数。我认为该服务是在应用程序启动时自动初始化的。另外,我开始从 firebase 云消息发送测试通知,但它不起作用。

    class PushNotificationService: FirebaseMessagingService() {
    private lateinit var app: App

    override fun onCreate() {
        super.onCreate()
        App.log("FireBaseMsg: starting service")
        app = application as App
    }

    override fun onMessageReceived(msg: RemoteMessage?) {
        super.onMessageReceived(msg)

        App.log("FireBaseMsg: onMessageReceived")
        val pNotification = msg?.notification
        if (pNotification != null){
            val title = pNotification.title
            val text = pNotification.body

            if (!title.isNullOrEmpty() && !text.isNullOrEmpty()){
                val p = PushNotification(app, NOTIFICATION_CHANNEL_ID_PUSH, title = title, text = text)
                p.fireNotification(NOTIFICATION_ID_PUSH)
            }
        }
    }

    override fun onNewToken(token: String) {
        App.log("FireBaseMsg: Received token: $token")
        //REGISTER TOKEN
        app.regPushNotification(token, ::onNewTokenCallback)
    }

    private fun onNewTokenCallback(err: ApiCallError?){
        if (err == null){
            app.showToast(app.getString(R.string.notification_push_token_failed))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

显现:

<service
   android:name=".services.PushNotificationService"
   android:enabled="true"
   android:exported="false">
   <intent-filter>
       <action android:name="com.google.firebase.MESSAGING_EVENT" />
   </intent-filter>
</service>
Run Code Online (Sandbox Code Playgroud)

Sai*_*lam 6

我在实现 FirebaseMessagingService 类时遇到了同样的问题

我的解决方案

清单.xml

<service
        android:name=".MyFirebaseMessagingServices"
        android:enabled="true"
        android:permission="com.google.android.c2dm.permission.SEND"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
Run Code Online (Sandbox Code Playgroud)

如果您的清单服务部分一切正常,那么

  1. 卸载您的应用程序

  2. 文件 -> 使缓存无效/重新启动....

  3. 运行您的应用程序

  • 非常感谢您最后一节关于卸载、使缓存失效和重新启动,然后运行应用程序的内容!经过几个小时的研究,这是我通过“onNewToken”获得注册令牌以显示在日志中的唯一方法。我不需要清单中的其他内容,只需要官方 FirebaseMessagingService 文档/教程中所做的最低限度的声明。 (2认同)