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
I am not sure best practice for this case but i would like to set the Context in my singleton class during Application onCreate.
MyLibrary.init(this);
Why? If you had use Crashlytic/Fabric before, you will found that they are using
Fabric.with(this, new Crashlytics());
If you read the code in Fabric will found that they store the Context in Fabric singleton.
Facebook Android SDK did similar thing:
FacebookSdk.sdkInitialize(getApplicationContext());
If your browse their codes will found that they store static Context.
Well, which are the best practices? I am not sure but i believe those are awesome developers create awesome libraries and they did debate on this before come out this libraries. Anyway, I am still learning how to write best android library and come across this topics.
App Startup library is the part of Android Jetpack. It allows to listen application startup without the cost of multiple ContentProviders. Also, it provides the ability to handle dependencies tree.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.