首页 > 解决方案 > 应用启动时未调用 FirebaseMessagingService

问题描述

我想使用 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))
        }
    }
}

显现:

<service
   android:name=".services.PushNotificationService"
   android:enabled="true"
   android:exported="false">
   <intent-filter>
       <action android:name="com.google.firebase.MESSAGING_EVENT" />
   </intent-filter>
</service>

标签: androidfirebasefirebase-cloud-messaging

解决方案


I was in same problem while i am implementing FirebaseMessagingService class

My solution

Manifest.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>

If everything ok in your manifest service section then

  1. Uninistall your application

  2. File -> Invalidate Caches / Restart....

  3. Run your application


推荐阅读