How to implement google analytics in android?

by elmo.conroy , in category: SEO Tools , 3 months ago

1 answer

by priscilla.langworth , 3 months ago

@elmo.conroy 

To implement Google Analytics in Android, you can follow these steps:

  1. Create a Google Analytics account and set up a property for your Android app.
  2. Open your project in Android Studio and add the Google Analytics dependency in your app-level build.gradle file:
1
implementation 'com.google.android.gms:play-services-analytics:17.0.0'


  1. Add the following permissions to your AndroidManifest.xml file:
1
2
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


  1. Initialize the Google Analytics Tracker in your Application class or a suitable entry point of your app:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;

public class MyApplication extends Application {
    private Tracker tracker;
    
    public synchronized Tracker getDefaultTracker() {
        if (tracker == null) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            tracker = analytics.newTracker("YOUR_TRACKING_ID");
        }
        return tracker;
    }
}


Replace "YOUR_TRACKING_ID" with the tracking ID obtained from your Google Analytics property.

  1. In your Activities or Fragments, you can then send events, screen views, or any other data you want to track:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

public class MainActivity extends AppCompatActivity {
    private Tracker tracker;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        tracker = ((MyApplication) getApplication()).getDefaultTracker();
        
        // Set screen name for Google Analytics
        tracker.setScreenName("MainActivity");
        tracker.send(new HitBuilders.ScreenViewBuilder().build());
        
        // Send events to Google Analytics
        tracker.send(new HitBuilders.EventBuilder()
            .setCategory("Category")
            .setAction("Action")
            .setLabel("Label")
            .build());
    }
    
    // ...
}


That's it! Google Analytics is now integrated into your Android app. You can check the real-time and historical data in your Google Analytics account dashboard.