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
252 views
in Technique[技术] by (71.8m points)

android - Use of Context to start another Activity

To start an Activity you need an Intent, like:

Intent i = new Intent(context, class)

So to fill in the context parameter, a couple of options are available:

  • Use MyActivity.this or just this
  • Use getApplicationContext()
  • Use getBaseContext()

And I'm sure there are one or two more options. These options all appear in some sort of tutorial, one uses the first, the next uses the third option.

So which one should I use? Does it even matter? Is it different for different cases?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yes its different for different cases,

It depends on the scope. Suppose if you are creating a method in a global class that extends Application to create a Toast that is used in every class of your Application you can use getApplicationContext() to create it.

If you want to create a view that is restricted to that particular Activity you can use Activity.this

Also if you want to create an AlertDialog in some inner class say AsyncTask, then you have to use Activity.this, because the AlertDialog is to be linked to Activity itself.

Also don't use getBaseContext() just use the Context that you are having. For getting further information for the same you can see this Answer.

So, the answer to the real question is better to use Activity.this to start a new Activity.

Intent intent = new Intent(Current_Activity.this, Calling.class);
startActivity(intent);

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

...