In-App Messaging

In-App Messaging (IAM) module allows app developers to easily configure and display notifications within their app.

In-App Messaging Sample

This page covers:

Requirements

Supported Android Versions

This SDK supports Android API level 23 (Marshmallow) and above.

In-App Messaging Subscription Key

You must have a subscription key for your application from IAM Dashboard.

SDK Integration

#1 Include Maven Central repo in your project, this should be added in your project root build.gradle file.

allprojects {
    repositories {
        mavenCentral()
    }
}

#2 Add InAppMessaging SDK in your project dependencies.

Note: InAppMessaging SDK only uses AndroidX libraries. Host apps should migrate to AndroidX to avoid duplicate dependencies.

dependencies {
    implementation 'io.github.rakutentech.inappmessaging:inappmessaging:${latest_version}'
}

Please refer to Changelog section for the latest version.

#3 Target and compile SDK version to 33 or above.

Note: It is required to target and compile to SDK version 33 or above.

android {
    compileSdkVersion 33

    defaultConfig {
    // Defines the minimum API level required to run the app.
    minSdkVersion 23
    // Specifies the API level used to test the app.
    targetSdkVersion 33
    }
}

#4 Adding subscription ID and config URL.

It is required set your app’s subscription key and config endpoint URL using one of these methods:

<meta-data
    android:name="com.rakuten.tech.mobile.inappmessaging.subscriptionkey"
    android:value="change-to-your-subsrcription-key"/>

<meta-data
    android:name="com.rakuten.tech.mobile.inappmessaging.configurl"
    android:value="change-to-config-url"/>
InAppMessaging.configure(context = this,
                         subscriptionKey = "change-to-your-subsrcription-key",
                         configUrl = "change-to-config-url")

Note: The runtime configuration takes precedence over build-time configuration.

If you want to enable debug logging in In-App Messaging SDK (tags begins with “IAM_”), add the following meta-data in AndroidManifest.xml file.

<meta-data
    android:name="com.rakuten.tech.mobile.inappmessaging.debugging"
    android:value="true"/>
Field Datatype Manifest Key Optional Default
Subscription Key String com.rakuten.tech.mobile.inappmessaging.subscriptionkey ✅ (if using runtime configuration) 🚫
Config URL String com.rakuten.tech.mobile.inappmessaging.configurl ✅ (if using runtime configuration) 🚫
Debugging boolean com.rakuten.tech.mobile.inappmessaging.debugging false

Enable and disable the SDK remotely

We recommend, as good engineering practice, that you integrate with a remote config service so that you can fetch a feature flag, e.g. Enable_IAM_SDK, and use its value to dynamically enable/disable the SDK without making an app release. There are many remote config services on the market, both free and paid.

#5 Creating UserInfoProvider.

Create a new class in your project that implements the following class:

com.rakuten.tech.mobile.inappmessaging.runtime.UserInfoProvider

This class serves the purpose of providing basic user information such as user ID, Access Token, and ID Tracking Identifier at runtime. These user information are used by the SDK for campaigns targeting specific users.

class AppUserInfoProvider : UserInfoProvider {

    // This method is optional for Kotlin class
    // If Access Token will not be used, no need to override this method (i.e. default value is "")
    override fun provideAccessToken(): String? {
        return accessToken
    }

    // This method is optional for Kotlin class
    // If User ID will not be used, no need to override this method (i.e. default value is "")
    override fun provideUserId(): String? {
        return userId
    }

    // This method is optional for Kotlin class
    // If ID tracking identifier will not be used, no need to override this method (i.e. default value is "")
    override fun provideIdTrackingIdentifier(): String? {
        return idTrackingIdentifier
    }
}

To help IAM identify users, please keep user information in the preference object up to date. After logout is complete, please ensure that all UserInfoProvider methods in the preference object return null or empty string.

Notes for Rakuten Developers:

#6 Configuring In-App Messaging SDK.

