jtnire
jtnire

Reputation: 1358

Android - Best way to use contexts

I've got a quick question on the best way to handle Android contexts. A lot of things (e.g. Service) require that you pass a context as a parameter. At the present time, I have a public static variable that is set to point to getApplication() and I just refer to this throughout my application where a context is required.

Is this ok to do? Or is there a better method to handle this? A lot of my classes don't extend Activity or service and as such, don't have access to this.getApplication().

Everything seems to work ok when I just pass in my static variable.

Upvotes: 2

Views: 687

Answers (2)

Jeffrey Blattman
Jeffrey Blattman

Reputation: 22637

At the present time, I have a public static variable that is set to point to getApplication() and I just refer to this throughout my application where a context is required.

Is this ok to do?

No.

A context applies to the context in which it was obtained. That is, an activity has context for that activity, a service has context for the service, and so on. Now, a lot of folks do what you are doing, and as you observe, it seems to work. That doesn't mean it will continue to work or that it's good design. If that was the proper pattern, Android would have been designed with Context.INSTANCE that is available statically.

An activity, service, and application are contexts (isA). Receivers are passed a context to their onHandlerIntent() method. For all other classes you write, just get used to constructing them with a context. Out of habit, whenever I create a new class, I automatically add a constructor that accepts a context and add a private field to hold it.

When you need a context in a static method, you should pass it in directly as a parameter.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006584

Is this ok to do?

The Application object, in some cases, will fail to work. For example, it sucks for UI-related stuff.

Dianne Hackborn, a leading Android engineer, has stated her regret at Application existing in the first place.

My general advice is to use Application only when you know specifically why it is superior to using your Activity, Service, etc. There are cases when it is the better answer (e.g., binding to services).

A lot of my classes don't extend Activity or service and as such, dont have access to this.getApplication().

Pass a suitable Context as a parameter, as the Android SDK does.

Upvotes: 1

Related Questions