Getting Started

The Android SDK is designed to support all Android devices and tablets, including Amazon Fire TV.

Create an Input

To send data from your Android app to your mParticle workspace input, you need an API key and secret. In the mParticle dashboard, navigate to Setup > Inputs and select the Android (or Fire) platform. From here you will be able to create a key and secret. Reference the guide section for information on creating inputs.

Add SDK Dependencies

mParticle’s Android SDK is powered by a “core” library, which supports mParticle’s server-side integrations and audience platform. You can add the core SDK via Maven Central or jCenter. Please follow the releases page on Github to stay up to date with the latest version.

Add the following dependencies to your app’s build.gradle:

dependencies {
    implementation 'com.mparticle:android-core:5+'

    // Required for gathering Android Advertising ID (see below)
    implementation 'com.google.android.gms:play-services-ads-identifier:16.0.0'

    // Recommended to query the Google Play install referrer
    implementation 'com.android.installreferrer:installreferrer:1.0'
}

Google Play Services Ads

The Google Play Services Ads framework is necessary to collect the Android Advertising ID (also known as Google Advertising ID). AAID collection is required by all attribution and audience integrations, and many other integrations. Include the com.google.android.gms:play-services-ads-identifier artifact, a subset of Google Play Services. The SDK will use reflection to determine if the necessary API is present at runtime.

Google Play Install Referrer

The Google Play “install referrer” string contains information for how the user arrived at your listing in Google Play prior to downloading your app. Collection of this information is recommended in order for attribution, deep linking, and analytics integrations to work properly. There are three ways to collect the install referrer string via mParticle:

  • (recommended) Add the com.android.installreferrer:installreferrer dependency to your application and the SDK will automatically gather it. This is the latest and most foolproof method
  • Listen for the legacy INSTALL_REFERRER broadcast as detailed below
  • Collect the install referrer string and pass it to mParticle yourself, see the complete API reference for more information

Play Install Referrer Library

Add the com.android.installreferrer:installreferrer library dependency to your app as in the example above and the Android SDK will automatically gather the install referrer string. This is the best way to collect the install referrer due to higher reliability than the intent broadcast. You can read more about the install referrer library here.

Single Receiver

Google Play will only deliver the INSTALL_REFERRER Intent to a single BroadcastReceiver - you should not have multiple receivers listening to this action in your AndroidManifest.xml file. This is a common mistake to be avoided - read below for your options.

In order for attribution, deep linking, and many other integrations to work properly, add the mParticle ReferrerReceiver to your manifest file within the <application> tag. The mParticle SDK will collect any campaign referral information and automatically forward it to kits (such as AppsFlyer, Kochava, and Adjust) and server-side integrations.

<receiver android:name="com.mparticle.ReferrerReceiver" android:exported="true">
    <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER"/>
    </intent-filter>
</receiver>

Multiple Receivers

If you already have your own receiver, or otherwise have multiple SDKs that require referral data, you must expose your own BroadcastReceiver in your manifest and then forward the received Intent to mParticle:

public class ExampleReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //process the Intent/send to other receivers as desired, and
        //send the Context and Intent into mParticle's BroadcastReceiver
        new com.mparticle.ReferrerReceiver().onReceive(context, intent);
    }
}

Firebase Cloud Messaging

If you’re integration push notifications via Firebase Cloud Messaging or the legacy Google Cloud Messaging, please see the Android push notification guide. If this is your first time instrumenting the mParticle SDK, we recommend continuing on and coming back to push notification instrumentation after completing the basic SDK integration below.

Initialize the SDK

You can configure the SDK with an MParticleOptions object and its respective builder class. At minimum you must supply your mParticle input key and secret via the credentials() builder API.

We recommend initializing the SDK in the onCreate() method of your app’s Application class. If you prefer, you may initialize the SDK in an Activity class - as long as the SDK is initialized prior to any other SDK API calls.

//import mParticle
import com.mparticle.MParticle;
import com.mparticle.MParticleOptions;

public class ExampleApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        MParticleOptions options = MParticleOptions.builder(this)
                .credentials("REPLACE ME WITH KEY", "REPLACE ME WITH SECRET")
                .build();
        MParticle.start(options);
    }
}
//import mParticle
import com.mparticle.MParticle
import com.mparticle.MParticleOptions

class ExampleApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        var options = MParticleOptions.builder(this)
            .credentials("REPLACE ME WITH KEY", "REPLACE ME WITH SECRET")
            .build()
        MParticle.start(options)
    }
}

Verify connection

Install and open a test build of your app on a device or emulator. Your app should immediately begin uploading installation and session data and you’ll see that data arriving in the live stream almost immediately:

If you don’t see data in the live stream, check that you’ve correctly copied your API key and secret, and look in your logcat console for any errors logged by the mParticle SDK. Reference the guide section for more information on the live stream.

Kit Integrations

Several integrations require additional client-side add-on libraries called “kits.” Some kits embed other SDKs, others just contain a bit of additional functionality. Kits are designed to feel just like server-side integrations; you enable, disable, filter, sample, and otherwise tweak kits completely from the mParticle platform UI. Reference the kit documentation for information on kits.

SDK Configuration

Many other functions of the SDK are customizable via MParticleOptions, a few of which are documented below. Reference the complete API Reference for all of the configuration options.

Identify Request

The SDK will automatically initialize with the most recent user identities from the most recently active user. You may override this by including an identity request via the identify API of your MParticleOptions object:

MParticleOptions.Builder options = MParticleOptions.builder(this);
options.identify(identityRequest);
var options = MParticleOptions.builder(this)
options.identify(identityRequest)

See the IDSync documentation for more information on building a complete identity request.

Environment

All data sent into an mParticle input must be marked as either “development” or “production”. The SDK attempts to detect the environment by based on whether the Android APK is “debuggable” according to its AndroidManifest.xml, setting it to development-mode when the API is debuggable.

In addition to uploading data as development, the SDK will also adjust some of its functionality to allow for a faster integration process:

  • In development mode, data is uploaded every 10 seconds, rather than the configurable upload interval
  • In development mode, the SDK will throw IllegalArgumentException and IllegalStateException exceptions when invalid objects are passed to its APIs, such as the IDSync and commerce APIs.
  • While in development mode, log level is configurable. See below for more information.

You can override the environment in your MParticleOptions object:

MParticleOptions.Builder options = MParticleOptions.builder(this);
options.environment(MParticle.Environment.Production);
var options = MParticleOptions.builder(this)
options.environment(MParticle.Environment.Production)

All development data will appear in your workspace’s live stream. In order to see production data, log into the mParticle platform, navigate to live stream, select your app, and filter on the appropriate devices based on Google Ad ID (GAID).

Log Level

Development Logs

The SDK log level is only respected while in development mode, which you can configure via the loglevel MParticleOptions object:

MParticleOptions.Builder options = MParticleOptions.builder(this);
options.logLevel(MParticle.LogLevel.VERBOSE);
var options = MParticleOptions.builder(this)
options.logLevel(MParticle.LogLevel.VERBOSE)

Production Logs

For production builds, you must manually enable logging using the adb setprop command with the “mParticle” tag:

adb shell setprop log.tag.mParticle VERBOSE

Reference the Android development documentation for more information on issuing adb commands.

Event Upload Interval

To save bandwidth and device battery, mParticle does not upload each event as it is recorded. Instead, events are assembled into batches and uploaded based on specific triggers. When a trigger is fired, the SDK will:

  • Query for the current events stored in a dedicated SQLite database table
  • Assemble batches of events, enriching the batch with user, device, and other application state information
  • Store each batch in a different, dedicated SQLite table, and delete the respective events from the events table
  • Attempt to upload each batch by order of creation, including batches from previous sessions.
  • Failed uploads will be continously retried whenever the trigger next fires, and batches are individually deleted from the device only upon successful upload.

The following will trigger SDK batch creation and upload:

  • When the app is opened first time to ensure that install events are immediately available
  • When the app is sent to background
  • When a commerce event is recorded
  • When the mParticle session ends - this will be after a user navigates away from your app according to the configured session timeout
  • After the configured upload interval (see below)
  • When the manual upload API is invoked (see below)

Configured Upload Interval

You can configure the regular upload trigger:

MParticleOptions.Builder options = MParticleOptions.builder(this);
options.uploadInterval(60)
var options = MParticleOptions.builder(this)
options.uploadInterval(60)

Force an Event Upload

You can also force an upload trigger with the upload method:

MParticle.getInstance().upload();
MParticle.getInstance().upload()

Was this page helpful?