Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate Google Analytics in Android app

Hi I am trying to integrate the Google Analytics but I am not able to find any analytics data that shows on the Google Analytics Account of mine. I am using the link mention below:-

developers.google.com link 1

some link 1

some link 2

developer.google link 2

But I am not able to get the result, nor the correct path/way or proper and Detailed Tutorial for how to integrate the Google Analytics in android app.

My code is as follows:-

    public class MainActivity extends Activity {
    GoogleAnalytics tracker;

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

         // Get tracker.
        Tracker t = ((AnalyticsHelper) MainActivity.this.getApplication()).getTracker(
            TrackerName.APP_TRACKER);
     // Set the dispatch period in seconds.
        GAServiceManager.getInstance().setLocalDispatchPeriod(8);
    }

    @Override
    protected void onStart() {
        super.onStart();
        EasyTracker.getInstance(this).activityStart(this);
     // Set the dispatch period in seconds.
        GAServiceManager.getInstance().setLocalDispatchPeriod(8);
    }

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

My Analytics Helper class is as follows:-

public class AnalyticsHelper extends Application {

     // The following line should be changed to include the correct property id.
    private static final String PROPERTY_ID = "UA-xxxxxxxx-x"; // My Property id.

    public static int GENERAL_TRACKER = 0;

    public enum TrackerName {
        APP_TRACKER, // Tracker used only in this app.
        GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
        ECOMMERCE_TRACKER, // Tracker used by all ecommerce transactions from a company.
    }

    HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();

    public AnalyticsHelper()
    {
        super();
    }

    synchronized Tracker getTracker(TrackerName trackerId) {
        if (!mTrackers.containsKey(trackerId)) {

            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            analytics.getLogger().setLogLevel(LogLevel.VERBOSE);
            Tracker t = null;
            if(trackerId==TrackerName.APP_TRACKER){
                t= analytics.getTracker(PROPERTY_ID);
            }
                 mTrackers.put(trackerId, t);
                }
        return mTrackers.get(trackerId);
    }
}

And my analytics xml file in xml directory is as follows:-

    <?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
            tools:ignore="TypographyDashes">

     <!--  The following value should be replaced with correct property id. -->
    <string name="ga_trackingId">UA-xxxxxxxx-X</string>

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

  <!--Enable automatic exception tracking-->
  <bool name="ga_reportUncaughtExceptions">true</bool>

</resources>

Any help will be heart-fully welcomed. Thanks in advance.

like image 324
Pravinsingh Waghela Avatar asked Jul 16 '14 14:07

Pravinsingh Waghela


People also ask

How do I integrate Google Analytics into an android app?

Go to Analytics and select the Analytics account you registered the app with. If you're unsure, look for the Analytics tracking ID in the google-services. json file you added to your project earlier. Copy that ID to the Analytics account search in the report drop-down.

Can we use Google Analytics for Mobile Apps?

Analytics surfaces data about user behavior in your iOS and Android apps, enabling you to make better decisions about your product and marketing optimization.

How long does it take to add integrations like Google Analytics to a mobile app?

If you have created a New App property and generated a Tracking ID earlier, link your Google Analytics App to it. Google Analytics would start measuring analytics within 24 hours.


3 Answers

Well the above code given in the Question works well. All you need to do is after setting your code and adding the Jar file Download Google Analytics Jar file to your Lib. just wait for 24 to 48 hours. and it would show all the events and analytic for the App you had registered.

Edited Answer:-

Once You had Created your Google Analytic account and Downloaded the Jar file, Add the Jar file in your lib folder of your Application

Google Analytic Implementation:-

Well For Analytic Part You Just need the analytic.xml file to be included in your values folder which is mentioned in the Question.

Then define private EasyTracker easyTracker = null; in your MainActivity.

