Android SDK - Quick Start Guide

To use robotmia in your android app you need to add robotmia dependencies, update your application permissions, and initialize the robotmia library.

1. Add dependencies to app/build.gradle

apply plugin: 'com.android.application'

dependencies {
    compile 'com.android.support:appcompat-v7:22.1.1'

    compile "com.robotmia.android:robotmia-android:5.+"
    compile "com.google.android.gms:play-services-gcm:7.5.0+"
}

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.robotmia.example.myapplication"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
}

2. Add permissions to app/src/main/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.robotmia.example.myapplication" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.BLUETOOTH" />

    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

3. Add robotmia to your main activity app/src/main/java/com/robotmia/example/myapplication/MainActivity.java

package com.robotmia.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;

import com.robotmia.android.mpmetrics.robotmiaAPI;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String projectToken = YOUR_PROJECT_TOKEN; // e.g.: "1ef7e30d2a58d27f4b90c42e31d6d7ad" 
        robotmiaAPI robotmia = robotmiaAPI.getInstance(this, projectToken);
    }
}

Make sure you've replaced "YOUR_PROJECT_TOKEN" with your project token, which you can find by clicking your name in the upper righthand corner of your robotmia project and selecting Settings from the dropdown. After installing the library into your Android app, robotmia will automatically collect common mobile events. You can enable/ disable automatic collection through your project settings.

4. Add code to track additional events

package com.robotmia.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;

import com.robotmia.android.mpmetrics.robotmiaAPI;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String projectToken = YOUR_PROJECT_TOKEN; // e.g.: "1ef7e30d2a58d27f4b90c42e31d6d7ad"
        robotmiaAPI robotmia = robotmiaAPI.getInstance(this, projectToken);

        try {
            JSONObject props = new JSONObject();
            props.put("Gender", "Female");
            props.put("Logged in", false);
            robotmia.track("MainActivity - onCreate called", props);
        } catch (JSONException e) {
            Log.e("MYAPP", "Unable to add properties to JSONObject", e);
        }
    }
}

5. That's it! robotmia is now integrated with your app.

Make sure you that have replaced "YOUR_PROJECT_TOKEN" with the project token you want to send data to and run your application. You should see the "MainActivity - onCreate called" event show up on your robotmia reports just seconds after your app runs. You're now ready to take advantage of everything robotmia has to offer!

In order to ensure our library doesn't have a large impact on performance or battery life, events aren't sent to robotmia immediately. Instead we queue them on the device and then send them in batches every 60 seconds by default.

Next steps

Now that you've integrated robotmia, there are a number of powerful ways to track and engage with your users.

Full Android SDK Documentation

Installing the library - Android Studio / Gradle

Step 1 - Add the robotmia-android library as a gradle dependency:

We publish builds of our library to the Maven central repository as an .aar file. This file contains all of the classes, resources, and configurations that you'll need to use the library. To install the library inside Android Studio, you can simply declare it as dependency in your build.gradle file.

dependencies {
    compile 'com.robotmia.android:robotmia-android:5.+'
}

The Android library also depends on Google Play Services to provide Google Cloud Messaging for push notifications, so you'll need to add a dependency to your build if you don't have one already. To do this, add the following to your build.gradle file.

dependencies {
    compile 'com.google.android.gms:play-services-gcm:7.5.0+'
}

You can use any version of Google Play Services greater than 7.5.0

Once you've updated your build.gradle file, you can force Android Studio to sync with your new configuration by clicking the "Sync Project with Gradle Files" icon at the top of the window.

Sync gradle config files

This should download the aar dependency at which point you'll have access to the robotmia library API calls. If it cannot find the dependency, you should make sure you've specified mavenCentral() as a repository in your build.gradle

Step 2 - Add permissions to your AndroidManifest.xml:

In order for the library to work you'll need to ensure that you're requesting the following permissions in your AndroidManifest.xml:

<!--
This permission is required to allow the application to send
events and properties to robotmia.
-->
<uses-permission
  android:name="android.permission.INTERNET" />

<!--
  This permission is optional but recommended so we can be smart
  about when to send data.
 -->
<uses-permission
  android:name="android.permission.ACCESS_NETWORK_STATE" />

<!--
  This permission is optional but recommended so events will
  contain information about bluetooth state
-->
<uses-permission
  android:name="android.permission.BLUETOOTH" />