Host app should configure the SDK, then register the provider containing the user information.

In your Application class’ onCreate() method, add:

// Set optional lambda function callback.
// This can be used for analytics and logging of encountered configuration issues.
InAppMessaging.errorCallback = {
    Log.e(TAG, it.localizedMessage, it.cause)
}

// Configure API: configure(context: Context): Boolean
// In a Java app, this API is callable via `InAppMessaging.Companion.configure(context: Context)`.
val iamFlag = InAppMessaging.configure(context = this, // Required
                                       subscriptionKey = "change-to-your-subsrcription-key", // Optional, overrides the subscription ID from AndroidManifest.xml
                                       configUrl = "change-to-config-url", // Optional, overrides the config URL from AndroidManifest.xml
                                       enableTooltipFeature = true // Optional, enables/disables tooltip campaigns feature (disabled by default)
)
// use flag to enable/disable IAM feature in your app.
if (iamFlag) {
    InAppMessaging.instance().registerPreference(provider)
}

The preference object can be set once per app session. IAM SDK will read object’s properties on demand.

Preferences are not persisted so this function needs to be called on every launch.

Notes:

#7 Registering and unregistering activities.

Only register activities that are allowed to display In-App messages. Your activities will be kept in a WeakReference object, so it will not cause any memory leaks. Don’t forget to unregister your activities in onPause() method.

Please see Context feature section to have more control on displaying campaigns.

override fun onResume() {
    super.onResume()
    InAppMessaging.instance().registerMessageDisplayActivity(this)
}

override fun onPause() {
    super.onPause()
    InAppMessaging.instance().unregisterMessageDisplayActivity()
}

#8 Logging events

Host app can log events to InAppMessaging anywhere in your app.

These events will trigger messages with the same event based trigger. Upon receiving logged event, InAppMessaging SDK will start matching it with current campaigns immediately. After a campaign message’s trigger events are matched by the logged events, this message will be displayed in the current registered activity. If no activity is registered, it will be displayed in the next registered activity.

#9 See advanced features for optional behavior

Pre-defined event classes:

AppStartEvent

Host app should log this event on app launch from terminated state. Recommended to log this event in host app’s main activity’s Activity#onStart().

App Start Event is persistent, meaning, once it’s logged it will always satisfy corresponding trigger in a campaign. All subsequent logs of this event are ignored. Campaigns that require only AppStartEvent are shown once per app session.

class MainActivity : AppCompatActivity() {

    override fun onStart() {
        super.onStart()
        InAppMessaging.instance().logEvent(AppStartEvent())
    }
}

LoginSuccessfulEvent

Host app should log this every time the user logs in successfully.

InAppMessaging.instance().logEvent(LoginSuccessfulEvent())

PurchaseSuccessfulEvent

Host app should log this event after every successful purchase.

InAppMessaging.instance().logEvent(PurchaseSuccessfulEvent())

Custom event class:

CustomEvent

Host app should log this after app-defined states are reached or conditions are met.

Custom events can have attributes with names and values. Attributes can be integer, double, String, boolean, or java.util.Date type.

InAppMessaging.instance().logEvent(CustomEvent("search").addAttribute("keyword", "book").addAttribute("number_of_keyword", 1))

Please note: Logging events may trigger InAppMessaging SDK to update current session data if there were changes in the app’s user information (see UserInfoProvider section for details).

SDK Logic

Client-side opt-out handling

If user (with valid identifiers in UserInfoProvider class) opts out from a campaign, that information is saved in user cache locally on the device and the campaign won’t be shown again for that user on the same device. The opt-out status is not shared between devices. The same applies for anonymous user.

Client-side max impressions handling

Campaign impressions (displays) are counted locally for each user. Meaning that a campaign with maxImpression value of 3 will be displayed to each user (different identifiers in UserInfoProvider class) max 3 times. Campaign’s max impression number can be modified in the dashboard/backend. Then the SDK, after next ping call, will compare new value with old max impression number and add the difference to the current impression counter. The max impression data is not shared between devices. The same applies for anonymous user.

