Integrating Google Analytics SDK (V2) with Android

The Google Analytics SDK for Android makes it easy for developers to collect valuable statics about how the users are using their app.

Here are some features that Android Google Analytics SDK offers:

  • The number of active users that are using the application
  • Usage of specific features
  • The number and type of application crashes
  • From where in the world the application is used
  • And many other useful metrics.

Just to illustrate the integration process lets create a simple proof of concept application with 2 activities: MainActivity and AboutActivity, and 2 buttons: Rate and Share.

Our mission is to integrate Google Analytics SDK with the application, to:

  • track activity views, (MainActivity and About)
  • track events (how many times the buttons “Rate”, and “Share” are clicked)

android google analytics sdk

If you are searching for Google Analytics I’m assuming you are already pretty familiar with Android and could create the proof of concept application yourself, so I will skip this step and concentrate solely on integration.

 

1. Downloading the SDK

Go to downloads page and download GoogleAnalyticsAndroid.zip Version 2.0. Extract the archive and add libGoogleAnalyticsV2.jar to your project’s /libs directory.

At the moment of writing this post, Google provides two versions: version 1.5.1 (legacy), and version 2.0 beta. Still if the Version 2 of SDK is beta, I highly suggest you choose this version, over the 1.5.1 (legacy).
The reason not to choose SDK 1.5.1 is that it uses a tracking model that is designed to track visitors to traditional websites and interaction with widgets in traditional web pages.

The new “App” profiles and reports will only accept data from version 2 or higher of the SDK.

 

2. Creating a Google Analytics account

Before starting to use the SDK you first must create an account at: http://www.google.com/analytics/

  1. Sign in to your account.
  2. Click Admin.
  3. Click Account list (just below the menu bar)
  4. Click +New Account
  5. When asked what you would like to track, select App property.android app profile
  6. Enter all the necessary information and click Get Tracking ID.

Now that you have a Tracking ID, you can begin the integration with the application. The first step is to update the AndroidManifest file.

 

3. Updating AndroidManifest file.

Add folowing permissions to the AndroidManifest file:

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

 

4. Creating the analytics.xml file

In version 2 of Google Analytics SDK for Android, the tracking settings are managed from an xml resource file called: analytics.xml. You will need to create this file in res/values directory, and add your tracking ID as well as other settings here.


<?xml version="1.0" encoding="utf-8"?>
<resources>

   <!-- Replace placeholder ID with your tracking ID -->
   <string name="ga_trackingId">UA-00000000-0</string>

   <!-- Enable Activity tracking -->
   <bool name="ga_autoActivityTracking">true</bool>

   <!-- Enable debug -->
   <bool name="ga_debug">true</bool>

   <!-- The screen names that will appear in your reporting -->
   <string name="com.testgoogleanalytics.MainActivity">MainActivity</string>
   <string name="com.testgoogleanalytics.About">About</string>

   <!--
   The inverval of time after all the collected data
   should be sent to the server, in seconds.
   -->
   <integer name="ga_dispatchPeriod">30</integer>

</resources>

 

5. Tracking activities.

To track activities add the tracking methods to the onStart() and onStop()  of each of your activities.


// Example of tracking MainActivity
public class MainActivity extends Activity {
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }

   @Override
   protected void onStart() {
      super.onStart();
      EasyTracker.getInstance().activityStart(this); // Add this method
   }

   @Override
   protected void onStop() {
      super.onStop();
      EasyTracker.getInstance().activityStop(this); // Add this method
   }
}

One thing to note here is that EasyTraker requires a context before you can use it. If you attempt to call any of its methods but did not pass first a context, you may end up with an IllegalStateException.

In the above example, in  the onStart()  and onStop() methods the context is passed as an argument to activityStart() and activityStop(), but  if you need to make EasyTracker calls in other classes or methods, you’ll need to call EasyTracker’s setContext(Context context) method first:

Context context= this;  // Get current context.
EasyTracker.getInstance().setContext(context);  // Set context
// EasyTracker is now ready for use.

 

6. Tracking events

Tracking events is just as easy as tracking activities, you just need a Tracker object and call the trackEvent(String category, String action, String label, int value) method.

public class MainActivity extends Activity {

   private Tracker tracker;

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

      // Set context
      EasyTracker.getInstance().setContext(getApplicationContext());
      // Instantiate the Tracker
      tracker = EasyTracker.getTracker();

