Android SDK - Quick Start Guide

To use Mixpanel in your android app you need to add Mixpanel dependencies, update your application permissions, and initialize the Mixpanel 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.mixpanel.android:mixpanel-android:4.6.0"
    compile "com.google.android.gms:play-services:3.1+"
}

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.mixpanel.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.mixpanel.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 Mixpanel to your main activity app/src/main/java/com/mixpanel/example/myapplication/MainActivity.java

package com.mixpanel.example.myapplication;

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

import com.mixpanel.android.mpmetrics.MixpanelAPI; 

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" 
        MixpanelAPI mixpanel = MixpanelAPI.getInstance(this, projectToken);
    }
}

Make sure that you've replaced "YOUR_PROJECT_TOKEN" with your project token and run your app! You should now see the "MainActivity - onCreate called" event show up in your Mixpanel reports.

4. Add code to track your first event

package com.mixpanel.example.myapplication;

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

import com.mixpanel.android.mpmetrics.MixpanelAPI;

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"
        MixpanelAPI mixpanel = MixpanelAPI.getInstance(this, projectToken);
        
        try {
            JSONObject props = new JSONObject();
            props.put("Gender", "Female");
            props.put("Logged in", false);
            mixpanel.track("MainActivity - onCreate called", props);
        } catch (JSONException e) {
            Log.e("MYAPP", "Unable to add properties to JSONObject", e);
        }
    }
}

5. That's it! Mixpanel 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 Mixpanel reports just seconds after your app runs. You're now ready to take advantage of everything Mixpanel 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 Mixpanel immediately. Instead we queue them on the device and then send them in batches at set intervals. The default interval when you run your app in normal mode is 60 seconds. However, the default interval when you run your app in debug mode is 1 second. Therefore, it is recommended that you test your application in debug mode when you are integrating Mixpanel.

Next steps

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

  • Track important actions in your app
    To get the most value out of Mixpanel, you should identify the actions that are important to you and track them. To track events, you can add code to your app or use our codeless event tracking tool.
  • Setup and run your first A/B test
    Once you have the Mixpanel SDK initialized you can build and run an A/B test without writing any additional code. This is a great way to quickly test and measure changes to your application.
  • Send your users a push notification or message
    Mixpanel allows you to send your users targeted push notifications, in-app messages, and surveys. To get started, you need to send people profiles to Mixpanel. This will allow you to send messages or surveys to particular users within your app.

Full Android SDK Documentation

Installing the library - Android Studio / Gradle

Step 1 - Add the mixpanel-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.mixpanel.android:mixpanel-android:4.6.0'
}

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-base:7.0.0+'
    compile 'com.google.android.gms:play-services-gcm:7.0.0+'
}

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

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 Mixpanel 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 Mixpanel.
-->
<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 Mixpanel Android library inside Android Studio!

Installing the library - Eclipse

Please see our specific documentation for using the Mixpanel library for Android with Eclipse and ADT for instructions on how to import the library as an Eclipse project, and build it from source.

Initializing the library

Once you've set up your build system or IDE to use the Mixpanel library, you can initialize it in your code by calling MixpanelAPI.getInstance with your application context and your Mixpanel project token. You can find your token in the settings dialog in the Mixpanel web application.

public static final String MIXPANEL_TOKEN = "YOUR_TOKEN";

// Initialize the library with your
// Mixpanel project token, MIXPANEL_TOKEN, and a reference
// to your application context.
MixpanelAPI mixpanel =
    MixpanelAPI.getInstance(context, MIXPANEL_TOKEN);

Flushing events

To preserve battery life and customer bandwidth, the Mixpanel library doesn't send the events you record immediately. Instead, it sends batches to the Mixpanel 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 MixpanelAPI.flush in the onDestroy method of your main application activity.

