Mixpanel Integration in Android Tutorial

Udemy Generic 728x90

Objective

In this tutorial, we will learn how to integrate Mixpanel with Android application and track user action in app through a simple example.

 





 

Mixpanel is an analytics platform for mobile and web. It offers to analyze actions user take in Android application. An action is anything such as uploading a picture, playing a video, or sharing a post, etc.

This tutorial explains how to integrate Mixpanel with Android application and also how to track user’s event in Android application. To integrate Mixpanel with Android application, we need to create an account on Mixpanel.
 

Step 2

Create a New Project

Create a new Project in Android Studio, goto File ⇒ New ⇒ New Projects.
 

Step 3

Add Supporting Library

To use Mixpanel API, we need to add supporting library as dependencies. So, open build.gradle file and following code under dependencies.

compile "com.mixpanel.android:mixpanel-android:4.8.0"
compile "com.google.android.gms:play-services:3.1+"

 

Step 4

Add Internet Permission

To track user’s event in application, Application needs to request Internet permission from user’s. So we need to add Internet permission in AndroidManifest.xml file.

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

 

Step 5

Get Mixpanel Token

To integrate with Mixpanel with Android application and track user event, we need to get a taken from Mixpanel Account. Follow these steps to get a token:

  • Login to Mixpanel account.
  • Click on Account Tab then a pop window will open.
  •  

    account

     

  • Click on Projects tab.
     
    pop window

     
  • Copy token, we will add this token in Android application.
    mixpanel token

     

 

Step 6

Add token in Project

We will add token in the MainActivity.java file to track the event. We need to add token in the getInstance() method of MixpanelAPI class.

public class MainActivity extends AppCompatActivity {
    
    // Mixpanel project token
    String projectToken = "569346ed4438011af52a0f2361xxxxxxxx";
    MixpanelAPI mixpanel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Add project token in the getInstance() method. 
        MixpanelAPI mixpanel = MixpanelAPI.getInstance(this, projectToken);
    }
}

 

Step 7

Flushing events

To preserve battery life of mobile and customer bandwidth, Mixpanel does not send recorded events immediately. When application stops, all event will send by calling MixpanelAPI.flush in the onDestroy method of your main application activity. If we don’t call flush, event will be sent the next time the application is opened.

@Override
protected void onDestroy() {

     // Flushing Event
     mixpanel.flush();
     super.onDestroy();
}

 

Step 8

Sending your first event

We can track an event by calling MixpanelAPI.track with the event name and properties. An event is an action user takes in your application. A property is a little bit of extra information that describes an event.

/**
 *  track event by calling MixPanelAPI.track() method with event name and properties
 */
public void trackEvent(){

    try {

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

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

    } catch (JSONException e) {

            Log.e("MYAPP", "Unable to add properties to JSONObject", e);
    }

}

 

Step 9

Event Timing

We can track the timing of the action to take competition. It will mark the time, when start your action and record the time duration of the event. For that we are making simple example in which display text using TextView and track timing of this action. In this exaple, we track trackTiming() method.

public class MainActivity extends AppCompatActivity {

    // Replace project token with your token
    String projectToken = "569346ed4438011af52a0f2xxxxxxxx";
    TextView textView;
    MixpanelAPI mixpanel;


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

        // Initialize textview
        textView = (TextView) findViewById(R.id.textview);

        //  Add project token in the getInstance() method.
        mixpanel = MixpanelAPI.getInstance(this, projectToken);

        // Call trackEvent method
        trackEvent();

        // start the timer for the event "display data"
        mixpanel.timeEvent("display data");

        if(trackTiming()){

            mixpanel.track("display data");
        }

    }

    /**
     *  track event by calling MixPanelAPI.track() method with event name and properties
     */
    public void trackEvent(){

        try {

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

            // track event by calling track() method
            mixpanel.track("Plan Selected", props);

        } catch (JSONException e) {

            Log.e("MYAPP", "Unable to add properties to JSONObject", e);
        }

    }

    /**
     * Set text on TextView
     * @return
     */
    public boolean trackTiming(){

        textView.setText("name: Abhay \n email: abhay@numetriclabz.com");
        return true;

    }

    /**
     *  Called when app closed.
     *  Calling flush() method of MixPanelAPI class to send all recorded event.
     */
    @Override
    protected void onDestroy() {
        mixpanel.flush();
        super.onDestroy();
    }

}

 

Step 10

Super properties

If we want to include some important properties with event then we can register properties as a super properties. Super properties are saved to device storage. To set super properties, call MixpanelAPI.registerSuperProperties.

