FCM background notifications do not trigger custom Analytics event

Ouverte
#2,663 1 commentaire 0 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

Évaluation

Difficulté
4/5
Temps estimé
3-5 jours
Accessibilité débutants
25/100
Type d'issue
Bug
Clarté
À clarifier
Activité
À l'abandon
Stack technique
android, firebase, kotlin
Domaine
mobile-dev

Piste de recherche

Commencez par MyFirebaseMessagingService.onMessageReceived et comparez le comportement des payloads notification et data décrit dans les étapes de reproduction. Consultez la documentation sur la livraison en arrière-plan de Firebase Messaging et l’envoi des données Analytics, puis vérifiez si l’événement signalé apparaît lorsque l’application revient au premier plan. La tâche est terminée lorsqu’une cause est confirmée ou qu’un problème quickstart plus clair et reproductible est identifié.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Description

Description
I am trying to log a custom Analytics event from onMessageReceived in my FirebaseMessagingService when a background notification is delivered. However, the custom event is never showing up in Firebase DebugView or the Analytics dashboard. I suspect that onMessageReceived is not being called in the background or that the payload might not be set up correctly. I’d like help diagnosing why the custom event is not appearing.

Step 1: Describe your environment
  • Android device: Pixel 5 (example)
  • Android OS version: 12 (example)
  • Google Play Services version: 22.12.13 (example)
  • Firebase/Play Services SDK version:
    • Firebase Messaging: 23.0.0
    • Firebase Analytics: 21.2.0
      (examples—replace with your actual versions)
Step 2: Describe the problem
Steps to reproduce
  1. Create a subclass of FirebaseMessagingService (e.g., MyFirebaseMessagingService) that overrides onMessageReceived.
  2. In onMessageReceived, log a custom event using FirebaseAnalytics.logEvent(...) when a data payload is present.
  3. Send an FCM message from the Firebase Console or a server with both notification and data payloads.
  4. Put the app in the background.
  5. Wait for the notification to arrive, then check Firebase DebugView for the custom event.
Observed Results
  • The onMessageReceived method seems to run when the app is in the foreground (and the custom event appears in DebugView).
  • When the app is in the background, the custom event (notification_received_background) never appears in DebugView or in the Analytics dashboard.
  • It appears that onMessageReceived is not being triggered, or the event is not being uploaded in the background.
Expected Results
  • Even if the notification is received while the app is in the background, the custom event (notification_received_background) should be logged and appear in DebugView (after the app comes to the foreground to upload events).
Relevant Code
package com.example.myapplication

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.core.app.NotificationCompat
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.example.myapplication.extension.isAppInForeground

class MyFirebaseMessagingService : FirebaseMessagingService() {

    private val firebaseAnalytics: FirebaseAnalytics by lazy {
        Firebase.analytics
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        // Log data payload
        if (remoteMessage.data.isNotEmpty()) {
            Log.d("FirebaseMessagingService", "Data payload: ${remoteMessage.data}")
            // Log custom event
            logEventToFirebase("notification_received_background", "Android", "google.com")
        }

        val isInForeground = applicationContext.isAppInForeground()
        if (isInForeground) {
            logEventToFirebase("notification_user_foreground", "Android", "google.com")
        }

        // Show a local notification
        showNotification(remoteMessage, "Android", "google.com")
    }

    override fun onNewToken(token: String) {
        super.onNewToken(token)
        Log.d("FCM", "New FCM Token: $token")
    }

    private fun showNotification(
        remoteMessage: RemoteMessage,
        operatorName: String,
        subDomain: String
    ) {
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val channelId = "default_channel"

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "Default Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            notificationManager.createNotificationChannel(channel)
        }

        val tapIntent = Intent(this, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            putExtra("operator_name", operatorName)
            putExtra("sub_domain", subDomain)
        }
        val pendingTapIntent = PendingIntent.getActivity(
            this, 0, tapIntent, PendingIntent.FLAG_IMMUTABLE
        )

        val dismissIntent = Intent(this, NotificationDismissReceiver::class.java)
        val pendingDismissIntent = PendingIntent.getBroadcast(
            this, 1, dismissIntent, PendingIntent.FLAG_IMMUTABLE
        )

        val builder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(remoteMessage.data["title"] ?: "Title")
            .setContentText(remoteMessage.data["body"] ?: "Body")
            .setContentIntent(pendingTapIntent)
            .setDeleteIntent(pendingDismissIntent)
            .setAutoCancel(true)

        notificationManager.notify(0, builder.build())
    }

    private fun logEventToFirebase(eventName: String, operatorName: String, subDomain: String) {
        val params = Bundle().apply {
            putString("operator_name", operatorName)
            putString("sub_domain", subDomain)
        }
        firebaseAnalytics.logEvent(eventName, params)
    }
}
Langage dominant
Kotlin
Étoiles
9.3k
Forks
7.4k
Merge moyen
7 j 9 h
PR mergées (30 j)
6

Préparer son environnement

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de firebase/quickstart-android

Toutes les issues de firebase/quickstart-android

Issues similaires

Plus d'issues Kotlin

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.