Salivan
Salivan

Reputation: 1903

The right use of the Context

I use Context pretty often in my applications and I have heard that it often causes memory leaks and other problems so I have a couple of related questions.

What Context is best to use: should I always use getApplicationContext() or, if possible, Activity like with getActivity() in a Fragment or this in an Activity or the Context object that usually comes as a parameter from constructors or methods like onReceive() if I am inside a Broadcast Receiver?

How to release the Context related objects? Simply assign null to variables that hold a reference to Context object when I don't need it anymore?

What if I had used some Context to instantiate a Toast, ProgressDialog, TextView or another object? Should I release references to these objects too to avoid memory leaks?

Is it a good practice to keep Context object in a global variable? Because I often need it in inner classes or methods.

I hope to get some clear clarifications, explanations, links to related topics.

Upvotes: 2

Views: 78

Answers (2)

Sergi and Replace
Sergi and Replace

Reputation: 829

Different context have different capabilities (for example, only Activity context can start another Activity).

Check great article about how to use context: http://www.doubleencore.com/2013/06/context/

One of the common pitfalls is for example, to use Activity context on AsyncTask. The major problem here is that the activity could be finished (and the context destroyed) while the AsyncTask is still working. If it tries to use the context for any operation, it will fail. In this case, is much better to use the context received in the constructor (or any other method) to retrieve the Application context.

Upvotes: 3

Christopher Francisco
Christopher Francisco

Reputation: 16288

Always use the Context reference for the component, and by that I mean, use this for Activity and Service; use the {@param context} for BroadcastReceiver.

Only use getApplicationContext() for Singleton that have to be init in Application#onCreate()

Upvotes: 1

Related Questions