How to implement google analytics in android?
@elmo.conroy
To implement Google Analytics in Android, you can follow these steps:
1
|
implementation 'com.google.android.gms:play-services-analytics:17.0.0' |
1 2 |
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> |
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 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.