18

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
nhaarman
  • 98,571
  • 55
  • 246
  • 278

3 Answers3

17

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);
Community
  • 1
  • 1
Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242
4

They are different for sure. These are different contexts, and should be used with the least possible scope(context).

For example if we can use Activity's Context instead of ApplicationContext, one should use the activity context, same applies to application context, and base context.

nhaarman
  • 98,571
  • 55
  • 246
  • 278
jeet
  • 29,001
  • 6
  • 52
  • 53
  • 1
    It is true, but not for `getBaseContext`. `getBaseContext` is a method of `ContextWrapper` class. Developer can't definetely know which context is wrapped with it. – Olegas Feb 10 '12 at 12:40
  • This makes sense but I'm curious about the "why" of this maxim. And is there a functional difference between starting an activity from another activity or application context? – Daniel Dickison Nov 07 '17 at 19:50
-2

You do it like this....

Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivity(intent);
FabianCook
  • 20,269
  • 16
  • 67
  • 115