Get Context in Android library

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 .

answered Jan 12, 2014 at 0:06 CommonsWare CommonsWare 1.0m 192 192 gold badges 2.4k 2.4k silver badges 2.6k 2.6k bronze badges

Hi @CommonsWare, thanks for your answer but could you elaborate on what you mean by "This will not work"? From what I understand, it would work, but extending Application would be unnecessary as long as you already have a reference to a Context? Thanks for your time :)

Commented Jan 12, 2014 at 0:14

@TheIT: Yeah, that sentence was poorly phrased, so I fixed it. My apologies for the confusion. BTW, since you seem focused on Application , if you have not done so already, you might want to read Dave Smith's excellent post on choosing the right Context for the, um, context: doubleencore.com/2013/06/context Application is the right answer, particularly if you need a Context for something that will be referenced from a static data member, but often it is used in cases where it is inappropriate.