Advanced Features

#1 Campaign’s context

Contexts are used to add more control on when campaigns are displayed. A context can be defined as the text inside “[]” within an IAM portal “Campaign Name” e.g. the campaign name is “[ctx1] title” so the context is “ctx1”. Multiple contexts are supported. In order to handle defined contexts in the code an optional callback is called before a message is displayed:

InAppMessaging.instance().onVerifyContext = { contexts: List<String>, campaignTitle: String -> Boolean
    if /* check your condition e.g. are you on the correct screen to display this message? */ {
        true // campaign message will be displayed
    } else {
        false // campaign message won't be displayed
    }
}

#2 Close campaign API

There may be cases where apps need to manually close the campaigns without user interaction.

An example is when a different user logs-in and the currently displayed campaign does not target the new user.

It is possible that the new user did not close the campaign (tapping the ‘X’ button) when logging in. The app can force-close the campaign by calling the closeMessage() API.

InAppMessaging.instance().closeMessage()

An optional parameter, clearQueuedCampaigns, can be set to true (false by default) which will additionally remove all campaigns that were queued to be displayed.

InAppMessaging.instance().closeMessage(true)

Note: Calling this API will not increment the campaign’s impression (i.e not counted as displayed).

#3 Custom fonts for campaigns

The SDK can optionally use custom fonts on campaign header and body texts, and button texts. The default Android system font will be used if custom fonts are not added.

To use custom fonts:

  1. Add the font files, ttf or otf format, to the font resource folder of your app.
  2. To use custom font for the following campaign parts, define a string resource in the app’s res/values/string.xml:

Note: You can set the same font filename for the different string resources to use the same font.

...
├── res
     ├── font
          ├── your_app_font.otf // or ttf format
          ├── your_app_other_font.otf // or ttf format

in strings.xml:

    <string name="iam_custom_font_header">your_app_font</string>
    <string name="iam_custom_font_body">your_app_font</string>
    <string name="iam_custom_font_button">your_app_other_font</string>

#4 Push Primer

Starting v7.2.0, campaigns can be used as push primer to explain to users the context and advantages of enabling push notification in your app.

When the user taps the push primer button in the campaign, this will trigger the app to display the runtime push permission request.

There are two ways to handle the push primer button:

  1. Add a push primer callback

Add a callback in the the activity that you want to display the permission request dialog. The callback is called by the SDK when a push primer button is tapped by the user.

override fun onStart() {
  InAppMessaging.instance().onPushPrimer = {
    // add push permission request or other handlings here
    ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), <your request code>)
  }
}

// need to override this function to notify app when the user granted or denied the permission request
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
  when(requestCode) {
    <your request code> -> {
      // add checking if the permission request was granted or denied here
    }
  }
}
  1. Let SDK handle the permission request

If the push primer callback is not set, the SDK will send the push permission request if the device is running on Android 13 or higher.

The app only needs to override the onRequestPermissionsResult function to be notified when the user granted or denied the permission request. Please note the SDK uses its own request code (i.e. InAppMessaging.PUSH_PRIMER_REQ_CODE).

// need to override this function to notify app when the user granted or denied the permission request
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
  when(requestCode) {
    InAppMessaging.PUSH_PRIMER_REQ_CODE -> {
      // add checking if the permission request was granted or denied here
    }
  }
}

Note: Please make sure that Push Primer Campaigns are only triggered for devices with Android 13 or higher OS since push notification permission request is not available for devices running in lower OS versions.

#5 Push Primer Tracker

Starting v7.3.0, a new API can be used for tracking if user granted or denied push permission request from a Push Primer campaign.

