Difference between Activity Context and Application Context Ask Question

Difference between Activity Context and Application Context Ask Question

This has me stumped, I was using this in Android 2.1-r8 SDK:

ProgressDialog.show(getApplicationContext(), ....);

and also in

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

using getApplicationContext() crashes both ProgressDialog and Toast .... which lead me to this question:

What is the actual differences between a activity context and application context, despite sharing the wording 'Context'?

ベストアンサー1

They are both instances of Context, but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.

If you read the docs at getApplicationContext it notes that you should only use this if you need a context whose lifecycle is separate from the current context. This doesn't apply in either of your examples.

The Activity context presumably has some information about the current activity that is necessary to complete those calls. If you show the exact error message, might be able to point to what exactly it needs.

But in general, use the activity context unless you have a good reason not to.

おすすめ記事