Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

Diffinitive rules for using Android's getBaseContext, getApplicationContext or using an Activity's "this"

I've googled this question a lot and have found many differing recommendations on when to use getBaseContext, getApplicationContext or an Activity's own this pointer.

Three rules that come up often and seem to make a lot of sense are -

  1. For a long-lived reference to a context activity getApplicationContext should be used as this exists as long as your application exists
  2. For contexts whose life-cycles are bound to their activities, their own activity context (this) should be used
  3. Store context pointers statically only with great caution (and, if possible, not at all)

Assuming these are correct, what is the use of getBaseContext?

I've seen a great many examples where new intents are created using -

Intent intent = new Intent(getBaseContext(), myClass.class);

As opposed to -

Intent intent = new Intent(this, myClass.class);

Which is the correct, or recommended, method and why?

question from:https://stackoverflow.com/questions/5458156/diffinitive-rules-for-using-androids-getbasecontext-getapplicationcontext-or-u

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The getBaseContext() is the method of ContextWrapper. And ContextWrapper is, "Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context." (as per javadocs)

So this is used to delegate the calls to another context.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...