【Android】FCM(Firebase Cloud Messaging)の通知をバックグラウンドでも処理する


前提

前回の記事↓の続きです。 kwn1125.hatenablog.com
こちらの記事↓を参考に実現できました。 zenn.dev

目標

バックグラウンドで通知を受信した時もコードで処理する。

実装

handleIntent

公式ドキュメントに記載されているonMessageReceivedを使った書き方をせず、handleIntentを使うことで実現できました。handleIntentを書いた状態だと、onMessageReceivedは実行されません。

package com.example.testapplication;

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.google.firebase.messaging.FirebaseMessagingService

class MyFirebaseMessagingService : FirebaseMessagingService() {
    companion object {
        private const val TAG = "MyFirebaseMessagingService"
    }

    override fun handleIntent(intent: Intent) {
        Log.d(TAG, "handleIntent")

        intent.extras?.also {
            showNotification(it)
        } ?: Log.w(TAG, "intent.extras is null")
    }

    private fun showNotification(extras: Bundle) {
        val notification = NotificationCompat.Builder(this, "channel_1")
                .setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(extras.getString("gcm.notification.title"))
                .setContentText(extras.getString("gcm.notification.body"))
                .build()
        val notificationManager = NotificationManagerCompat.from(this)
        notificationManager.notify(0, notification)
    }

    override fun onNewToken(token: String) {
        Log.d(TAG, "Refreshed token: $token")
    }
}


参考サイトには

Firebase SDK を 11.6.0 にすると FirebaseMessagingService#handleIntent が final になるので、上記のコードはコンパイルできません。11.4.2 では大丈夫です。

と記載されています(ここで言うFirebase SDKはおそらくfirebase-messagingのことだと思っています)。執筆時点の最新バージョンである下記のバージョンでhandleIntentを使うことができました。

implementation 'com.google.firebase:firebase-messaging-ktx:22.0.0'