Android API Integration

Installing the library - Eclipse

Step 1 - Download the latest Mixpanel library release

To use the Mixpanel library inside of Eclipse, download the latest library source from Github and extract it.

Step 2 - Import the Mixpanel library into your project's workspace:

To have access to the Mixpanel library, you need to import it into your workspace by going to File->Import->Android->Existing Android Code into Workspace. Browse for the folder where you extracted the library and then choose Finish.

Step 3 - Associate the library as a dependency of your project:

Now that the library is in your workspace, you need to associate it as a dependency of your project. You can do this by going to your project properties, going to the 'Android' tab, and then adding the Mixpanel library in the library section.

Step 4 - Add permissions to your AndroidManifest.xml:

In order for the library to work, you 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 library inside Eclipse!

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 dependecy in your build.gradle file.

dependencies {
    compile "com.mixpanel.android:mixpanel-android:4.1.0@aar"
}

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!

Initializing the library

To use the Mixpanel library, you must first initialize it 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);

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 will change the ID being sent with future events. So, if you call identify 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 'joe@example.com' interchangeable distinct ids.
mixpanel.alias("joe@example.com", 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.

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.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.showSurveyIfAvailable() to allow the Mixpanel library to render a survey for you.

Document Sections
Learn more