What is difference between this and getContext(), when I say this I mean this within an Activity.
- 5,753
- 72
- 57
- 129
- 31,523
- 64
- 157
- 244
3 Answers
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).
If class extends
ContextWrapperthen you can usethisasContext. Such classes normally do not havegetContext()method.Those classes that do not extend
ContextWrapperbut still save and useContextnormally exposegetContext()function. And you cannot usethisasContextin 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.
- 74,247
- 24
- 188
- 156
-
7Actually, 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
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).
- 232,168
- 48
- 399
- 521
There is no difference. When you are in an Activity, getContext() will return this. This is because an Activity is a context!
- 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