31

I'm trying decide which of the following is the proper way to do this:

  1. Calling FirebaseAnalytics.getInstance(Context) from every activity, fragment, and service that I'm logging an event from.

or

  1. Calling FirebaseAnalytics.getInstance(Context) once from Application class and keeping it around as a public static variable. Then, from everywhere I need this I can call `MyAppClass.mFirebaseAnalytics.logEvent()'.

Will any of the above methods have a undesired impact on the events that are automatically collected and/or do either of those have an efficiency gain over the other?

Many thanks!

4
  • Select a correct answer. Commented Nov 8, 2016 at 15:19
  • 1
    @fahmy Did you get any chance to find out the difference of using 1 and 2? I am using Firebase V 10.2.0. And looking upon the usage of context inside the Firebase decompiled classes, I am seeing the context is used to get application context only. For activity and stuff, there is method firebaseAnalytics.setCurrentScreenwhere we can name the activity and stuff. So, my guess right now is that using application context is enough, but I haven't tested it yet.
    – laaptu
    Commented Jul 11, 2017 at 4:42
  • @laaptu Nope, apart from the answer below, haven't got any new info on this.
    – fahmy
    Commented Jul 13, 2017 at 3:52
  • You need to be a little bit careful because it's possible to access MyAppClass.mFirebaseAnalytics when it is still null
    – Mark
    Commented Sep 7, 2017 at 10:06

1 Answer 1

12

The documentation states:

public static FirebaseAnalytics getInstance (Context context)

Returns the singleton FirebaseAnalytics interface.

So I don't see any particular reason why you can't just have a singleton instance in your code. There won't be any noticeable efficiency gains with either approach. If you're looking into the second option, it might be worth considering doing this with dependency injection and a simple wrapper around the analytics instance to increase the testability of your code.

2
  • 15
    I am worried that Firebase might use the context to derive something about life-time or flow of application. All guidelines I've read only states it should be put in Activity.
    – jayeffkay
    Commented Jan 13, 2017 at 12:42
  • Response to jayeffkay's comment: if it's a singleton and you're not passing in a lifecycle owner, why would it matter where you initialize it? Looking at the docs I see there are already some automatically collected events support.google.com/firebase/answer/6317485
    – Markymark
    Commented Apr 8, 2020 at 6:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.