Android device mode

 

To enable its full functionality (like Push Notifications, InApp Messaging), there are still a couple of steps that you have to take care of in your Android app.

Build Settings

Add mavenCentral() repository in the project-level build.gradle file.

build.gradle
buildscript {
    repositories {
        mavenCentral()
    }
}

allprojects {
    repositories {
        mavenCentral()
    }
}

SDK Installation

Installing using Catalog

Integration using a Version Catalog is the recommended way of integration, refer to the Configure Version Catalog document to configure a catalog if not done already. Once you have configured the catalog add the dependency in the app/build.gradle file as shown below

build.gradle

    dependencies {
    	...
    	implementation(moengage.moengageSegmentIntegration)
    }
    

Alternatively, you can add the dependency directly as shown below.

Installing using Artifact Id

Add the following dependency in the app/build.gradle file.

build.gradle

    dependencies {
    	...
      implementation("com.moengage:moengage-segment-integration:$sdkVersion")
    }
    

replace $sdkVersion with the appropriate SDK version

MoEngage SDK depends on the following Jetpack libraries provided by Google for its functioning, make sure you add them if it isn't already present in the application.

build.gradle

    implementation("androidx.core:core:1.6.0")
    implementation("androidx.appcompat:appcompat:1.3.1")
    implementation("androidx.lifecycle:lifecycle-process:2.4.0")
    

Refer to the Android SDK Configuration documentation to know more about the build config and other libraries used by the SDK.

Register MoEngage with Segment SDK:

After adding the dependency, you must register the integration with Segment SDK. To do this, import the MoEngage
integration:

KotlinJava

    import com.segment.analytics.android.integrations.moengage.MoEngageIntegration
   

Add the following line:

KotlinJava

        val analytics = Analytics.Builder(this, "write_key")
            .use(MoEngageIntegration.FACTORY)
            .build()
        Analytics.setSingletonInstance(analytics)
   

How to Initialise MoEngage SDK:

Get APP ID from the Settings Page Dashboard --> Settings --> App --> General and initialize the MoEngage SDK in the Application class's onCreate()
Note: It is recommended that you initialize the SDK on the main thread inside onCreate() and not create a worker thread and initialize the SDK on that thread.

KotlinJava

    // this is the instance of the application class and "XXXXXXXXXXX" is the APP ID from the dashboard.
    val moEngage = MoEngage.Builder(this, "XXXXXXXXXXX")
	       .enablePartnerIntegration(IntegrationPartner.SEGMENT)
	       .build()
   MoEngage.initialiseDefaultInstance(moEngage)
   

Exclude MoEngage Storage File from Auto-Backup

Auto backup service of Andriod periodically backs up the Shared Preference file, Database files, and so on.

For more information, refer to Auto Backup.

The backup results in MoEngage SDK identifiers to be backed up and restored after re-install.
The restoration of the identifier results in your data being corrupted and the user not being reachable using push notifications.

To ensure data is not corrupted after a backup is restored, opt-out of MoEngage SDK storage files.

Refer to the Exclude MoEngage Storage File from Auto-Backup document to configure this.

Install/Update Differentiation

SDK needs support to enable the update by the user application or install the application.
You need to have a logic on the app side to distinguish between app INSTALL and UPDATE

KotlinJava
 
    //For Fresh Install of App
    MoEAnalyticsHelper.setAppStatus(context, AppStatus.INSTALL)

  // For Existing user who has updated the app
  MoEAnalyticsHelper.setAppStatus(context, AppStatus.UPDATE)

 

How To Push Notifications:

Copy the Server Key from the FCM console and add it to the MoEngage Dashboard(Not sure where to find the Server Key refer to Getting FCM Server Key). To upload it, navigate to MoEngage Dashboard --> Settings --> Channel --> Push --> Mobile Push --> Android and add the Server Key and package name.

 

WARNING

Ensure you add the keys both in the Test and Live environment.

Adding metadata for push notification

Metadata regarding the notification is required to show push notifications where the small icon and large icon drawable are mandatory.

For more information about API references for all the possible options, refer to NotificationConfig.

Use the configureNotificationMetaData() to transfer the configuration to the SDK.

Kotlin Java

    val moEngage = MoEngage.Builder(this, "XXXXXXXX")
     .configureNotificationMetaData(NotificationConfig(R.drawable.small_icon, R.drawable.large_icon)) 
     .enablePartnerIntegration(IntegrationPartner.SEGMENT)
     .build()
   MoEngage.initialiseDefaultInstance(moEngage)

Ensure that the SDK is initialized with the metadata in the onCreate() of the Application class for push notifications to work.

 

Notification Small Icon Guidelines

Notification small icon should be flat, pictured face on, and must be white on a transparent background.