      // Add tracking functionality to "Rate" button
      Button rate = (Button) findViewById(R.id.rate);
      rate.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View arg0) {
            // The rest of your code
            tracker.trackEvent("Buttons Category", "Rate", "", 0L);
         }
      });

      // Add tracking functionality to "Share" button....
   }
}

In this particular example I don’t need a label nor a value, that is why I set for the last 2 parameters of trackEvent() method, an empty string a 0 (zero), but depending of your needs you may populate them with some data.

 

7. Debugging

Debugging helps you deal with troubleshooting, and make you sure that the data actually is sent to the server. To set the Google Analytics in debug mode, add the following setting in the analytics.xml


<bool name="ga_debug">true</bool>

Once your are in debug mode, you can watch the log information in LogCat:

 

Waiting for the big moment!

If everything is configured correctly, the reports should appear on live. Usually it takes about 24 hours to see the data in your account.

android actions google analytics

 

 

What happens if my application is used when no network is available?

Just in case you asked this yourself…, all the events are persisted in a local storage, and they will be sent the next time your app is running and dispatch is called.

 

Last but not least

One important thing not to be forgotten: you must indicate to your users, either in the application itself or in your terms of service, that you reserve the right to anonymously track and report a user’s activity inside of your app.

Android Google Analytics SDK offers more than tracking activities and events, see: https://developers.google.com/analytics/devguides/collection/android/v2/ to get the most out of it.

Please visit the Android Tutorials page for more tutorials.

Advertisement

Drawing Shapes in Android

In this post I would like to share my findings about defining and using shapes.  A shape is an XML file that defines a geometric shape, including strokes, colors and gradients

Android Shapes

To define a shape:

1. Create a new Android XML file in the folder res/drawable

2. Make sure the root element of the file is <shape >. (If it’s not, then change it manually)

3. Inside the <shape> element, press CTRL + Space to reveal all the available elements you can use to define a shape:

android shapes options

As you can see, the elements are pretty self explanatory. To reveal the attributes of an element, put the cursor inside that element and press CTRL + Space:

android shape corner

4. Once the shape is defined, you can specify it as a background resource to any view: android:background=”@drawable/myshape”

Example:

res/drawable/boxbg.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

<stroke
  android:width="2dp"
  android:color="#FFFFFF" />

<corners android:radius="5dp" />

<gradient
  android:angle="270"
  android:centerColor="#6E7FFF"
  android:endColor="#142FFC"
  android:startColor="#BAC2FF" />

</shape>

 

res/drawable/box2bg.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

<solid android:color="#4D9611" />

<stroke
  android:width="4dp"
  android:color="#FFFB00" />

</shape>

 

res/layout/main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<!-- First box, boxbg.xml -->
<LinearLayout
  android:layout_width="match_parent"
  android:layout_height="80dp"
  android:layout_margin="20dp"
  android:background="@drawable/boxbg"
  android:orientation="vertical"
  android:padding="5dp" >

  <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:textColor="#000"
    android:textSize="20dp" />
</LinearLayout>

<!-- Second box, box2bg.xml -->
<LinearLayout
  android:layout_width="match_parent"
  android:layout_height="80dp"
  android:layout_margin="20dp"
  android:background="@drawable/box2bg"
  android:orientation="vertical"
  android:padding="7dp" >

  <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:textColor="#FFF"
    android:textSize="20dp" />
</LinearLayout>

</LinearLayout>

 

The final output should look like this:

android shape

Understanding AsyncTask – Once and Forever

This article describes the usage of AsyncTask class in Android.

Motivation

Android modifies the user interface via one thread, the so called UI Thread. If you perform a long running operation directly on the UI Thread, for example downloading a file from the internet, the user interface of your application will “freeze” until the corresponding task is finished. When this happens it is very easy for the user to perceive your application as slow.

As a concrete example of a bad implementation and what happens when a long running operation is done on the UI Thread, I want to refer to one of my previous tutorials: Creating A Simple RSS Application in Android. Well, that application is working fine, and it does what it is supposed to do – parse an XML feed and display the headlines in a ListView. The “vulnerability” of that application is that the network access is done directly on the UI Thread which makes the application to “freeze” while the XML feed is downloaded (take a look at point number 5 to see).
When I created that tutorial I wanted to make it as simple as possible without dealing with more advanced topics like asynchronous tasks. The intent of tutorial was to show the working process with feeds on a high level. But I promise you, by the end of this article you will be able to fix it and have a Cool Rss App that runs smoothly! 🙂