@Override
protected void onDestroy() {
    mMixpanel.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.

Sending your first event

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

MixpanelAPI mixpanel =
    MixpanelAPI.getInstance(context, MIXPANEL_TOKEN);

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

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

Event timing

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.

MixpanelAPI mixpanel =
    MixpanelAPI.getInstance(context, MIXPANEL_TOKEN);

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

// stop the timer if the imageUpload() method returns true
if(imageUpload()){
    mixpanel.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.

To set super properties, call MixpanelAPI.registerSuperProperties

MixpanelAPI mixpanel =
    MixpanelAPI.getInstance(context, MIXPANEL_TOKEN);

// Send a "User Type: Paid" property will be sent
// with all future track calls.
JSONObject props = new JSONObject();
props.put("User Type", "Paid");
mixpanel.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 MixpanelAPI.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 Mixpanel 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 using your app on multiple platforms (both web and mobile, for example). To assign your own distinct_ids, you can use MixpanelAPI.identify

MixpanelAPI mixpanel =
    MixpanelAPI.getInstance(context, MIXPANEL_TOKEN);

// Associate all future events sent from
// the library with the distinct_id 13793
mixpanel.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 actual application usage to the correct user ID.

Calling identify with a new ID will change the ID being sent with future events. If you change the ID in the middle of a funnel, the funnel will break - we won't be able to associate the old ID with the new.

Linking two user IDs

In situations where you want to link the two IDs (in practice, this really just means when the user signs up) you should use alias which sends an update to our server linking the current ID with a new ID.

// This makes the current ID (an auto-generated GUID)
// and '13793' interchangeable distinct ids.
mixpanel.alias("13793", null);

The recommended usage pattern is to call alias when the user signs up and identify when the user logs in. In general, you should not call identify in the Android library after alias —you don't need to, since you've already set an alias from the new id to the existing id. You only need to identify if the user logs in again.

If you use alias you should only call it once during the lifetime of the user.

Storing user profiles

In addition to events, you can store user profiles in Mixpanel'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 notifications, 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 MixpanelAPI.getPeople().set.

MixpanelAPI mixpanel =
    MixpanelAPI.getInstance(context, MIXPANEL_TOKEN);

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

// Sets user 13793's "Plan" attribute to "Premium"
mixpanel.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 Mixpanel 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 MixpanelAPI.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 Mixpanel
mixpanel.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);

mixpanel.getPeople().increment(properties);

Other types of profile updates

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

Tracking revenue

Mixpanel 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 MixpanelAPI.getPeople().trackCharge. This call will add transactions to the individual user profile, which will also be reflected in the Mixpanel Revenue report.

MixpanelAPI mixpanel =
    MixpanelAPI.getInstance(context, MIXPANEL_TOKEN);

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

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

// Refund this user 50 dollars
mixpanel.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");
mixpanel.getPeople().trackCharge(25, properties);

Handling push notifications

The Mixpanel Android library will handle registering for and displaying Google Cloud Messaging notifications sent from the Mixpanel 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="android.permission.GET_ACCOUNTS" />
<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 Mixpanel library's com.mixpanel.android.mpmetrics.GCMReceiver class as a receiver for GCM intents:

<receiver
  android:name="com.mixpanel.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 Mixpanel library is almost completely automatic. You can initialize push handling in your app by callng MixpanelAPI.getPeople().initPushHandling with your 12 digit project number of your Google API project as an argument.

MixpanelAPI mixpanel =
    MixpanelAPI.getInstance(context, MIXPANEL_TOKEN);

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

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

Push notifications guide

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

In-app notifications

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

Make sure that you have already:

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

A/B testing

Prerequisites

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

Creating your first A/B test

Mixpanel 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 Mixpanel 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 Mixpanel using the flip gesture
  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 Mixpanel A/B testing to change the values of variables by taking advantage of developer tweaks.

Notes on experiment delivery

Mixpanel 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.

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 Mixpanel. 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 MixpanelAPI.booleanTweak, MixpanelAPI.stringTweak, MixpanelAPI.longTweak, MixpanelAPI.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.mixpanel.example.mygame;

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

import com.mixpanel.android.mpmetrics.MixpanelAPI;
import com.mixpanel.android.mpmetrics.Tweak;


public class GameActivity extends Activity {

    private static Tweak<Double> gameSpeed = MixpanelAPI.doubleTweak("Game speed", 1.0);
    private static Tweak<Boolean> showAds = MixpanelAPI.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 Mixpanel 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.mixpanel.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 Mixpanel.

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.

Surveys

To use Surveys in your Android app, you need to do four things:

  1. Include the Mixpanel Android library of version 4.1.0 or higher in your app
  2. Register the SurveyActivity in your AndroidManifest.xml file
  3. Identify the current user using getPeople().identify()
  4. Create a survey for your project in the Surveys tab of the Mixpanel website

By default, the Mixpanel Android library will check for a survey when your app loads or resumes from the background. If a survey is available for the current user that they haven't already seen, it will be displayed immediately in an overlay view.

Surveys are only supported on Android versions from API Level 14 (Ice Cream Sandwich) and up.

Registering the SurveyActivity

To enable your app to show surveys, you need to register the SurveyActivity within your AndroidManifest.xml inside the <application> tag. Here is an example snippet for an app that uses surveys:

...
<application>
  <activity android:name="com.mixpanel.android.surveys.SurveyActivity"
            android:theme="@style/com_mixpanel_android_SurveyActivityTheme"/>
</application>
...
            

The specified theme is a general Mixpanel default, so feel free to substitute your own theme better match the look and feel of your application.

Controlling when to show a survey

You may not want the surveys to show immediately when your app loads. If, for example, you have an app like Skype™, and you want to show a call quality survey at the end of a phone call, you need to turn off the automatic showing of surveys, by setting com.mixpanel.android.MPConfig.AutoDisplayMixanelUpdates in your main Activity using a meta-data tag in AndroidManifest.xml to false:

...
<application>
    <meta-data
      android:name="com.mixpanel.android.MPConfig.AutoShowMixpanelUpdates"
      android:value="false" />
    ...
</application>
...
            

If you turn off the auto-check, you'll need to manually use our library to display a survey.

To manually check if a survey is available, you may call MixpanelAPI.People.getSurveyIfAvailable(). This method will return a Survey object if the Mixpanel library has received a survey for the currently identified user, and null otherwise. You may then use this object to render your own survey.

You can also call MixpanelAPI.People.showSurveyIfAvailable() to allow the Mixpanel library to render a survey for you.

Debugging and Logging

Enabling Mixpanel debugging and logging allows you to see the debug output from the Mixpanel Android library. This may be useful in determining when track calls go out or in-app notifications or surveys are fetched. To enable Mixpanel 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.mixpanel.android.MPConfig.EnableDebugLogging"
      android:value="true" />
    ...
</application>
...

Document Sections
Learn more