Skip to main content

Implementation Examples

Example

The following code snippet shows how you can extend the FirebaseMessagingService class to pass the push token to the Adtrace SDK, and to update your push notification handling logic. If you are not sending your own push notifications, you can skip the override of the onMessageReceived method.

Important

When overriding onMessageReceived as shown below, be careful not to impact how the app handles your own push notifications. Be sure to test sending your own push notifications while your app is in the foreground after any modifications to the below push notification handling code.

import io.adtrace.sdk.AdTrace
import io.adtrace.sdk.Util
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

class MyFirebaseMessagingService : FirebaseMessagingService() {

override fun onCreate() {
super.onCreate()
// Fetch FCM token and set in Adtrace SDK
FirebaseMessaging.getInstance().token
.addOnCompleteListener {task ->
if (task.isSuccessful && task.result != null) {
AdTrace.setPushToken(task.result, applicationContext)
}
}
}

override fun onNewToken(token: String) {
super.onNewToken(token)

// Receive new FCM token and set in Adtrace SDK
AdTrace.setPushToken(token, applicationContext)
}

override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)

// Check if message has data payload
if (remoteMessage.data.isNotEmpty()) {
val payload: Map<String, String> = remoteMessage.data

// Check for Adtrace uninstall detection data message
if (Util.isAdTraceUninstallDetectionPayload(payload)) {
// No handling required for Adtrace data payload
} else {
// Handle other data payloads here
}
}

// Check if message has notification payload
remoteMessage.notification?.let {
// Handle notification payload here
}
}
}
  1. Initialize the Firebase instance in your application before initializing the Adtrace SDK.

Example

Here is an example of an application class in an Android project. You can see that it initializes the Firebase instance as soon as the app starts.

import android.app.Application
import io.adtrace.sdk.AdTrace
import io.adtrace.sdk.AdTraceConfig
import com.google.firebase.FirebaseApp

class MyApp : Application() {

override fun onCreate() {
super.onCreate()

// Initialize Firebase App
FirebaseApp.initializeApp(this)

// Configure Adtrace SDK
// Replace {YourAppToken} with your Adtrace app token
val appToken = "{YourAppToken}"
val environment = AdTraceConfig.ENVIRONMENT_PRODUCTION
val config = AdTraceConfig(this, appToken, environment)

// Initialize Adtrace SDK
AdTrace.onCreate(config)
}
}