Alex Rivera | Logout

When to call activity context OR application context?

Asked 2011-09-04T11:02:11.823
281

I do not fully understand the activity context vs the application context.

As I understand it so far, each is an instance of its class, which means that some programmers recommend you to use this.getApplicationContext() as often as possible in order to not "leak" out any memory. This is because the other this (getting the Activity instance context) points to an Activity that is being destroyed each time the user tilts the phone, or leave the app, etc., which the Garbage Collector (GC) apparently doesn't catch and therefore the app uses too much memory.

But where would it be right to use this (getting the context of the current Activity instance) and the application context would be useless/wrong?

Edit
Report

1 Answer

4

Two great examples of when you should use Activity context vs. the Application context are when displaying either a Toast message or a built-in Dialog message as using the Application context will cause an exception:

ProgressDialog.show(this, ....);

or

Toast t = Toast.makeText(this,....);

Both of these need information from the Activity context that is not provided in the Application context.

answered 2011-09-04T11:38:57.147

Your Answer