Skip to main content

Android SDK

This guide explains how to integrate an mtribes Space into your Android application.

You'll learn how to synchronize changes from your Space into your codebase using our CLI's code generation, and how to use this code to control the UX of your end users.

Sample apps

Check out our sample app covering Android to fast-track your integration.


  1. An Android project ready to integrate with mtribes
  2. An mtribes Space with at least one Collection and one Experience
  3. The mtribes CLI installed
  4. Android code generated for your Space

Our SDK is designed to use in modern Android applications with support for backward compatibility, up to devices running API 21(Android 5.0).

Kotlin is treated as our first class language in the SDK with 100% Java interoperability in mind.

Generated code is basically an Android library module which contains Kotlin code. But don't worry if your app is written in Java, as we always try to keep the experience and compatibility intact.

We use RxJava2 for our asynchronous functionalities, which is the only supported method at present. We're working on providing more options in the future, for example: coroutines.

We only support AndroidX as support libraries are now deprecated.

Code integration#

With your Space code generated, you're ready to integrate mtribes into your Android application.

In the code examples which follow, we'll build out an example Space containing:

  1. A homepage Collection, which contains:
    1. A banner Experience
    2. A body Section, which supports:
      1. Hero Experience types
      2. Carousel Experience types

On successful completion, an Android library module will be generated. This newly generated module will be automatically added to your project's settings.gradle.


If run outside of your root directory, you'll need to add your generated module manually to your project settings.gradle

Module integration#

To see the module in your Android Studio project navigator,

  1. Run Sync Project with Gradle Files.
  2. Add the module dependency in your application build.gradle file just as the CLI prompts.
dependencies {    implementation project(":<module_name>")}

Module insights#

The generated Android module uses Kotlin with 100% Java interoperability in mind. We've made sure the integration experience for both languages are seamless.


Manually updating the version of the core library is not recommended. We suggest you always use the CLI to synchronize with the latest versions. The library cannot be used independently as we treat the CLI generated module and the library as a single entity.


With your Space configured and code generated, you can now import and use Experience instances to control elements of your UX.

The entry point to the mtribes platform is the Mtribes singleton class included within the generated module. With that comes the initialization functionality, which should be the first function you call in your application code.

The recommended way of invoking this is via the entry point of your app workflow, typically in the Application.onCreate() method, just before super.onCreate().

Client initialization#

The mtribes Client is a top-level object for configuring your mtribes SDK.

A Client instance is generated along with your Space integration code and can be accessed via Mtribes.client

Before using the SDK, first initialize the mtribes Client with the API key of the mtribes Environment you wish to target.

You can find Environment API keys under your Space settings page.

class MainApplication : Application() {    override fun onCreate() {        Mtribes.init(this, "YOUR_MTRIBES_API_KEY_GOES_HERE")        super.onCreate()    }}

Client configuration#

The mtribes Client will expose some optional settings. We've given these sensible defaults, but you can override them to further harmonize mtribes with your application.

Example: Disable session locking to enable live Section and Experience change events during a user session.

Mtribes.client.sessionLock = false

It's best to configure the Client before starting the session, but configuration can be adjusted at any time.

See the full list of client configuration options.

Session start#

Before accessing an Experience, it's important to start a session for the active user, so we can serve them personalized states.

We represent an mtribes session via the session object, which you can access via Mtribes.session

Anonymous user#

Start a session for an anonymous user.


This should be done:

  • on app launch if the user is anonymous
  • when a user logs out

It's important to wait for the completion of start() before accessing Experiences and Sections.

Logged in user#

Starting a session for a logged in user is similar to an anonymous one, except you must provide their unique identifier.


This should be done:

  • on app launch if the user is already logged in
  • when a user logs in

Again, wait for the completion of start() before accessing Experiences and Sections.

Personal Information

A user ID should be opaque and not personally identifiable. For example, you should avoid email addresses, social security numbers or similarly personal information.

If you don't have an opaque ID for a user, you can use a secure hashing algorithm such as SHA256 to encode it before passing it to session.start.

Contextual properties#

When starting a session, you can also provide fields with values specific to the user. These open up powerful Tribe targeting options in the mtribes platform.

Example 1: Start a session for an anonymous user with a contextual property of campaign.

Mtribes.session.start(    StartOptions(        fields = mutableMapOf("campaign" to campaignId)    ))

Example 2: Start a session for a logged in user with a contextual property of subscription.

Mtribes.session.start(    StartOptions(        userId =,        fields = mutableMapOf("subscription" to user.subscription)    ))

We currently support the following contextual property types.

  • Boolean: true or false
  • Number: e.g. 842, 0.332
  • String: e.g. "gold"
  • Date: ISO-8601 UTC string encoded timestamp e.g. "2020-12-02T02:45:02.076Z" This must include the date and time.
Property Limits

A maximum of 50 contextual properties can be active at one time. You can remove unused properties to make room for new ones in the contextual property settings page.

To avoid exceeding these limits or sending PII by mistake, we recommend selecting specific contextual properties to include when starting a session.

Experience access#

With the session primed, you can now check whether Experiences modeled in the Space are enabled for a user, and if so, what custom data properties have been defined for them.

