I'm writing an Android app that has some functionality encapsulated in an internal library. However, for this functionality to work, the library needs an instance of the Application Context. What's the best way to give the library this Context? I see a few options, none of them appealing:
Application
, and call getApplicationContext()
Context
each time they get a reference to the singleton.
What's the best way to give the library this Context?
Pass a Context
into the methods exposed by your library that need a Context
. This is what the Android SDK does in places.
Or, change your library to expose objects, not static methods, and have the objects hold an instance of Context
(supplied to the constructor or factory method that created the instance).
Have my library classes extend Application, and call getApplicationContext()
If you can call getApplicationContext()
on a Context
, you would just do that, without needing to subclass Application
.
This is a solution that I found, which I have not tested, but is used by Firebase apparently to avoid creating an init method:
"What happens on Application start is, that it registers all ContentProviders in the system (calling onCreate). This means that at this point no activity has been started, but we have access to the (Application)Context, where we can initialise our library using this Context"
Essentially you are utilizing the onCreate of the empty ContentProvider as the init. It is hacky, but seamless.
https://medium.com/@andretietz/auto-initialize-your-android-library-2349daf06920
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With