The trackPushPrimer() API should be called upon receiving permission results on the onRequestPermissionsResult callback.

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
  when(requestCode) {
    InAppMessaging.PUSH_PRIMER_REQ_CODE -> { // or the request code used if push permission request is handled by the app via push primer callback
      InAppMessaging.instance().trackPushPrimer(permissions, grantResults)
    }
  }
}

Note: Please make sure that trackPushPrimer() API is only called for devices with Android 13 or higher OS since push notification permission request is not available for devices running in lower OS versions.

#6 Tooltip Campaigns

Tooltip feature is currently in beta testing; its features and behaviour might change in the future. Please refer to the internal guide for more information.

To enable tooltips you must set enableTooltipFeature flag to true when calling configure().

InAppMessaging.instance().configure(context = this,
                                    enableTooltipFeature = true)

Troubleshooting

Proguard ParseException

Caused by: java.io.IOException: proguard.ParseException: Unknown option '-if' in line 84 of file
This error will be thrown during compilation if `minifyEnabled = true`, and your Proguard version is below 6.0.
(click to expand) Recommendation: Update your project's Android Gradle Plugin to the latest version, it includes the latest version of Proguard.

Less optimal solution: Force Gradle to use the latest version of Proguard(https://sourceforge.net/p/proguard/discussion/182455/thread/89a4d63d/):

buildscript {
    ...
    configurations.all {
      resolutionStrategy {
        force 'net.sf.proguard:proguard-gradle:6.0.3'
        force 'net.sf.proguard:proguard-base:6.0.3'
      }
    }
}

Duplicate class ManifestConfig

Build Error: java.lang.RuntimeException: Duplicate class com.rakuten.tech.mobile.manifestconfig.annotations.ManifestConfig

(click to expand)

This build error could occur if you are using older versions of other libraries from com.rakuten.tech.mobile. Some of the dependencies in this SDK have changed to a new Group ID of io.github.rakutentech (due to the JCenter shutdown). This means that if you have another library in your project which depends on the older dependencies using the Gropu ID com.rakuten.tech.mobile, then you will have duplicate classes.

To avoid this, please add the following to your build.gradle in order to exclude the old com.rakuten.tech.mobile dependencies from your project.

configurations.all {
    exclude group: 'com.rakuten.tech.mobile', module: 'manifest-config-processor'
    exclude group: 'com.rakuten.tech.mobile', module: 'manifest-config-annotations'
}

Other Issues

Rakuten developers experiencing any other problems should refer to the Troubleshooting Guide on the internal developer documentation portal.

Frequently Asked Questions

Q: How do I send message for in staging or testing environment?

When creating campaigns, you can set the versions which the campaign will be applied to your app. You can set the versions to staging versions (ex. 0.0.1, 1.0.0-staging, 0.x.x, etc.)

Q: How many times In-App Message should be sent to device? Does it depends on Max Lifetime Impressions?

The max impression is handled by SDK and is bound to user per device.

  1. Scenario- Max impression is set to 2. User does not login with any ID. So It will be shown 2 times.
  2. Scenario- Max impression is set to 2. User login with any ID for 2 devices. It will show 2 times for each device.
  3. The campaign start time can be shown

Please refer to max impression handling for more details.

Q: Is the campaign displayed if ALL or ANY of triggers are satisfied?

All the events “launch the app event, login event, purchase successful event, custom event” work as AND. It will send to the device only all defined event are triggered.

Documents targeting Engineers:

Documents targeting Product Managers:

Changelog

7.4.0 (2023-04-24)

7.3.0 (2022-12-13)

7.2.0 (2022-09-28)

7.1.0 (2022-06-24)

7.0.0 (2022-04-25)

6.1.0 (2022-02-09)

6.0.0 (2021-12-03)

5.0.0 (2021-09-10)

4.0.0 (2021-08-04)

3.0.0 (2021-03-24)

2.3.0 (2021-02-24)

2.2.0 (2020-11-10)

2.1.0 (2020-09-18)

2.0.0 (2020-06-11)

1.4.0

1.3.0

1.2.0