To provide a good user experience all long running operations in an Android application should run asynchronously. To achieve this we will be using the AsyncTask class.

What does AsyncTask do?

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. 

In order to use the AsyncTask class, you must extend it and override at least the doInBackground() method.

The most common methods you will need to implement are these:

   1. onPreExecute() – called on the UI thread before the thread starts running. This method is usually used to setup the task, for example by displaying a progress bar.

   2. doInBackground(Params…) – this is the method that runs on the background thread. In this method you should put all the code you want the application to perform in background. Referring to our Simple RSS Aplication, you would put here the code that downloads the XML feed and does the parsing. The doInBackground() is called immediately after onPreExecute(). When it finishes, it sends the result to the onPostExecute().

   3. onProgressUpdate() – called when you invoke publishProgress() in the doInBackground().

   4. onPostExecute(Result) – called on the UI thread after the background thread finishes. It takes as parameter the result received from doInBackground().

AsyncTask is a generic class, it uses 3 types: AsyncTask<Params, Progress, Result>.

  1. Params – the input. what you pass to the AsyncTask
  2. Progress – if you have any updates, passed to onProgressUpdate()
  3. Result – the output. what returns doInBackground()

Once a task is created, it can be executed like this:
new DownloadTast().execute(url1, url2, urln);

Code Example

This is a simple skeleton of an AsyncTask implementation.


public class AsyncTaskTestActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      //Starting the task. Pass an url as the parameter.
      new PostTask().execute("http://feeds.pcworld.com/pcworld/latestnews");
   }

   // The definition of our task class
   private class PostTask extends AsyncTask<String, Integer, String> {
   @Override
   protected void onPreExecute() {
      super.onPreExecute();
      displayProgressBar("Downloading...");
   }

   @Override
   protected String doInBackground(String... params) {
      String url=params[0];

      // Dummy code
      for (int i = 0; i <= 100; i += 5) {
        try {
          Thread.sleep(50);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
         publishProgress(i);
      }
      return "All Done!";
   }

   @Override
   protected void onProgressUpdate(Integer... values) {
      super.onProgressUpdate(values);
      updateProgressBar(values[0]);
   }

   @Override
   protected void onPostExecute(String result) {
      super.onPostExecute(result);
      dismissProgressBar();
   }
   }
}

AsyncTasks are great for performing tasks in a separate thread, they have however one weakness. While the AsyncTask is in the middle of the work and the screen of device is rotated, you’ll notice that the application crashes. This happens because when rotating the device screen a configuration change occurs, which will trigger the Activity to restart. The AsyncTask reference to the Activity is invalid, an onPostExecute() will have no effect on the new Activity. How to handle this sort of issues is described in: Dealing with AsyncTask and Screen Orientation, which I highly recommend reading it if you are concerned to deliver stable Android applications.

How to simulate an incoming call in Android

1. Start the Android Emulator

2. Open up the windows console by going to Start -> Run (or Windows + R shortcut) and type in “cmd”. Press Enter. This should open the dos console.

3. Type in “telnet” and press enter. This should open the Telnet Console.
(At this stage you may experience some problems, the console may display the error: ‘telnet’ is not recognized as an internal or external command, operable program or batch file. If this is the case, scroll down to see how to fix it, then return and continue the process)

4. Telnet Console being displayed, type in “o localhost 5554″. This will establish a connection with the emulator on port 5554 and open the Android Console. 5554 is the port number and you can see it on the title bar of the emulator window.

5. To simulate the call, type in “gsm call 099062274”

6. To cancel the call, type “gsm cancel 099062274″

7. Use “exit” to exit the Android Console, and “quit” to quit the Telnet client.

That’s it!

android incoming call

*How to fix the: ‘telnet’ is not recognized as an internal or external command, operable program or batch file error.

When trying to invoke the telnet program you may experience the above error. The cause of this could be that the Telnet Client is turned off on your computer.

To turn it on, follow these steps:
1. Go to Control Panel

2. Click on Programs

3. Under Programs and Features section, click on Turn Windows features on or off. This should bring you the Windows Features pop-up.

4. Find the Telnet Client, select it, click OK.