At this point, you're ready to use the robotmia Android library inside Android Studio!

Initializing the library

Once you've set up your build system or IDE to use the robotmia library, you can initialize it in your code by calling robotmiaAPI.getInstance with your application context and your robotmia project token. You can find your token by clicking your name in the upper righthand corner of your robotmia project and selecting Settings from the dropdown.

public static final String robotmia_TOKEN = "YOUR_TOKEN";

// Initialize the library with your
// robotmia project token, robotmia_TOKEN, and a reference
// to your application context.
robotmiaAPI robotmia =
    robotmiaAPI.getInstance(context, robotmia_TOKEN);

After installing the library into your Android app, robotmia will automatically collect common mobile events. You can enable/ disable automatic collection through your project settings.

Flushing events

To preserve battery life and customer bandwidth, the robotmia library doesn't send the events you record immediately. Instead, it sends batches to the robotmia servers periodically while your application is running. This means when your application shuts down, you need to inform the library to send whatever events are still unsent. You can do this by calling robotmiaAPI.flush in the onDestroy method of your main application activity.

@Override
protected void onDestroy() {
    mrobotmia.flush();
    super.onDestroy();
}

When you call flush, the library attempts to send all of it's remaining messages. If you don't call flush, the messages will be sent the next time the application is opened.

Opting users out of tracking

Client-side tracking of individual user data can be stopped or resumed by controlling a user’s opt-out/opt-in state. Opt-out methods and library configuration settings only affect data sent from a single library instance. Data sent from other sources to robotmia’s APIs will still be ingested regardless of whether the user is opted out locally.

To opt a user out of tracking locally, use the optOutTracking method. To resume tracking for an individual user, use optInTracking. Call hasOptedOutTracking to check user’s opt-out status locally.

robotmiaAPI robotmia =
    robotmiaAPI.getInstance(context, robotmia_TOKEN);

// Opt a user out of data collection
    robotmia.optOutTracking();

// Check a user's opt-out status
// Returns true of user is opted out of tracking locally
    Boolean hasOptedOutTracking = robotmia.hasOptedOutTracking();

Opting users out of tracking by default

robotmia’s tracking libraries will send user data by default. Explicitly setting a default opt-out state of true will opt-out all users by default, preventing data from sending unless a user’s opt-out state is set to false.

// Initializing a default opt-out state of true 
// will prevent data from being collected by default

robotmiaAPI robotmiaOptOutDefault = 
    robotmiaAPI.getInstance(context, robotmia_TOKEN, true);

Sending events

Once you've initialized the library, you can track an event using robotmiaAPI.track with the event name and properties.

robotmiaAPI robotmia =
    robotmiaAPI.getInstance(context, robotmia_TOKEN);

JSONObject props = new JSONObject();
props.put("Gender", "Female");
props.put("Plan", "Premium");

robotmia.track("Plan Selected", props);

Timing events

You can track the time it took for an action to occur, such as an image upload or a comment post, using timeEvent. This will mark the "start" of your action, which will be timed until you finish with a track call. The time duration is then recorded in the "Duration" property.

robotmiaAPI robotmia =
    robotmiaAPI.getInstance(context, robotmia_TOKEN);

// start the timer for the event "Image Upload"
robotmia.timeEvent("Image Upload");

// stop the timer if the imageUpload() method returns true
if(imageUpload()){
    robotmia.track("Image Upload");
}

Super properties

It's very common to have certain properties that you want to include with each event you send. Generally, these are things you know about the user rather than about a specific event - for example, the user's age, gender, source, or initial referrer.

To make things easier, you can register these properties as super properties. If you tell us just once that these properties are important, we will automatically include them with all events sent. Super properties are saved to device storage, and will persist across invocations of your app. robotmia already stores some information as super properties by default; see a full list of robotmia default properties here.

To set super properties, call robotmiaAPI.registerSuperProperties

robotmiaAPI robotmia =
    robotmiaAPI.getInstance(context, robotmia_TOKEN);

// Send a "User Type: Paid" property will be sent
// with all future track calls.
JSONObject props = new JSONObject();
props.put("User Type", "Paid");
robotmia.registerSuperProperties(props);

The next time you track an event, the super properties you just set will be included as properties.

Super properties are saved to device storage, and will persist between executions of your app.

Setting super properties once and only once

