What is different between MainActivity.this vs getApplicationContext()

  • MainActivity.this only works if you are in an inner class of MainActivity.

  • If you are in MainActivity itself, just use this.

  • If you are in another class entirely, you need to pass it an instance of a context from the Activity you are in.

Hope this helps..


This explanation is probably missing some subtle nuances but it should give you a better understanding of why one works but the other doesn't.

The difference is that MainActivity.this refers to the current activity (context) whereas the getApplicationContext() refers to the Application class.

The important differences between the two are that the Application class never has any UI associations and as such has no window token.

Long story short: For UI items that need context, use the Activity.


Which context to use?

There are two types of Context:

Application context is associated with the application and will always be the same throughout the life of application; it does not change. So if you are using Toast, you can use application context or even activity context (both) because Toast can be displayed from anywhere within your application and is not attached to a specific window. But there are many exceptions. One such exception is when you need to use or pass the activity context.

Activity context is associated with the activity and can be destroyed if the activity is destroyed; there may be multiple activities (more than likely) with a single application. Sometimes you absolutely need the activity context handle. For example, should you launch a new Activity, you need to use activity context in its Intent so that the newly-launched activity is connected to the current activity in terms of activity stack. However, you may also use application's context to launch a new activity, but then you need to set flag Intent.FLAG_ACTIVITY_NEW_TASK in intent to treat it as a new task.

Let's consider some cases:

MainActivity.this refers to the MainActivity context which extends Activity class but the base class (Activity) also extends Context class, so it can be used to offer activity context.

getBaseContext() offers activity context.

getApplication() offers application context.

getApplicationContext() also offers application context.

For more information please check this link.

Tags:

Android