getApplicationContext()与this,getBaseContext() ---有时间翻译一下

来源:互联网 发布:如何自学大数据 编辑:程序博客网 时间:2024/05/16 01:01
 

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 should be used. 

Pointers to documentation on this, and guidance about what might break if the wrong one is chosen, would 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 various 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 could possible be destroyed many 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.