33

What is difference between this and getContext(), when I say this I mean this within an Activity.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Lukap
  • 31,523
  • 64
  • 157
  • 244

3 Answers3

63

In general there are two type of classes. Ones that extend ContextWrapper class (Activity, Service, Application) and those that do not extend it (like View).

  1. If class extends ContextWrapper then you can use this as Context. Such classes normally do not have getContext() method.

  2. Those classes that do not extend ContextWrapper but still save and use Context normally expose getContext() function. And you cannot use this as Context in such cases.

And these two cases are mutually exclusive. At least I don't recall classes that extend ContextWrapper and have getContext at the same time.

inazaruk
  • 74,247
  • 24
  • 188
  • 156
  • 7
    Actually, the important type is `Context`, not `ContextWrapper` (which is a subclass of `Context`). So, for instance, a `MockContext` can also use `this` where a `Context` is required, even though `MockContext` does not extend `ContextWrapper`. – Ted Hopp Jan 03 '13 at 03:37
  • What about getBaseContext()? – powder366 Nov 19 '16 at 13:58
16

getContext() is not defined in an Activity. It's used in a View (or View subclass) to get a reference to the enclosing context (an Activity).

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
5

There is no difference. When you are in an Activity, getContext() will return this. This is because an Activity is a context!

Justin Breitfeller
  • 13,737
  • 4
  • 39
  • 47
  • Than when is a difference between this and getContext() is there a difference when we use Service (maybe brodcast receiver...) ,I mean is there any place where this will not suffice and there will be need for getContext() ? – Lukap Jun 03 '11 at 15:28
  • 1
    In a View, `getContext()` returns the containing activity. – Ted Hopp Jun 03 '11 at 15:30