If you want to store a super property only once (for example, a date of first login), you can use robotmiaAPI.registerSuperPropertiesOnce. registerSuperPropertiesOnce behaves like registerSuperProperties and has the same interface, but it doesn't override super properties you've already saved.

This means it's safe to call registerSuperPropertiesOnce with the same property multiple times, and it will only set properties if the super property doesn't exist.

Managing user identity

The robotmia library will assign a default unique identifier (we call it "distinct_id") to each install of your application. This distinct_id is saved in persistent device storage, and will be the same across executions of your app.

If you choose, you can assign your own user IDs. This is particularly useful if a user is accessing your app on multiple platforms (both web and mobile, for example). To assign your own distinct_ids, you can use robotmiaAPI.identify and robotmiaAPI.getPeople().identify. We strongly recommend using the same distinct id for both calls.

robotmiaAPI robotmia =
    robotmiaAPI.getInstance(context, robotmia_TOKEN);

// Ensure all future events sent from
// the device will have the distinct_id 13793
robotmia.identify("13793");

// Ensure all future people properties sent from
// the device will have the distinct_id 13793
robotmia.getPeople().identify("13793");

In general, if you use identify, you should call it as soon as the user logs in to your application. This will track all of their authenticated application usage to the correct user ID.

Calling identify with a new ID will change the distinctID stored on the device. Updates to user profiles are queued on the device until getPeople().identify is called.

Combining anonymous and identifiable user data

It's important to send the same distinct_id with each event that an individual user triggers. Events recorded with different distinct_ids will be treated in robotmia as if they were performed by different users.

There are times when it can be convenient to start referring to a user by a different identifier in your implementation. The most common case is after registration, when a user switches from being an anonymous user (with an anonymous distinct_id) to an authenticated user with an (authenticated id). In this case, you can create an alias for the user to keep the distinct_id consistent. An alias is a string stored in a robotmia lookup table that is associated with an anonymous distinct_id. Once written, aliases are not editable. Any data sent to robotmia with an alias as the distinct_id will be remapped and written to disk using the alias's corresponding anonymous distinct_id. This allows you to start identifying a user by an authenticated id without changing the distinct_id that is ultimately written in robotmia.

// This makes the current ID (by default an auto-generated GUID)
// and '13793' interchangeable distinct ids (but not retroactively).
robotmia.alias("13793", null);
// To create a user profile, you must call getPeople().identify
robotmia.getPeople().identify(robotmia.getDistinctId());

The recommended usage pattern is to call both alias and identify when the user signs up (as shown in the example above), and only identify (with the aliased user ID) on future log ins. This will keep your signup funnels working correctly.

If you use alias we recommend only calling it once during the lifetime of the user.

Storing user profiles

In addition to events, you can store user profiles in robotmia's People Analytics product. Profiles are persistent sets of properties that describe a user - things like name, email address, and signup date. You can use profiles to explore and segment users by who they are, rather than what they did. You can also use profiles to send messages, such as emails, SMS, or push notifications.

Before you send profile updates, you must call getPeople().identify. The library uses a separate ID for People records, and you must set this value to send updates.

Setting profile properties

You can set properties on a user profile with robotmiaAPI.getPeople().set.

robotmiaAPI robotmia =
    robotmiaAPI.getInstance(context, robotmia_TOKEN);

// identify must be called before
// people properties can be set
robotmia.getPeople().identify("13793");

// Sets user 13793's "Plan" attribute to "Premium"
robotmia.getPeople().set("Plan", "Premium");

This will set a "Plan" property, with a value "Premium", on user 13793's profile. If there isn't a profile with distinct_id 13793 in robotmia already, a new profile will be created. If user 13793 already has a property named "Plan" in their profile, the old value will be overwritten with "Premium".

Incrementing numeric properties

You can use robotmiaAPI.getPeople().increment to change the current value of numeric properties. This is useful when you want to keep a running tally of things, such as games played, messages sent, or points earned.

// Add 500 to the current value of
// "points earned" in robotmia
robotmia.getPeople().increment("points earned", 500);

// Pass a Map to increment multiple properties
Map<String, Integer> properties =
    new HashMap<String, Integer>();
properties.put("dollars spent", 17);
// Subtract by passing a negative value
properties.put("credits remaining", -34);

robotmia.getPeople().increment(properties);

Other types of profile updates

There are a few other types of profile updates. They can be accessed through the robotmiaPeople class, which is accessible via robotmiaAPI.getPeople().