And now in your onCreate(Bundle savedInstanceState) method just write the following lines of Code. Well you can also write the following code for any Listners e.g. on any Button Click.

    /*
    *For Google Analytics...
    */
    easyTracker = EasyTracker.getInstance(MainActivity.this); // It Tracks your Activity...
    easyTracker.send(MapBuilder.createEvent("SomeValue(StoryPage)",
            "SomeMoreValue(AuthorName) , "SomeMoreValueAgain(StoryTitle)", null).build()); //This line creates the event for keeping logs and other Analytical stuffs concerned to this Activity of Application...
//In the above example we had Tracked the session for the MainActivity and also Analysed how many time this activity was opened, which Author story and which Story was read.

Now in your onStart() Method, just write the following code, it starts the Tracking and Analytics session for your Activity.

EasyTracker.getInstance(this).activityStart(this);

And now in your onStop() Method, just write the following code, it will close or stop the Tracking session for this activity.

EasyTracker.getInstance(this).activityStop(this);

Now you are able to Track and Analysis your Application and Activities in It.

like image 188
Pravinsingh Waghela Avatar answered Oct 14 '22 07:10

Pravinsingh Waghela


I have detailed the steps for integrating Google Analytics into an existing app here. When I publish a new app I always go back to these instructions which work well.

like image 45
mackenziesoftware Avatar answered Oct 14 '22 05:10

mackenziesoftware


  1. Fisrt we have to create google analytics track id Goolge analytics sign in and enable api and get track id

  2. After that put that track id in below .xml code


 <?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="ga_sessionTimeout">300</integer>
<bool name="ga_autoActivityTracking">true</bool>
<string name="ga_trackingId">"place your track id"</string>
<string name="ga_sampleFrequency">100.0</string>
<bool name="ga_reportUncaughtExceptions">true</bool>
<screenName name="com.aquadeals.seller.HomeMainActivity">DashBoard Screen</screenName>

3. After that we can change manifest file very important to add this code below Add permissions

4.Change your application name to google analytics class name example"MyApplication.java"

 <application
    android:name=".app.MyApplication"

5. After that add services for sending and receiving broadcast events using internet

 <receiver
        android:name="com.google.android.gms.analytics.AnalyticsReceiver"
        android:enabled="true">
        <intent-filter>
            <action android:name="com.google.android.gms.analytics.ANALYTICS_DISPATCH" />
        </intent-filter>
    </receiver>
    <service           android:name="com.google.android.gms.analytics.AnalyticsService"
        android:enabled="true"
        android:exported="false" />
    <receiver       android:name="com.google.android.gms.analytics.CampaignTrackingReceiver"
        android:exported="true">
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
    </receiver>
    <service android:name="com.google.android.gms.analytics.CampaignTrackingService" />
  1. Before this manifest changes first add this two classes in your app

public final class AnalyticsTrackers {

public enum Target {APP,}
private static AnalyticsTrackers sInstance;
public static synchronized void initialize(Context context)
{
    if (sInstance != null) 
    {
        throw new IllegalStateException("Extra call to initialize analytics trackers");
    }
    sInstance = new AnalyticsTrackers(context);
}
public static synchronized AnalyticsTrackers getInstance() 
{
    if (sInstance == null) {
        throw new IllegalStateException("Call initialize() before getInstance()");
    }
    return sInstance;
}
private final Map<Target, Tracker> mTrackers = new HashMap<Target, Tracker>();
private final Context mContext;
private AnalyticsTrackers(Context context)
{
    mContext = context.getApplicationContext();
}
public synchronized Tracker get(Target target)
{
    if (!mTrackers.containsKey(target)) 
    {
        Tracker tracker;
        switch (target)
        {
            case APP:
                tracker = GoogleAnalytics.getInstance(mContext).newTracker(R.xml.app_tracker);
                break;
            default:
                throw new IllegalArgumentException("Unhandled analytics target " + target);
        }
        mTrackers.put(target, tracker);
    }
    return mTrackers.get(target);
}

}

And Add this AnalyticsApplication.java

public class AnalyticsApplication extends MultiDexApplication

{

private Tracker mTracker;
private static AnalyticsApplication mInstance;

@Override
public void onCreate()
{
    super.onCreate();
    mInstance = this;
    AnalyticsTrackers.initialize(this);
    AnalyticsTrackers.getInstance().get(AnalyticsTrackers.Target.APP);
}

synchronized public Tracker getDefaultTracker()
{
    if (mTracker == null)
    {
        GoogleAnalytics analytics = GoogleAnalytics.getInstance(AnalyticsApplication.this);

        mTracker = analytics.newTracker(R.xml.app_tracker);
    }
    return mTracker;
}

public synchronized Tracker getGoogleAnalyticsTracker()
{
    AnalyticsTrackers analyticsTrackers = AnalyticsTrackers.getInstance();
    return analyticsTrackers.get(AnalyticsTrackers.Target.APP);
}

public void trackEvent(String category, String action, String label)
{
    Tracker t = getDefaultTracker();
    t.send(new HitBuilders.EventBuilder().setCategory(category).setAction(action).setLabel(label).build());
}

public static synchronized AnalyticsApplication getInstance()
{
    return mInstance;
}

public void trackScreenView(String screenName)
{
    Tracker t = getGoogleAnalyticsTracker();
    t.setScreenName(screenName);
    t.send(new HitBuilders.ScreenViewBuilder().build());
    GoogleAnalytics.getInstance(this).dispatchLocalHits();
}


public void trackException(Exception e)
{
    if (e != null) {
        Tracker t = getGoogleAnalyticsTracker();
        t.send(new HitBuilders.ExceptionBuilder()
             .setDescription( new StandardExceptionParser(this, null)
             .getDescription(Thread.currentThread().getName(), e))
     .setFatal(false)
     .build()
        );
    }
}

}

  1. And last we can add code in your mainactivity.java class or you required classes Initialize Step1

    AnalyticsApplication application1;

    private Tracker mTracker;

    Step :2

    application1 = (AnalyticsApplication) getApplication();

    mTracker = application1.getDefaultTracker();

if you run this code in google analytics showing screen name you mentioned in xml.

Step :3 Add this code for track event

mTracker.send(new HitBuilders.EventBuilder()

                .setCategory("DashBoard ")

                    .setAction("View Bookings Pressed")

                    .build());

Step :4 Track exception behaviour code add in you catch block

 catch (Exception e) {
         **   AnalyticsApplication.getInstance().trackException(e);**
            e.printStackTrace();
        }

Happy coding..

like image 23
Venkatesh Avatar answered Oct 14 '22 05:10

Venkatesh