0

I was thinking if there is a way to determine what is the best context to pass to methods like Toast.makeText() or when getting SharedPreferences like with context.getSharedPreferences().. Is there a reason not for using always the Application context in place of Activity or IntentService contexts, for example?

Gianni Costanzi
  • 6,054
  • 11
  • 48
  • 74

1 Answers1

0

To explain the difference, Copied from https://stackoverflow.com/a/4128799/1143977

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.

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.

Community
  • 1
  • 1
VendettaDroid
  • 3,131
  • 2
  • 28
  • 41
  • They're saying the opposite on the [Android Developer Blog](http://android-developers.blogspot.it/2009/01/avoiding-memory-leaks.html), i.e. try to avoid Activity-context and use Application-context instead.. – Gianni Costanzi Sep 05 '12 at 21:52
  • IMO, I think what they are trying to say is, if you are planning to have context for long life of object then application context is a good idea. They are telling us to avoid activity context in that cases only. Whereas in my understanding you can use activity context for rest. – VendettaDroid Sep 05 '12 at 21:58