Integrate Amplitude Mobile Analytics In Android Tutorial

Udemy Generic 728x90

Objective

In this tutorial, we will learn the integration process of Amplitude Mobile Analytics in an Android Application through a simple example.

 




Analytics can be defined as analysis of historical data to examine the current patterns, derive potential trends and new equations and use them to enhance the business performance and make better decisions for future goals. There are various analytical services present in market that can be used to track the traffic of applications and provide a detailed analysis of collected data.

Amplitude Mobile Analytics is one of the best analytics service, through which you can track user engagement and traffic of your web and mobile app. Amplitude provides the following services :

  • Real Time Analytics : It shows the user engagement in real time. It show the user timelines to drill down the real time event feed. You can create funnels, check retention or can create multiple segments to compare.
  • Microscope : This feature enables you to explore the user behavior at a data point. To do so, simply click on the data point and it will display the list of actions by various users that make up the point.
  • Behavioral Cohorts : It provides functionality to create Cohorts through which you can track the user engagement, retention, etc. based on specific actions.
  • SQL : It also provides the ability to query the data through sql queries.

In this tutorial, we will learn how to integrate Amplitude Analytics in Android application and used its method to track the data through a simple example.

 

Step 2

Create a New Project

Create a new project in your Android Studio, named AmpltitudeDemo.
 

Step 3

Integrate Amplitude in App

Next step would be the integration of Amplitude in your application and to do so, you will need a Amplitude account.
 

Step 3.1

Create Amplitude Account

To create Amplitude account, open Amplitude Sign Up page and register there.


amplitude-demo

 
Next, you need to add your app at Amplitude Dashboard. So, enter AmplitudeDemo in the text field and click on Add App button to add app.

amplitude-create
 

amplitude-apps

 

Step 3.2

Integrate Amplitude SDK in App

Once the app is added, you need to integrate Amplitude in your project, i.e, install Amplitude SDK and set Amplitude credentials at app level. So, open your app in Android Studio and add following line in app’s build.gradle file to add Amplitude SDK as a dependency of your project.

<br />
 compile 'com.amplitude:android-sdk:2.5.0'<br />

 

Step 3.3

Track First Event

Now, Amplitude is ready to track your app’s data. So, next would be initializing Amplitude in your activity and define your first event. Open your MainActivity file and import Amplitude by adding the following line.

<br />
import com.amplitude.api.Amplitude;<br />

To make Amplitude recognize your application, you need to initialize Amplitude in your application and provide your API key created while adding app in Amplitude dashboard.
Add the following line inside the onCreate() method of your activity :

<br />
// Initializes the amplitude sdk<br />
Amplitude.getInstance().initialize(this, &quot;YOUR_API_KEY&quot;).enableForegroundTracking(getApplication());<br />

If your app have more than one entry points then you need to initialize Amplitude at every entry point. Now, initialization is complete so you can define events and send them to Amplitude. Add the below code in onCreate() method to define your first event :

<br />
// Logs event named &quot;App Installed&quot; in Amplitude<br />
Amplitude.getInstance().logEvent(&quot;App Installed&quot;);<br />

Amplitude SDK logs all the events registered and send them to your Amplitude dashboard after every 30 seconds. To send and update events at dashboard, Amplitude SDK needs Internet permission. If permission is not added in manifest file then Amplitude SDK will not be able to send the events to dashboard. So, open AndroidManifext.xml and add the following line to provide permission :

<br />
&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;<br />

 

Step 3.4

Run Application

Now, run your application and open your Amplitude Dashboard. In dashboard, you can see the number of events logged by your app.

amplitude-new

 

Step 4

Tracking Events with Custom Properties

Now, we know how to log a simple event using logEvent() method. But, we can also attach additional data with every event to get more visibility of that event. To do so, first create a JSON object and then pass the object as second argument to logEvent() method. So, to generate an event with additional data add a button and log that click event.
Add the following code snippet in activity_main.xml file to add button :

<br />
    &lt;Button<br />
        android:layout_width=&quot;wrap_content&quot;<br />
        android:layout_height=&quot;wrap_content&quot;<br />
        android:text=&quot;Click Event&quot;<br />
        android:id=&quot;@+id/button&quot;<br />
        android:layout_centerVertical=&quot;true&quot;<br />
        android:layout_centerHorizontal=&quot;true&quot;<br />
        android:onClick=&quot;GenerateEvent&quot;/&gt;<br />

Generate the event by adding below code snippet in MainActivity class :

<br />
/**<br />
 * Creates json packet for event properties and logs event with its properties<br />
 */<br />
public void GenerateEvent(View view){</p>
<p>    // creates json packet for event properties<br />
    JSONObject eventProperties = new JSONObject();</p>
<p>    try {<br />
        eventProperties.put(&quot;Event&quot;, &quot;Click&quot;);<br />
        eventProperties.put(&quot;Value&quot;, &quot;Test&quot;);<br />
    }<br />
    catch (JSONException exception) {<br />
        exception.printStackTrace();<br />
    }</p>
<p>    Amplitude.getInstance().logEvent(&quot;Button is Clicked&quot;);<br />
}<br />

 

Step 5

Track Sessions

Sessions can be defined as a period of time for which app was in foreground of the device (i.e. running state). In Amplitude, we can track sessions of the app. Events of same session will have same session id. To add session tracking in your app, add the following line after SDK initialization :

