648

What is the difference between getContext() , getApplicationContext() , getBaseContext() , and "this"?

Though this is simple question I am unable to understand the basic difference between them. Please give some easy examples if possible.

N J
  • 27,217
  • 13
  • 76
  • 96
iCurious
  • 8,161
  • 7
  • 28
  • 46
  • 1
    There is an excellent writeup in the first answer: http://stackoverflow.com/questions/1026973/android-whats-the-difference-between-the-various-methods-to-get-a-context – ky1enamic May 17 '12 at 18:10
  • Possible duplicate of [What's the difference between the various methods to get a Context?](https://stackoverflow.com/questions/1026973/whats-the-difference-between-the-various-methods-to-get-a-context) – Just The Highlights Aug 28 '17 at 21:18

10 Answers10

602
  • View.getContext(): Returns the context the view is currently running in. Usually the currently active Activity.

  • Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.

  • ContextWrapper.getBaseContext(): If you need access to a Context from within another context, you use a ContextWrapper. The Context referred to from inside that ContextWrapper is accessed via getBaseContext().

CaptJak
  • 3,592
  • 1
  • 29
  • 50
Alexander Lucas
  • 22,171
  • 3
  • 46
  • 43
  • 18
    +CooL i3oY same with getContext – Mikey Nov 09 '12 at 08:38
  • 16
    actually i am confuse that what is the proper defination of context?? – Ravi Jan 16 '13 at 11:04
  • 12
    "this" and getContext() both are same – KCRaju Aug 24 '13 at 01:18
  • 1
    +1 for the detailed answer. I would give this another update (if I could) if i contained a real life example of each of the `Context`s so that the forum and I can get a clearer understanding of how they're used. And maybe what object requires which of the `Context`s. – Subby Jan 22 '14 at 10:50
  • What if you get your Application extented class? – Maxrunner Jan 23 '14 at 10:41
  • You said about "Usually the currently active Activity.", what it could be in other cases if not currently active Activity? Thx – Jacob Oct 06 '14 at 13:20
  • 52
    `this` and `getContext()` are not always same e.g. in Activity class, you can use `this` because `Activity` inherits from `Context` but method `getContext()` is not in `Activity` class. @mikedroid @KCRaju – nandan May 07 '15 at 15:17
  • 6
    `this` gives an instance of the class it's in, which could be any class, not necessarily a context. If you use it in an Activity class, then `this` will be an instance of a `Context`. – LarsH Jul 02 '15 at 17:29
  • You can not use `this` in an inner class of an `Activity`, but you can use `getContext()`. – Jeffrey Chen Jan 13 '16 at 15:00
  • Pls incorporate letter A and B into your definition of context withhin context, it's not clear in any answer which context is accessed. – HopefullyHelpful Sep 14 '16 at 16:01
  • This might be Java syntax help to some: `YourActivity.this.getApplicationContext()` will qualify your context from instance of `YourActivity`. Otherwise above answer is great - it is all about the lifecycle of code you are writing - out living the activity/fragment or not. – bgs Apr 25 '17 at 18:31
  • To understand first point **view.getContext()** better refer **[this](http://androidforbeginners.blogspot.com/2009/12/context.html)**. – CoDe Jul 24 '17 at 12:04
  • 3
    `getBaseContext()` needs more explaination perhaps with an example. – CopsOnRoad Nov 12 '17 at 11:02
  • 1
    @nandan you said "getContext() is not in Activity class" what do you mean by that ? I thought we are able to use getContext() in Activity class ? – isJulian00 Jun 14 '19 at 19:37
  • @isJulian00 Activity is a subclass of Context. "context.getContext" would make much sense. "this" already IS the context in Activity. – The incredible Jan Sep 01 '21 at 12:58
  • so for example basecontext would be like for example a state of a button within a view? correct me if I'm wrong – Kipruto May 07 '22 at 11:06
147

Most answers already cover getContext() and getApplicationContext() but getBaseContext() is rarely explained.

The method getBaseContext() is only relevant when you have a ContextWrapper. Android provides a ContextWrapper class that is created around an existing Context using:

ContextWrapper wrapper = new ContextWrapper(context);

The benefit of using a ContextWrapper is that it lets you “modify behavior without changing the original Context”. For example, if you have an activity called myActivity then can create a View with a different theme than myActivity:

ContextWrapper customTheme = new ContextWrapper(myActivity) {
  @Override
  public Resources.Theme getTheme() { 
    return someTheme;
  }
}
View myView = new MyView(customTheme);

ContextWrapper is really powerful because it lets you override most functions provided by Context including code to access resources (e.g. openFileInput(), getString()), interact with other components (e.g. sendBroadcast(), registerReceiver()), requests permissions (e.g. checkCallingOrSelfPermission()) and resolving file system locations (e.g. getFilesDir()). ContextWrapper is really useful to work around device/version specific problems or to apply one-off customizations to components such as Views that require a context.

The method getBaseContext() can be used to access the “base” Context that the ContextWrapper wraps around. You might need to access the “base” context if you need to, for example, check whether it’s a Service, Activity or Application:

public class CustomToast {
  public void makeText(Context context, int resId, int duration) {
    while (context instanceof ContextWrapper) {
      context = context.baseContext();
    }
    if (context instanceof Service)) {
      throw new RuntimeException("Cannot call this from a service");
    }
    ...
  }
}

Or if you need to call the “unwrapped” version of a method:

class MyCustomWrapper extends ContextWrapper {
  @Override
  public Drawable getWallpaper() {
    if (BuildInfo.DEBUG) {
      return mDebugBackground;
    } else {
      return getBaseContext().getWallpaper();
    }
  }
}
Mike Laren
  • 8,028
  • 17
  • 51
  • 70
  • 24
    I would say, this is the most important answer after an accepted one. – 0leg Mar 31 '17 at 08:21
  • 8
    I would say that the existence of `ContextWrapper` is one of the worst decisions ever made by developers of Android framework. When they realized that they created an entire family of God Objects, instead of doing the right thing and refactoring the code toward Single Responsibility, they added an ugly hack that allowed to change Context behavior by deepening the inheritance tree. Bad software engineering at its ugliest. As for us, developers, IMHO no one should ever use `getBaseContext()` or `ContextWrapper`. If you do - it is a huge "code smell". – Vasiliy Nov 23 '17 at 16:53
  • I'd like to see the complete `CustomToast` code. THANKS:))) – Alston Sep 29 '19 at 04:34
  • 1
    Thank you for this answer, I was not aware that ContextWrapper was to be used like this!! I always thought it was something internal from the Android Team. In my sense, this is the expected Answer. T H A N K S !!! – Bawender Yandra Jul 02 '20 at 17:27
47

The question "what is Context" is one of the most difficult questions in the Android universe.

Context defines methods that access system resources, retrieve application's static assets, check permissions, perform UI manipulations and many more. In essence, Context is an example of God Object anti-pattern in production.

When it comes to which kind of Context should we use, it becomes very complicated because except for being God Object, the hierarchy tree of Context subclasses violates Liskov Substitution Principle brutally.

This blog post (now from Wayback Machine) attempts to summarize Context classes applicability in different situations.

Let me copy the main table from that post for completeness:

+----------------------------+-------------+----------+---------+-----------------+-------------------+
|                            | Application | Activity | Service | ContentProvider | BroadcastReceiver |
+----------------------------+-------------+----------+---------+-----------------+-------------------+
| Show a Dialog              | NO          | YES      | NO      | NO              | NO                |
| Start an Activity          | NO¹         | YES      | NO¹     | NO¹             | NO¹               |
| Layout Inflation           | NO²         | YES      | NO²     | NO²             | NO²               |
| Start a Service            | YES         | YES      | YES     | YES             | YES               |
| Bind to a Service          | YES         | YES      | YES     | YES             | NO                |
| Send a Broadcast           | YES         | YES      | YES     | YES             | YES               |
| Register BroadcastReceiver | YES         | YES      | YES     | YES             | NO³               |
| Load Resource Values       | YES         | YES      | YES     | YES             | YES               |
+----------------------------+-------------+----------+---------+-----------------+-------------------+
  1. An application CAN start an Activity from here, but it requires that a new task be created. This may fit specific use cases, but can create non-standard back stack behaviors in your application and is generally not recommended or considered good practice.
  2. This is legal, but inflation will be done with the default theme for the system on which you are running, not what’s defined in your application.
  3. Allowed if the receiver is null, which is used for obtaining the current value of a sticky broadcast, on Android 4.2 and above.

screenshot

Vasiliy
  • 16,221
  • 11
  • 71
  • 127
40

getApplicationContext() - Returns the context for all activities running in application.

getBaseContext() - If you want to access Context from another context within application you can access.

getContext() - Returns the context view only current running activity.

Community
  • 1
  • 1
Jaykumar Patel
  • 26,836
  • 12
  • 74
  • 76
28

Context provides information about the Actvity or Application to newly created components.

Relevant Context should be provided to newly created components (whether application context or activity context)

Since Activity is a subclass of Context, one can use this to get that activity's context

tez
  • 4,990
  • 12
  • 47
  • 67
3

getApplicationContext()

this is used for application level and refer to all activities.

getContext() and getBaseContext()

is most probably same .these are reffered only current activity which is live.

this

is refer current class object always.

Jatin Bansal
  • 123
  • 8
2

this: current class object

getContext(): return context for current live activity

getApplicationContext(): return all activities which are running in application

Abolee
  • 36
  • 2
1

From this docs

I understood that you should use:

Try using the context-application instead of a context-activity

mehmet
  • 1,558
  • 5
  • 30
  • 41
1

A Context is:

  • an abstract class whose implementation is provided by the Android system.
  • It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
Hafnernuss
  • 2,659
  • 2
  • 29
  • 41
1

getApplicationContext() - it's Returns the context for all activities running in application.

getBaseContext() - when you want to access Context from another context within application you can access.

getContext() - it's Returns the context view only current running activity.

this - it's refers to the current class object

This refers to the current activity class object, and activity inherits context, so this must be used where context or activity can be used.

Shirsh Shukla
  • 5,491
  • 3
  • 31
  • 44