// example of a render function in your app to present a Bannerfun renderBanner() {    // access the banner Experience from the homepage Collection    val banner = Mtribes.collections.homepage.banner    // only render the banner Experience if it's enabled        if (banner.enabled) {        // access customized data for the banner        val imageURL =        drawBanner(imageURL)    }}

Section iteration#

Sections contain a list of child Experiences defined at runtime by a Scheduler in the mtribes platform. You can iterate over these child Experiences and render each in turn, depending on its type.

Each Section defines its Supported Experience types enum. You can use these as switch cases/when expressions and render appropriately.

// example of a render function in your app to render// a dynamic list of UI elements in the body areafun renderBody() {    // access the body Section from the homepage Collection    val body = Mtribes.collections.homepage.body        // render each Experience of the Section in order    body.children.forEach { exp ->        // if an Experience is disabled we'll skip it        if (exp.enabled) {            when (exp::class) {                HomepageSection.Supported.HERO.type -> {                    drawHero(                }                HomepageSection.Supported.CAROUSEL.type -> {                    drawCarousel(                }            }        }    }}

Change events#

The state of an Experience or Section may change for a user during their session. You can monitor these changes and reflect them in your code.

Live updates

If you want published change events to fire during a user's session, then you'll need to set Client.sessionLock to false. By default, session locking is enabled to avoid published changes negatively impacting UX.

// access the members of the homepage Collectionval banner = Mtribes.collections.homepage.bannerval body = Mtribes.collections.homepage.body
// when the banner Experience changes, re-render itbanner.changed().subscribe { renderBanner() }
// when the body Section changes, re-render itbody.changed().subscribe { renderBody() }

Behavior tracking#

To help you gather user analytical behavioral patterns associated with an Experience, we expose a track function.

Analytic events support a Category and Action to help with event classification. These properties are encoded as a string in the format <category>/<action>. If only <action> is provided, a default Category of user is assumed.

Here are a few examples from our banner Experience above.

// access the banner Experience from the homepage Collectionval banner = Mtribes.collections.homepage.banner
// track an ad viewed event// category 'ad', action 'viewed'banner.track("ad/viewed")
// track a sign in event// category 'user' (default), action 'signed_in'banner.track("signed_in")
// optional details can be provided including// a contextual label and integer valuebanner.track("item/clicked",    AnalyticsEventDetails(label = "Winter Specials", value = 1))

Trusted identity#

Trusted Identity helps ensure the authenticity of users identified into your mtribes Space. View our comprehensive Trusted Identity guide to understand what this is and how to enable it.

Once you have a hashed user signature returned from your server, you should pass this as an option when starting a session for a logged in user.

Mtribes.session.start(    StartOptions(        userId =,        signed = signature  ))


You can enable internal SDK logs to get a deeper understanding of some workflows.

It's common practice to use a custom logger or a third party library like Timber for logging in an Android app code base. To make the logging experience seamless and consistent, you could use your own logger but conform to the MtLogger contract.

Following is an example where you can use Timber with Debug build configuration in your app.

if (BuildConfig.DEBUG) {    Mtribes.client.logger = object : MtLogger {        override fun error(tag: String, message: String, throwable: Throwable?) {            Timber.e(throwable, message)        }
        override fun info(tag: String, message: String) {            Timber.i(message)        }
        override fun warn(tag: String, message: String) {            Timber.w(message)        }    }}

Configuration options#

See below a list of all available client configuration options.


public final var sessionLock: Boolean

Defaults to true.

Determines whether the session lock cache is enabled or not.

When true, the default backing store of the cache will be memory. This means app refreshing will cause the cache to be purged, and updated Experience and Section states to be made available.

When set to 'false', all session caching is disabled. Published updates from mtribes will be pushed in real-time to connected clients.

We’d recommend you only use this in development, or when dealing with scheduled updates that need to be real-time. In all other cases, this can negatively impact the user experience, as published changes can alter the UI a user is currently engaging with.


public final var waitForMsec: Int

Defaults to 1200 milliseconds (1.2 seconds).

When session.start() is called, a network request is made to prime the session with Experience and Section states for the user.

This returns a Rx.Single which should be awaited until the session is ready to be accessed.

The priming request is designed to return quickly, however, poor network conditions may impact the response time.

To ensure that UX is not adversely impacted due to unexpected network delays, you can set waitForMsec to cap the number of milliseconds before the Single is complete and the application can begin accessing Experience and section states.

If the defined wait time has elapsed, then accessing the session's Experience and Section states will target code generated fallbacks. In the case that the same user was recently active, their session will target previously primed session states.

Priming will continue in the background if wait time elapses and populate the session state once loaded.


public final var userTracking: Boolean

Defaults to true.

Determines whether user behavioral tracking events may be sent to the mtribes platform.

Analytics events are needed to support meaningful insights and intelligent targeting decisions in mtribes.

Set this option to false if the user did not give tracking consent.


public final var includeTribes: Boolean

Defaults to false.

When true, Tribes for the current user will be evaluated when their session starts. Any Tribes the current user belongs to will have their IDs exposed via session.tribeIds


public final var logger: MtLogger

Sets a custom logger to consume and manage internal logs from the SDK.