<br />
// Enables Session tracking through Amplitude<br />
Amplitude.getInstance().trackSessionEvents(true);<br />

You don’t have to manually end a session. Session will get destroyed automatically after 5 minutes if app is not in foreground but if Android API level of the device is less than 14 then session will get destroyed after 30 mins. Also you can set define the session duration by using setMinTimeBetweenSessionsMillis() method.

 

Step 6

Set Custom User Id and Properties

Amplitude assign a specific user id based on the device but you can set custom user id if your app has a login system implemented in it. Once custom user is set, every event on the same device will be tracked under the same custom user. Also, SDK provides various operations to add individual user’s properties. These operations are :

  • set() : this is used set the value of a user property.
  • setOnce() : this is used to set a value just once. For ex – Registration date of user can be set only once.
  • unset() : this property is used to unset value of a user property.
  • add() : this is used to increment the value of a user property
  • append() : this is used to append values to a user property.

These operations can be declared under the Identify object of Amplitude SDK. After adding the user properties, Identify object is passed to Amplitude to modify user properties. To set custom user id and user properties, add a button in your layout and implement a method that will setUserId() method to set user id.
Open your activity_main.xml file and add a button there :

<br />
&lt;Button<br />
    android:layout_width=&quot;wrap_content&quot;<br />
    android:layout_height=&quot;wrap_content&quot;<br />
    android:text=&quot;Indentify User&quot;<br />
    android:id=&quot;@+id/button2&quot;<br />
    android:layout_below=&quot;@+id/button&quot;<br />
    android:layout_centerHorizontal=&quot;true&quot;<br />
    android:layout_marginTop=&quot;52dp&quot;<br />
    android:onClick=&quot;UserIdentification&quot;/&gt;<br />

Next, you need to implement a method that will be called on the click of the button. Within the method set the custom user id and define user properties using the defined operations.
Here is the sample code for same :

<br />
/**<br />
 * Method to identify user in Amplitude<br />
 */<br />
public void UserIdentification(View view){</p>
<p>    // Sets custom user id for app user<br />
    Amplitude.getInstance().setUserId(&quot;[email protected]&quot;);</p>
<p>    // declares and sets user properties through Identify interface<br />
    Identify identify = new Identify().set(&quot;name&quot;, &quot;age&quot;).set(&quot;udit&quot;, 23);</p>
<p>    // sends user properties to amplitude<br />
    Amplitude.getInstance().identify(identify);<br />
}<br />

 

Step 7

Run Application

Now, your app will be able to track the session and can set user id and also user properties. You can check the tracked data in Amplitude Dashboard.
Here is the final code of your main activity file :

<br />
public class MainActivity extends AppCompatActivity {</p>
<p>    @Override<br />
    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_main);</p>
<p>        // Initializes the amplitude sdk<br />
        Amplitude.getInstance().initialize(this, &quot;e145xxxxxxxxxxxxxxs2bf1b9c9xxxx&quot;)<br />
                               .enableForegroundTracking(getApplication());</p>
<p>        // Enables Session tracking through Amplitude<br />
        Amplitude.getInstance().trackSessionEvents(true);</p>
<p>        // Logs event named &quot;App Installed&quot; in Amplitude<br />
        Amplitude.getInstance().logEvent(&quot;App Installed&quot;);<br />
    }</p>
<p>    /**<br />
     * Method to identify user in Amplitude<br />
     */<br />
    public void UserIdentification(View view){</p>
<p>        // Sets custom user id for app user<br />
        Amplitude.getInstance().setUserId(&quot;[email protected]&quot;);</p>
<p>        // declares and sets user properties through Identify interface<br />
        Identify identify = new Identify().set(&quot;name&quot;, &quot;age&quot;).set(&quot;udit&quot;, 23);</p>
<p>        // sends user properties to amplitude<br />
        Amplitude.getInstance().identify(identify);<br />
    }</p>
<p>    @Override<br />
    protected void onResume(){<br />
        super.onResume();</p>
<p>        // Logs event every time app is resumed<br />
        Amplitude.getInstance().logEvent(&quot;App resumed&quot;);<br />
    }</p>
<p>    /**<br />
     * Creates json packet for event properties and logs event with its properties<br />
     */<br />
    public void GenerateEvent(View view){</p>
<p>        // creates json packet for event properties<br />
        JSONObject eventProperties = new JSONObject();</p>
<p>        try {<br />
            eventProperties.put(&quot;Event&quot;, &quot;Click&quot;);<br />
            eventProperties.put(&quot;Value&quot;, &quot;Test&quot;);<br />
        }<br />
        catch (JSONException exception) {<br />
            exception.printStackTrace();<br />
        }</p>
<p>        Amplitude.getInstance().logEvent(&quot;Button is Clicked&quot;);<br />
    }</p>
<p>    @Override<br />
    protected void onPause(){<br />
        super.onResume();<br />
        // Logs event every time app is paused<br />
        Amplitude.getInstance().logEvent(&quot;App paused&quot;);<br />
    }<br />
}<br />


amplitude-demo
amplitude-demo2
amplitude-demo1

Download Source Codedownload

 

Udemy Generic 728x90

Spread the word. Share this post!