Guides
Guides

Android Integration

Integration instructions for Android Apps using Java

📘

Note

The following steps assume you have access to the Marigold Platform, the latest version of either Android Studio or Eclipse with ADT installed, and are targeting at least Android API level 21 (Lollipop-5.0) – The Marigold SDK will not work on earlier versions of Android.

You can find our API documentation here:

Javadoc

KDoc

Android Studio

Edit the build.gradle file for your application (Module: app) and add the following repositories, dependencies and plugins:

repositories {
    maven {
        url "https://github.com/sailthru/maven-repository/raw/master/"
    }
}

dependencies {
    // Append this line to the dependencies section
    implementation 'com.marigold.sdk:marigold:21.+'
}
// This should be at the bottom of the file
apply plugin: 'com.google.gms.google-services'
plugins {
    id("com.google.gms.google-services")
}

repositories {
    maven {
        url = uri("https://github.com/sailthru/maven-repository/raw/master/")
    }
}

dependencies {
    // Append this line to the dependencies section
    implementation("com.marigold.sdk:marigold:21.+")
}

📘

Multidex

When integrating any 3rd party library with Android, you may run into issues of exceeding 65,000 methods. It's best to enable Multidex to support this limitation. Read more here

📘

Note

Using 10.+ for the version part of the dependencies will always get the latest minor version of the Marigold 10.x SDK. This will keep you up to date with minor upgrades to the SDK. Alternatively, you can specify this explicitly to stay on a certain version.

The google services plugin must be applied at the bottom of the app level build.gradle file. The Google Services dependency must also be added to the project level build.gradle file:

buildscript {
    dependencies {
        classpath 'com.google.gms:google-services:4.0.1'
    }
}

