In various bits of Android code I 've seen:
Public class myactivity extends activity {
Public void method (){
Mcontext = This; // Since activity extends Context
Mcontext = getapplicationcontext ();
Mcontext = getbasecontext ();
}
}
However I can't find any decent explanation of which is preferable, and under what circumstances which shocould be used.
Pointers to documentation on this, and guidance about what might break if the wrong one is chosen, wocould be much appreciated.
I agree that documentation is sparse when it comes to contexts in Android, but you can piece together a few facts from varous sources.
This blog post on the official Google Android Developers blog was written mostly to help address memory leaks, but provides some good information about contexts as well:
In a regular Android Application, you usually have two kinds of context, activity and application.
Reading the article a little bit further tells about the difference between to the two and why you might want to consider using the application context (activity. getapplicaitoncontext () rather than using the activity context ("this "). basically the application
Context is associated with the applicaiton and will always be the same throughout the life cycle of you app, where as the activity context is associated with the activity and cocould possible be destroyed stored times as the activity is destroyed during Screen
Orientation changes and such.
I couldn't find really anything about when to use getbasecontext () other than a for a one liner from Dianne hackborn, one of the Google engineers working on the android SDK:
Don't use getbasecontext (), just use the context you have.
That was from a post on the Android-developers newsgroup, you may want to consider asking your question there as well because a handful of the people working on Android actual monitor that newsgroup and answer questions.
So overall it seems preferable to use the global application context when possible.
I got bad window token errors when using application context to progress dialog. So I used activity context instead.