Push Notification Tracking
Track push notification delivery and engagement with built-in support for Firebase Cloud Messaging (FCM) and Huawei Mobile Services (HMS).
Firebase Cloud Messaging (FCM)
Setup FCM Service
Create a service that extends FirebaseMessagingService:
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.b2metric.core.B2MetricSDK
import com.b2metric.core.domain.model.PushProvider
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
super.onNewToken(token)
// Register the token with B2Metric
B2MetricSDK.getInstance(this)
.registerPushToken(token, PushProvider.FCM)
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
// Track when user opens the notification
B2MetricSDK.getInstance(this)
.trackPushOpened(remoteMessage.data)
}
}
Get Initial FCM Token
Retrieve and register the FCM token when your app starts:
import com.google.firebase.messaging.FirebaseMessaging
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
if (task.isSuccessful && task.result != null) {
val token = task.result
B2MetricSDK.getInstance(this)
.registerPushToken(token, PushProvider.FCM)
}
}
Register Service in AndroidManifest.xml
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Huawei Mobile Services (HMS)
For apps distributed through Huawei AppGallery:
import com.huawei.hms.aaid.HmsInstanceId
import com.b2metric.core.domain.model.PushProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
lifecycleScope.launch {
try {
val token = withContext(Dispatchers.IO) {
HmsInstanceId.getInstance(applicationContext)
.getToken("YOUR_HUAWEI_APP_ID", "HMS")
}
B2MetricSDK.getInstance(this@MainActivity)
.registerPushToken(token, PushProvider.HMS)
} catch (e: Exception) {
Log.e("HMS", "Failed to get token", e)
}
}
Push Notification Events
push_token
Logged when registerPushToken() is called. Tracks which devices have successfully registered for push notifications.
push_opened
Logged when trackPushOpened() is called. Tracks when users interact with push notifications. All custom data from your FCM/HMS payload is automatically included as event properties.