Get Context in Android library

joshlf picture joshlf · Jan 12, 2014 · Viewed 11.1k times · Source

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).

Answer

CommonsWare picture CommonsWare · Jan 12, 2014

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.