Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Context in Android library

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:

  • Have my library classes extend Application, and call getApplicationContext()
    • This is generally discouraged
  • Have my library classes each implement the singleton pattern, and have each caller pass in a Context each time they get a reference to the singleton.
    • This requires every caller to retrieve the Application Context before using the library, and also requires that the caller call against an instance of the library instead of against static methods defined on the library class (and thus further requires keeping a reference to this instance).
like image 385
joshlf Avatar asked Jan 11 '14 23:01

joshlf


2 Answers

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.

like image 139
CommonsWare Avatar answered Oct 13 '22 01:10

CommonsWare


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

like image 31
Droid Teahouse Avatar answered Oct 13 '22 00:10

Droid Teahouse