Configuring Firebase Cloud Messaging

For showing Push notifications there are 2 important things

1. Registration for Push, i.e. generating push token.
2. Receiving the Push payload from Firebase Cloud Messaging(FCM) service and showing the notification on the device.
The above can either be handled by the application or MoEngage SDK. There is some configuration required based on whether the above-mentioned things are handled by the application or SDK.

Push Registration and Receiving handled by App

By default, MoEngage SDK attempts to register for push token, since your application is handling push you need to opt out of SDK's token registration.

How to opt out of MoEngage Registration?

To opt out of MoEngage's token registration mechanism disable token registration using configureFCM() API while configuring FCM in the MoEngage.Builder as described

Kotlin Java
val moEngage = MoEngage.Builder(this, "XXXXXXXX")
    	.configureNotificationMetaData(NotificationConfig(R.drawable.small_icon, R.drawable.large_icon, R.color.notiColor, null, true, isBuildingBackStackEnabled = false, isLargeIconDisplayEnabled = true))
    .configureFcm(FcmConfig(false))
    .build()
MoEngage.initialiseDefaultInstance(moEngage)

Pass the Push Token To MoEngage SDK

Your application would need to pass the Push Token received from FCM to the MoEngage SDK for the MoEngage platform to send out push notifications to the device.
Use the passPushToken() API to pass the push token to the MoEngage SDK.

Kotlin Java
MoEFireBaseHelper.getInstance().passPushToken(applicationContext,token)
 

NOTE

Ensure token is passed to MoEngage SDK whenever push token is refreshed and on application update. Passing the token on the application update is important for migration to the MoEngage Platform.

Passing the Push payload to the MoEngage SDK

To pass the push payload to the MoEngage SDK call the passPushPayload() API from the onMessageReceived() in the Firebase receiver.
Before passing the payload to the MoEngage SDK you should check if the payload is from the MoEngage platform using the isFromMoengagePlatfrom() helper API provided by the SDK.

Kotlin Java
if (MoEPushHelper.getInstance().isFromMoEngagePlatform(remoteMessage.data)){
    MoEFireBaseHelper.getInstance().passPushPayload(applicationContext, remoteMessage.data)
 }else{
    // your app's business logic to show notification
 }

Push Registration and Receiving handled by SDK

 

When token registration is handled by the SDK use firebase-messaging 23.0.0 or higher.

Add the following code to the manifest file:

AndroidManifest.xml

  <service android:name="com.moengage.firebase.MoEFireBaseMessagingService">
   <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT" />
   </intent-filter>
  </service>

 

 

IMPORTANT

At any point, your application manifest file should have only one service with intent filter com.google.firebase.MESSAGING_EVENT. If there is more than one service only the first service will receive the callback and MoEngage SDK might never receive the Push Payload resulting in poor delivery rates.

Callbacks

We recommend you to add the callbacks in the onCreate() of the Application class since these callbacks can be triggered even when the application is in the background.

Token Callback

When MoEngage SDK handles push registration it optionally provides a callback to the application whenever a new token is registered or the token is refreshed.

To get the token callback implement the TokenAvailableListener and register for the callback using MoEFireBaseHelper.getInstance().addTokenListener().

Non-MoEngage Payload

If you are using the receiver provided by the SDK in your application's manifest file, SDK provides a callback in case a push payload is received for any other server apart from MoEngage Platform.

To get a callback implement the NonMoEngagePushListener and register for the callback using MoEFireBaseHelper.getInstance().addNonMoEngagePushListener.

Declaring and configuring Rich Landing Activity:

Add the following snippet and replace [PARENT_ACTIVITY_NAME] with the name of the parent
activity; [ACTIVITY_NAME] with the activity name which should be the parent of the Rich Landing Page

XML
<activity
    android:name="com.moe.pushlibrary.activities.MoEActivity"
    android:label="[ACTIVITY_NAME]"
    android:parentActivityName="[PARENT_ACTIVITY_NAME]" >
 </activity>

You are now all set up to receive push notifications from MoEngage. For more information on features provided in MoEngage Android SDK refer to the following links:

Identify

Use Identify to track user-specific attributes. It is equivalent to tracking user attributes on MoEngage. MoEngage supports traits supported by Segment as well as custom traits. If you set traits.id, we set that as the Unique ID for that user.

Track

Use track to track events and user behavior in your app.
This will send the event to MoEngage with the associated properties. Tracking events is essential and will help you create segments for engaging users.

Reset

If your app supports the ability for a user to log out and log in with a new identity, then you’ll need to call reset for the Analytics client.

Sample Implementation

Refer to this GitHub repository for a sample implementation

Was this article helpful?
0 out of 0 found this helpful