1

Added this line to dependencies in build.gradle:

classpath 'com.google.gms:google-services:3.0.0'

Also added this line to dependencies in app/build.gradle:

compile 'com.google.firebase:firebase-core:10.0.1'

Now the part I'm not sure is do I have to run this code at least once to even start automatic logging?

FirebaseAnalytics.getInstance(this);

Or is it only required if I want to log custom events and want to have a reference to the analytics instance?

Alireza
  • 100,211
  • 27
  • 269
  • 172
Taylan
  • 3,045
  • 3
  • 28
  • 38

2 Answers2

3

When you just include the Firebase Analytics (now called Google Analytics for Firebase) SDK, it automatically logs many basic analytics events. No code is needed for that.

If you want to log custom events, you'll indeed have to get an instance of the FirebaseAnalytics class and then call logEvent as Emilio shows.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
2

Yes, you have to run this code when you start your app: FirebaseAnalytics.getInstance(this);.

You can run this in your MainActivity onCreate. And that is all set!

But, if you want to log events, then you have to save the value from this code, like this: FirebaseAnalytics mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

And finally you create the event and log it to Firebase, using these lines:

Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, id);
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, name);
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
tyczj
  • 71,600
  • 54
  • 194
  • 296