Martin
Martin

Reputation: 2914

FirebaseMessagingService is not called on app start

I want to use FirebaseMessagingService to handle push notifications from the server. But there is not called onCreate function at the start. I thought that this service is initialized automatically when the app starts. Also, I started to send testing notification from firebase cloud messaging but it didn't work.

    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))
        }
    }
}

Manifest:

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

Upvotes: 7

Views: 4482

Answers (1)

Saiful Islam
Saiful Islam

Reputation: 1269

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

Upvotes: 7

Related Questions