How do I add Google Analytics to my Android app?

Asked

Viewed 360 times

5

I want to use Google Analytics to collect more information about using my apps, such as adding Google Analytics to my Android app?

1 answer

7

Project setup

Update the file AndroidManifest.xml of your project to include permissions INTERNET and ACCESS_NETWORK_STATE:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.analytics">

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

  <application android:name="AnalyticsApplication">
    ...
  </application>
</manifest>

The Google Services plugin for Gradle analyzes information from google-services.json file configuration.

To add the plug-in to your project, update your build.Gradle project and build.Gradle files at the application level as follows:

  1. Add the dependency to the file build.gradle at the project level:

    classpath 'com.google.gms:google-services:1.5.0-beta2'
    
  2. Add the plug-in to the file build.gradle at the application level:

    apply plugin: 'com.google.gms.google-services'
    

Now, you need to add a dependency to Google Play Services. Within the build.Gradle file of your app, add:

compile 'com.google.android.gms:play-services-analytics:8.4.0'

Accessing a configuration file

The configuration file provides specific service information for your app. To access it, you need to select a existing project for your application or create a new one. You also need to provide a package name for your app.


Note: You need to have a Google Analytics account and a registered property to access the configuration file.

Click on the link below to access a configuration file to be added to your project.

ACCESS A CONFIGURATION FILE

Add the configuration file to your project

Copy the google-services.json file you just received in the app/ or mobile/ directory of your Android Studio project.

/*
 * Copyright Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples.quickstart.analytics;

import android.app.Application;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

/**
 * This is a subclass of {@link Application} used to provide shared objects for this app, such as
 * the {@link Tracker}.
 */
public class AnalyticsApplication extends Application {
  private Tracker mTracker;

  /**
   * Gets the default {@link Tracker} for this {@link Application}.
   * @return tracker
   */
  synchronized public Tracker getDefaultTracker() {
    if (mTracker == null) {
      GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
      // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
      mTracker = analytics.newTracker(R.xml.global_tracker);
    }
    return mTracker;
  }
}
AnalyticsApplication.java

Activity ou Fragment

Open the activity you want to follow.

You can also follow a Fragment, but it needs to represent correctly display the screen.

Include in the method onCreate of the Activity or Fragment you want to track to access the shared Tracker instance:

// Obtain the shared Tracker instance.
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();

Include the code below in the appropriate method, such as onResume for an Activity or onPageSelected to a Viewpager for the purpose of registering when the screen changes.

Log.i(TAG, "Setting screen name: " + name);
mTracker.setScreenName("Image~" + name);
mTracker.send(new HitBuilders.ScreenViewBuilder().build());

Add the tracking code to each Activity or Fragment that represents a screen. Define a name within each Activity or Fragment if you want to differentiate screen views for your app in Google Analytics. All activities recorded on the shared tracker send the latest screen name until it is overwritten or deleted (set to null).

Sending an event

To send an event, set the values of the screen fields in the tracker and send the hit. The following example uses Hitbuilders.Eventbuilder to submit an Event:

mTracker.send(new HitBuilders.EventBuilder()
    .setCategory("Action")
    .setAction("Share")
    .build());

Complete Code:

Mainactivity.java:

/*
 * Copyright Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples.quickstart.analytics;

import java.util.Locale;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

/**
 * Activity which displays numerous background images that may be viewed. These background images
 * are shown via {@link ImageFragment}.
 */
public class MainActivity extends AppCompatActivity {
  private static final String TAG = "MainActivity";

  private static final ImageInfo[] IMAGE_INFOS = {
      new ImageInfo(R.drawable.favorite, R.string.pattern1_title),
      new ImageInfo(R.drawable.flash, R.string.pattern2_title),
      new ImageInfo(R.drawable.face, R.string.pattern3_title),
      new ImageInfo(R.drawable.whitebalance, R.string.pattern4_title),
  };

  /**
   * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each image.
   * This uses a {@link FragmentPagerAdapter}, which keeps every loaded fragment in memory.
   */
  @SuppressWarnings("FieldCanBeLocal")
  private ImagePagerAdapter mImagePagerAdapter;

  /**
   * The {@link ViewPager} that will host the patterns.
   */
  private ViewPager mViewPager;

  /**
   * The {@link Tracker} used to record screen views.
   */
  private Tracker mTracker;

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

    // [START shared_tracker]
    // Obtain the shared Tracker instance.
    AnalyticsApplication application = (AnalyticsApplication) getApplication();
    mTracker = application.getDefaultTracker();
    // [END shared_tracker]

    // Create the adapter that will return a fragment for each image.
    mImagePagerAdapter = new ImagePagerAdapter(getSupportFragmentManager(), IMAGE_INFOS);

    // Set up the ViewPager with the pattern adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mImagePagerAdapter);

    // When the visible image changes, send a screen view hit.
    mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
      @Override
      public void onPageSelected(int position) {
        sendScreenImageName();
      }
    });

    // Send initial screen screen view hit.
    sendScreenImageName();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
      case R.id.menu_share:
        // [START custom_event]
        mTracker.send(new HitBuilders.EventBuilder()
            .setCategory("Action")
            .setAction("Share")
            .build());
        // [END custom_event]

        String name = getCurrentImageTitle();
        String text = "I'd love you to hear about " + name;

        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, text);
        sendIntent.setType("text/plain");
        startActivity(sendIntent);
        break;
    }
    return false;
  }

  /**
   * Return the title of the currently displayed image.
   * @return title of image
   */
  private String getCurrentImageTitle() {
    int position = mViewPager.getCurrentItem();
    ImageInfo info = IMAGE_INFOS[position];
    return getString(info.title);
  }

  /**
   * Record a screen view hit for the visible {@link ImageFragment} displayed
   * inside {@link FragmentPagerAdapter}.
   */
  private void sendScreenImageName() {
    String name = getCurrentImageTitle();

    // [START screen_view_hit]
    Log.i(TAG, "Setting screen name: " + name);
    mTracker.setScreenName("Image~" + name);
    mTracker.send(new HitBuilders.ScreenViewBuilder().build());
    // [END screen_view_hit]
  }

  /**
   * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
   * one of the sections/tabs/pages.
   */
  public class ImagePagerAdapter extends FragmentPagerAdapter {

    private final ImageInfo[] infos;

    public ImagePagerAdapter(FragmentManager fm, ImageInfo[] infos) {
      super(fm);
      this.infos = infos;
    }

    @Override
    public Fragment getItem(int position) {
      ImageInfo info = infos[position];
      return ImageFragment.newInstance(info.image);
    }

    @Override
    public int getCount() {
      return infos.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
      if (position < 0 || position >= infos.length) {
        return null;
      }
      Locale l = Locale.getDefault();
      ImageInfo info = infos[position];
      return getString(info.title).toUpperCase(l);
    }
  }
}

Analyticsapplication.java

/*
 * Copyright Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples.quickstart.analytics;

import android.app.Application;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

/**
 * This is a subclass of {@link Application} used to provide shared objects for this app, such as
 * the {@link Tracker}.
 */
public class AnalyticsApplication extends Application {
  private Tracker mTracker;

  /**
   * Gets the default {@link Tracker} for this {@link Application}.
   * @return tracker
   */
  synchronized public Tracker getDefaultTracker() {
    if (mTracker == null) {
      GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
      // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG
      mTracker = analytics.newTracker(R.xml.global_tracker);
    }
    return mTracker;
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.