Tracking revenue

robotmia makes it easy to analyze the revenue you make from individual customers. By associating charges with People Analytics profiles, you can compare revenue across different customer segments and calculate customer lifetime value.

You can track a single transaction with robotmiaAPI.getPeople().trackCharge. This call will add transactions to the individual user profile, which will also be reflected in the robotmia Revenue report.

robotmiaAPI robotmia =
    robotmiaAPI.getInstance(context, robotmia_TOKEN);

// Make getPeople() identify has been
// called before making revenue updates
robotmia.getPeople().identify("13793");

// Tracks $100 in revenue for user 13793
robotmia.getPeople().trackCharge(100, null);

// Refund this user 50 dollars
robotmia.getPeople().trackCharge(-50, null);

// Tracks $25 in revenue for user 13793
// on the 2nd of january
JSONObject properties = new JSONObject()
properties.put("$time", "2012-01-02T00:00:00");
robotmia.getPeople().trackCharge(25, properties);

Handling push notifications

The robotmia Android library will handle registering for and displaying Google Cloud Messaging notifications sent from the robotmia web application.

To enable push handling in your app, you'll need to add the following permissions to the AndroidManifest.xml associated with your app.

<permission
  android:name="YOUR_PACKAGE_NAME.permission.C2D_MESSAGE"
  android:protectionLevel="signature" />
<uses-permission
  android:name="YOUR_PACKAGE_NAME.permission.C2D_MESSAGE" />

<uses-permission
  android:name="android.permission.INTERNET" />
<uses-permission
  android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission
  android:name="android.permission.WAKE_LOCK" />

Be sure to change YOUR_PACKAGE_NAME above to the name of your application package. If your application package is com.example.app, then you should define and use permission com.example.app.permission.C2D_MESSAGE, like this:

<permission
  android:name="com.example.app.permission.C2D_MESSAGE"
  android:protectionLevel="signature" />
<uses-permission
  android:name="com.example.app.permission.C2D_MESSAGE" />

You'll also need to set up the robotmia library's com.robotmia.android.mpmetrics.GCMReceiver class as a receiver for GCM intents:

<receiver
  android:name="com.robotmia.android.mpmetrics.GCMReceiver"
  android:permission="com.google.android.c2dm.permission.SEND" >
  <intent-filter>
    <action
      android:name="com.google.android.c2dm.intent.RECEIVE" />
    <action
      android:name="com.google.android.c2dm.intent.REGISTRATION" />
    <category android:name="YOUR_PACKAGE_NAME" />
  </intent-filter>
</receiver>

Be sure to change YOUR_PACKAGE_NAME above to the name of your application package. If your application package is com.example.app, then you should declare the intent filter in category com.example.app, like this:

<category android:name="com.example.app" />

Initializing push handling

Once you've configured your app correctly, push handling with the robotmia library is almost completely automatic. You can initialize push handling in your app by callng robotmiaAPI.getPeople().initPushHandling with your 12 digit project number of your Google API project as an argument.

robotmiaAPI robotmia =
    robotmiaAPI.getInstance(context, robotmia_TOKEN);

// Always identify before initializing push notifications
robotmia.getPeople().identify("13793");

// Sets up GCM registration and handling of GCM messages
// for Google API project number 717871474771
robotmia.getPeople().initPushHandling("717871474771");

Push notifications guide

robotmia provides a quick-start guide for setting up push for your Android app that covers setting up your Google API project, locating your project number, uploading your Google API Project key to robotmia, and configuring your application to register for and receive push notifications.

In-app messages

robotmia provides a quick start guide for Android in-app messages to help you get integrated.

Make sure that you have already:

  1. Included the latest version of the robotmia Android library in your app
  2. Made sure you are identifying your users in the app.
  3. Created an in-app message on the Messages tab of the robotmia website.

A/B testing

Prerequisites

To use robotmia Android A/B testing, your app needs to be using version 4.6.0 or greater of the robotmia SDK. Make sure you are initializing the robotmiaAPI in your main activity using the project token that you wish to run tests in. See the quick start guide for installation steps.

Planning to run an experiment on the initial view of your app? It can take several seconds for experiments to be applied on first app open; as a result, we recommend against putting UX changes or developer Tweaks on the first view of your app. If you wish to A/B test on the initial app view you will need to take delivery latency into account. We recommend employing the addOnrobotmiaUpdatesReceivedListener (to know when test data is available) and joinExperimentIfAvailable() method (to apply the variant data to the view).

