Google Analytics SDK Fundamental
Reference https://developers.google.com/analytics/devguides/collection/android/v4/
add permissions to Manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Configure Gradle
project-level build.gradle:
classpath 'com.google.gms:google-services:3.0.0'
app-level build.gradle:
apply plugin: 'com.google.gms.google-services'
compile library
compile 'com.google.android.gms:play-services-analytics:10.0.1'
Get your google-services.json file
Go to here and click "GET A CONFIGURATION FILE".
Copy the
google-services.json
file you just downloaded into the app/ or mobile/ directory of your Android Studio project.
Add Screen Tracking
Need to do the following task:
- Provide the shared tracker via an Application subclass.
- Override the callback method for the foreground activity.
Provide a name for the screen and execute tracking.
1.Application
Subclass Application class like a boss
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; } }
2.Foreground Activity(Activity or Fragment)
Override
onCreate
method// Obtain the shared Tracker instance. AnalyticsApplication application = (AnalyticsApplication) getApplication(); mTracker = application.getDefaultTracker();
You can send information in the lifecycle you like
Log.i(TAG, "Setting screen name: " + name); mTracker.setScreenName("Image~" + name); mTracker.send(new HitBuilders.ScreenViewBuilder().build());
If you need to listen event or actions, add the f*llowing code
mTracker.send(new HitBuilders.EventBuilder() .setCategory("Action") .setAction("Share") .build());
Why we are using GA?
1.We can get the following info:
- The number of users and sessions
- Session duration
- Operating systems
- Device models
- Geography
2.Log Events
tracker.send(new HitBuilders.EventBuilder()
.setCategory("Achievement")
.setAction("Earned")
.setLabel("5 Dragons Rescued")
.setValue(1)
.build());
tracker.send(new HitBuilders.EventBuilder()
.setCategory("Barren Fields")
.setAction("Rescue")
.setLabel("Dragon")
.setValue(1)
.build());
// Build and send a timing hit.
tracker.send(new HitBuilders.TimingBuilder()
.setCategory("Barren Fields")
.setValue(45000) // 45 seconds.
.setVariable("First Rescue")
.setLabel("Dragon")
.build());
3.Other Feature
Campaigns
Crashes and Reports
Custom Dimensions and Metrics
...