/**
 *  Register properties as super properties.
 *  Send Properties with event.
 */
 public void sentEventWithProperties(){

    try{

        // 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);
        mixpanel.track("setImportant");

    } catch (Exception e){

    }
}

 

Step 11

Setting super properties once and only once

If we want to save super properties only once (for example user first login) then we need to use MixpanelAPI.registerSuperPropertiesOnce. registerSuperPropertiesOnce has same interface of registerSuperProperties but it does not override super properties whatever you have saved.
 

Step 12

Managing user identity

Mixpanel library provides feature to assign a default unique identifier to each install of your application. The distinct id is saved in the device storage. If you assign own user Id. This is helpful to track user, if he uses your app on multiple device and also track user logs in your app. To assign own user id, use MixpanelAPI.identify.

/**
 * Associate all future events sent from
 * the library with the distinct_id 132
 */

 mixpanel.identify("132");

 

Step 13

Tracking revenue

We can analyze the revenue for individual customers. We can track a single transaction by using MixpanelAPI.getPeople().trackCharge() method. MixpanelAPI.getPeople().trackCharge() method will add transactions to the individual user profile, which will also be reflected in the Mixpanel Revenue report.

/**
 *  Using getPeople.trackCharge() method, we can track revenue for individual user
 */
 public void revenueTrack(){

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

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

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

     try {

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

      } catch (Exception e){

         e.printStackTrace();
      }
}

 

Step 14

Incrementing numeric properties

We can set numeric properties by using MixpanelAPI.getPeople().increment() method. This is useful when you want to keep a running tally of things, such as games played, messages sent, or points earned.

/**
 *  Set numeric properties.
 */
public void setNumericProperties(){
        
     /**
      * Add 500 to the current value of "points earned" in Mixpanel
      */
     mixpanel.getPeople().increment("points earned", 1000);

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

     mixpanel.getPeople().increment(properties);
}

 

Step 15

Final Code

Here is final code:

public class MainActivity extends AppCompatActivity {

    // Replace project token with your token
    String projectToken = "569346ed4438011af52a0fxxxxxxxx";
    TextView textView;
    MixpanelAPI mixpanel;


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

        // Initialize textview
        textView = (TextView) findViewById(R.id.textview);

        //  Add project token in the getInstance() method.
        mixpanel = MixpanelAPI.getInstance(this, projectToken);

        /**
         * Associate all future events sent from
         * the library with the distinct_id 132
         */
        mixpanel.identify("132");

        // Call trackEvent method
        trackEvent();

        // start the timer for the event "display data"
        mixpanel.timeEvent("display data");

        if(trackTiming()){

            mixpanel.track("display data");
        }

        // Calling sentEventWithProperties() method.
        sentEventWithProperties();

        // Calling revenueTrack() method.
        revenueTrack();

        // Calling setNumericProperties() method
        setNumericProperties();

    }

    /**
     *  track event by calling MixPanelAPI.track() method with event name and properties
     */
    public void trackEvent(){

        try {

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

            // track event by calling track() method
            mixpanel.track("Plan Selected", props);

        } catch (JSONException e) {

            Log.e("MYAPP", "Unable to add properties to JSONObject", e);
        }

    }

    /**
     *  Register properties as super properties.
     *  Send Properties with event.
     */
    public void sentEventWithProperties(){

        try{

            // 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);
            mixpanel.track("setImportant");

        } catch (Exception e){

        }
    }

    /**
     * Set text on TextView
     * @return
     */
    public boolean trackTiming() {

        textView.setText("name: Abhay \n email: abhay@numetriclabz.com");
        return true;

    }

    /**
     *  Using getPeople.trackCharge() method, we can track revenue for individual user
     */
    public void revenueTrack(){

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

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

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

        try {

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

        } catch (Exception e){

            e.printStackTrace();
        }
    }

    /**
     *  Set numeric properties.
     */
    public void setNumericProperties(){

        /**
         * Add 500 to the current value of "points earned" in Mixpanel
         */
        mixpanel.getPeople().increment("points earned", 1000);

        // Pass a Map to increment multiple properties
        Map<String, Integer> properties =
                new HashMap<String, Integer>();

        properties.put("dollars spent", 34);

        // Subtract by passing a negative value
        properties.put("credits remaining", -68);

        mixpanel.getPeople().increment(properties);
    }

    /**
     *  Called when app closed.
     *  Calling flush() method of MixPanelAPI class to send all recorded event.
     */
    @Override
    protected void onDestroy() {
        mixpanel.flush();
        super.onDestroy();
    }

}

 




 

Udemy Generic 728x90

Spread the word. Share this post!