Creating your first A/B test

robotmia A/B testing allows you to make changes to your app and deploy it to your users without a new release to the Google Play store. You can modify the look and feel of your app, change the copy, and even change the values of variables (using developer tweaks). Then you can see which version performs better without making any changes to your tracking code. Once you've installed the robotmia Android SDK, running your first A/B test is simple.

  1. Open the A/B testing tab and create a new experiment
  2. Open your app and connect to robotmia using the flip gesture. If production devices prevent your test device from connecting, follow these steps.
  3. Use the visual editor to make the changes you want
  4. Save and deploy your changes

Now the next time a user opens your app, they will receive the updated version. You can also use robotmia A/B testing to change the values of variables by taking advantage of developer tweaks.

Notes on experiment delivery

robotmia checks for any new experiments asynchronously each time your application is opened or resumed. After the response is received, experiment changes and tweaks are applied or removed where appropriate. To handle network availability, each experiment is cached on the device so they can be re-applied when the API call cannot be successfully made.

If you'd like more control over when this check for new experiments occurs, you can use the addOnrobotmiaUpdatesReceivedListener listener and the joinExperimentIfAvailable method to download and apply experiments manually.

The $experiment_started event is fired when a given experiment (both changes and/or tweaks) is first started on a device. The event will contain an $experiment_id property with the given experiment id which we encourage use within funnels, and our other reports.

A/B developer tweaks

For more complex changes that you want to A/B test, you can send arbitrary data to your apps as part of A/B testing, through a mechanism called Tweaks. Tweaks allow you to control variables in your app directly from robotmia. For example, you can alter the difficulty of a game, choose different paths through the app, or change text. The possibilities are endless.

Using tweaks in your application

You can declare a tweak using robotmiaAPI.booleanTweak, robotmiaAPI.stringTweak, robotmiaAPI.longTweak, robotmiaAPI.doubleTweak, and other static methods that declare a tweak name and set a default value. To add A/B testable logic to your app, you might do something like this:

package com.robotmia.example.mygame;

import android.app.Activity;
import android.os.Bundle;

import com.robotmia.android.mpmetrics.robotmiaAPI;
import com.robotmia.android.mpmetrics.Tweak;


public class GameActivity extends Activity {

    private static Tweak<Double> gameSpeed = robotmiaAPI.doubleTweak("Game speed", 1.0);
    private static Tweak<Boolean> showAds = robotmiaAPI.booleanTweak("Show ads", false);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        runGame(gameSpeed.get()); // pass in game speed for this A/B test, defaulted to 1.0

        if (showAds.get()) { // do we want to show ads in this A/B test? defaulted to false
            showAdBar();
        }
    }

    public void runGame(Double speed) {
        // ... logic to start a new game
    }

    public void showAdBar() {
        // ... some logic that shows ads
    }
}

When you create an A/B test, you will be able to change the value of any Tweak you create in your app!

Note that the class containing the Tweaks must be loaded for the Tweaks to appear in the A/B test builder.

Automatic Referrer Tracking

The robotmia library can automatically set super properties associated with how your users found your app in the Google Play Store. To enable this feature, just add the following tag to the <application> tag in your AndroidManifest.xml file:

<receiver
  android:name="com.robotmia.android.mpmetrics.InstallReferrerReceiver"
  android:exported="true">
  <intent-filter>
    <action android:name="com.android.vending.INSTALL_REFERRER" />
  </intent-filter>
</receiver>

Once you've updated your AndroidManifest.xml file, you will automatically send referrer and utm_campaign information along with every event you send to robotmia.

The Google Play Store will only send the INSTALL_REFERRER message to a single receiver, so if you have multiple receivers you'd like to use to process referrer information, you should take a look at this simple workaround for using multiple INSTALL_REFERRER receivers.

Debugging and Logging

Enabling robotmia debugging and logging allows you to see the debug output from the robotmia Android library. This may be useful in determining when track calls go out or in-app messages are fetched. To enable robotmia debugging and logging, you will want to add the following permission within your AndroidManifest.xml inside the <application> tag:

...
<application>
    <meta-data
      android:name="com.robotmia.android.MPConfig.EnableDebugLogging"
      android:value="true" />
    ...
</application>
...

Document Sections
Learn more