How do I add Google Analytics to my Android app?

5

I want to use Google Analytics to gather more information about using my apps, like adding Google Analytics to my Android app?

    
asked by anonymous 29.05.2016 / 11:40

1 answer

7

Project Configuration

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

<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 plug-in for Gradle parses information from   google-services.json file configuration.

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

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

    classpath 'com.google.gms:google-services:1.5.0-beta2'
    
  • Add the plug-in to the build.gradle file 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 application, add:

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

    Access a configuration file

      

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

      

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

    Click the link below to access a configuration file to add to your project.

    ACCESSING A CONFIGURATION FILE

    Add the configuration file to your project

    Copy the google-services.json file that you just received into 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 track.

      

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

    Include in the onCreate method of the Activity or Fragment that 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 for a ViewPager in order to register 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 in the shared crawler send the most recent screen name until it is replaced 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 send an Event:

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

    Full 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;
      }
    }
    
        
    29.05.2016 / 15:03