You will also need to ensure that the google-services.json file for your project has been added to the root directory of your Android app module (note that this is the root of the app, not the root of the project). If you have not yet created a Firebase Console project for your application, you should do so now here. The `google-services.json' file will be provided during the setup process. If you have already setup a project, the file can be downloaded from the Firebase Console from the project settings page:

In the General tab you should be able to find your app in the 'Your apps' section. You should then be able to download the JSON file from the 'Download the latest config file' section:

More information about adding the the google-services.json file to your app can be found in Google's developer documentation here.

Gradle Dependencies

The Android SDK utilises the Firebase Messaging library for push notifications. Since the library version is greater than version 15.0.0, there is a requirement that all Play Services and Firebase libraries included in your app also be at least version 15.0.0. This requirement was put in place by Google when they moved to semantic versioning from release 15.0.0 onwards. Further details can be found here.

The Firebase Messaging library and Play Services GCM library cannot be present in the same application, so you should ensure the Play Services GCM library is not present in your app dependencies.

If you do not include the Firebase Core library in your app dependencies you may receive a Java Compiler warning:

Warning: The app gradle file must have a dependency on com.google.firebase:firebase-core for Firebase services to work as intended.

Firebase Messaging notifications will still be received without adding the core library, so it is not required for the Marigold SDK to work correctly, however some of the additional functionality Firebase offers in the console may not work without it.

Connecting to Marigold

There is only one line of code that needs to go into your Application onCreate() method.
The Context that gets passed to Marigold should usually be this or getApplicationContext().

// Remember to add your import
import com.marigold.sdk.Marigold;

new Marigold().startEngine(getApplicationContext(), "SDK_KEY");
// Remember to add your import
import com.marigold.sdk.Marigold

Marigold().startEngine(applicationContext, "SDK_KEY")

Set your application to use your Application class in the manifest if you haven't already:

<application
        android:name=".MyApplication"
        ... >
  	...
</application>

Push Notification Permissions

From Android 13 (Tiramisu), new app installations will require explicit consent from the user before they can display push notifications.

📘

Note

Previously installed apps on devices that upgrade to Android 13 will retain their push notification permission.

This can be handled through the SDK by making use of the requestNotificationPermission method (available from SDK version 17.0.0). We recommend you display a screen explaining push notifications first and giving details about how they will enhance the user's experience using your app. You can then make the request through the SDK:

NotificationPermissionRequestResult requestResult = new Marigold().requestNotificationPermission(
    this, // the calling activity - required to request permissions
    true, // true if the calling activity provides the user with context for the permission request
)
val requestResult = Marigold().requestNotificationPermission(
    this, // the calling activity - required to request permissions
    true, // true if the calling activity provides the user with context for the permission request
)

This is a no-op on versions prior to Android 13. The result can be inspected to give an indication of whether the popup was displayed to the user. The user's response to the popup (if displayed) must be handled in the provided activity's onRequestPermissionsResult method:

@Override
public void onRequestPermissionsResult(
    int requestCode,
    @NonNull String[] permissions,
    @NonNull int[] grantResults
) throws SecurityException {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == Marigold.DEFAULT_NOTIFICATION_PERMISSION_REQUEST_CODE) {
        // Update the platform with the new notification settings
        new Marigold().syncNotificationSettings();
    }
}
override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<String>,
    grantResults: IntArray
) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)

    if (requestCode == Marigold.DEFAULT_NOTIFICATION_PERMISSION_REQUEST_CODE) {
        // Update the platform with the new notification settings
        Marigold().syncNotificationSettings()
    }
}

We recommend calling the SDK's syncNotificationSettings here to immediately update the platform with the new notification settings.

FirebaseMessagingService Implementation

Firebase sends tokens and notifications to the app through an implementation of the FirebaseMessagingService class. The SDK implements this class internally so your app can work with Firebase without having to create its own implementation. If, however, your app does have an implementation of the FirebaseMessagingService class then it will override the one that is implemented in the SDK. In this case in order for the SDK to function correctly you must pass the token and any received notifications to the SDK manually through the setDeviceToken() and handleNotification() methods:

import com.marigold.sdk.Marigold;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

/**
 * Your app's implementation of FirebaseMessagingService.
 */
public final class AppFirebaseService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
      
      	// Your code for handling notification
      
      	// Pass notification through to Marigold
        new Marigold().handleNotification(remoteMessage);
    }

    @Override
    public void onNewToken(String token) {
      	
      	// Your code for handling token
      
      	// Pass token through to Marigold
        new Marigold().setDeviceToken(token);
    }
}
import com.sailthru.mobile.sdk.SailthruMobile
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

/**
 * Your app's implementation of FirebaseMessagingService.
 */
class AppFirebaseService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {

        // Your code for handling notification

        // Pass notification through to Sailthru Mobile
        SailthruMobile().handleNotification(remoteMessage)
    }

    override fun onNewToken(token: String) {

        // Your code for handling token

        // Pass token through to Sailthru Mobile
        SailthruMobile().setDeviceToken(token)
    }
}

Notification Styling

One other optional small task you might want to do while integrating is to set the notification icon. Android notifications use a custom icon for your application that appears in the status bar. The Android documentation has a detailed explanation on how to create and style an icon for this use, but if you are using Android Studio the easiest way is to go File -> New -> Image Asset and select Notification Icons from the Icon Type drop-down. Change the Name to any value, for example ic_stat_notification.

Once you have your icon in your application, tell Marigold about it by creating a NotificationConfig object and calling setSmallIcon with the icon's drawable resource.

NotificationConfig config = new NotificationConfig();
config.setSmallIcon(R.drawable.ic_stat_notification);

new Marigold().setNotificationConfig(config);
val config = NotificationConfig()
config.setSmallIcon(R.drawable.ic_stat_notification)

Marigold().setNotificationConfig(config)

📘

NotificationConfig

NotificationConfig has many features to customize the behavior and style of push notifications. Check the javadoc for the full list of options.

Notification Channels

When targeting Android 8.0 (Oreo) and later, apps are required to define a NotificationChannel and send their notifications through it. Notification channels make it easier for users to define how notifications behave on their devices.

The Marigold SDK, on versions >= v5.0.0 will define a default notification channel called Notifications with a default priority. If you'd like to define your own default channel, however, you can define your own like so:

NotificationConfig config = new NotificationConfig();
NotificationChannel channel = new NotificationChannel("notifications_default", "Marigold Notifications", NotificationManager.IMPORTANCE_HIGH);
config.setDefaultNotificationChannel(channel);

Marigold marigold = new Marigold();

marigold.setNotificationConfig(config);
marigold.startEngine(getApplicationContext(), "SDK_KEY");
val config = NotificationConfig()
val channel = NotificationChannel("notifications_default", "Marigold Notifications", NotificationManager.IMPORTANCE_HIGH)
config.setDefaultNotificationChannel(channel)

val marigold = Marigold()

marigold.setNotificationConfig(config)
marigold.startEngine(applicationContext, "SDK_KEY")

If you use SDK 5.0.0 and above, default notification channel creation will occur even if your app does not target Android Oreo. If you would like to avoid default channel creation until your app targets Oreo, do not upgrade to this version.

Information on advanced usage of Notification Channels on Marigold can be found here.

Launch the App!

Finally, launch your application on your Android device or in the emulator.

Troubleshooting

Your device should be created with a device ID on the mobile platform. If you can't find it, try these steps:

  • Confirm that when you launch your Application that there are no "Marigold authentication failure" warnings in the log output. If you have warnings then this means you have supplied the wrong SDK key or you have not set up the Bundle Identifier correctly. Go back through the above steps.
  • Make sure you have an active internet connection.
  • Make sure that the device has Google Play Store installed.
  • If running on the Android emulator make sure that the AVD runs the Google APIs platform based on Android 4.2.2 or higher.
  • If you get this far and still have problems, re-trace over the steps above.

You have now completed this section and your Application should be correctly registering with Marigold.

Next Steps

  1. Setup Push Notifications for Android to ensure your users can receive push notifications.
  2. Setup in-app messages to enable Marigold's rich In-App Messages.
  3. Collect user data to help in segmenting and targeting your users based on their activity.