What is different between MainActivity.this vs getApplicationContext()
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.
Are Context and MainActivity.this different?
getApplicationContext()
(somewhat unsurprisingly) returns the application context, whilst MainActivity.this
is itself an activity context. Themes associated with your activity will differ from your application. They aren't the same thing.
if these are different, Complier didn't display red line in code.
You wont see an error, because it's only a Context
that is requested. I haven't tried it, but you probably could use an Application
instance so long as you specify the theme as well by using new AlertDialog.Builder(getApplicationContext(), /* theme res id */)
However, all the examples in the Android documentation use an Activity context, so I'd suggest you just go with that.
Difference between Activity Context and Application Context
They are both instances of Context, but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.
If you read the docs at getApplicationContext it notes that you should only use this if you need a context whose lifecycle is separate from the current context. This doesn't apply in either of your examples.
The Activity context presumably has some information about the current activity that is necessary to complete those calls. If you show the exact error message, might be able to point to what exactly it needs.
But in general, use the activity context unless you have a good reason not to.
Is there any difference between Activityname.this() & this?
Is there any difference between Activityname.this() & this in Android ?
This depends on where you are calling it from. If you are inside the Activity
, not inside of a listener or inner class like in onCreate
then no. They both refer to the Activity context
.
If you are say inside of an onClickListener
then yes. this
refers to the listener
and you need to use ActivityName.this
or something like
someButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Intent i = (v.getContext(), NextActivity.class); use the button context which will be the same as the activity context
startActivity(i);
}
});
This will be the same as when using a Dialog
or AlertDialog
, you will want to use ActivityName.this
This is an answer that talks about the difference of Context
s but there's a better one I will see if I can find
A great Context explanation
Edit for more completeness
AFAIK, getApplicationContext()
or ActivityName.this
is fine for Toasts
. The example in the docs uses getApplicationContext()
. But the Toast Docs says
Parameters
context The context to use. Usually your Application or Activity object.
So there may be certain instances where one is better but I have always used Activity Context
and I guess I will until I am corrected on this.
When to call activity context OR application context?
getApplicationContext()
is almost always wrong. Ms. Hackborn (among others) have been very explicit that you only use getApplicationContext()
when you know why you are using getApplicationContext()
and only when you need to use getApplicationContext()
.
To be blunt, "some programmers" use getApplicationContext()
(or getBaseContext()
, to a lesser extent) because their Java experience is limited. They implement an inner class (e.g., an OnClickListener
for a Button
in an Activity
) and need a Context
. Rather than using MyActivity.this
to get at the outer class' this
, they use getApplicationContext()
or getBaseContext()
to get a Context
object.
You only use getApplicationContext()
when you know you need a Context
for something that may live longer than any other likely Context
you have at your disposal. Scenarios include:
Use
getApplicationContext()
if you need something tied to aContext
that itself will have global scope. I usegetApplicationContext()
, for example, inWakefulIntentService
, for the staticWakeLock
to be used for the service. Since thatWakeLock
is static, and I need aContext
to get atPowerManager
to create it, it is safest to usegetApplicationContext()
.Use
getApplicationContext()
when you bind to aService
from anActivity
, if you wish to pass theServiceConnection
(i.e., the handle to the binding) betweenActivity
instances viaonRetainNonConfigurationInstance()
. Android internally tracks bindings via theseServiceConnections
and holds references to theContexts
that create the bindings. If you bind from theActivity
, then the newActivity
instance will have a reference to theServiceConnection
which has an implicit reference to the oldActivity
, and the oldActivity
cannot be garbage collected.
Some developers use custom subclasses of Application
for their own global data, which they retrieve via getApplicationContext()
. That's certainly possible. I prefer static data members, if for no other reason than you can only have one custom Application
object. I built one app using a custom Application
object and found it to be painful. Ms. Hackborn also agrees with this position.
Here are reasons why not to use getApplicationContext()
wherever you go:
It's not a complete
Context
, supporting everything thatActivity
does. Various things you will try to do with thisContext
will fail, mostly related to the GUI.It can create memory leaks, if the
Context
fromgetApplicationContext()
holds onto something created by your calls on it that you don't clean up. With anActivity
, if it holds onto something, once theActivity
gets garbage collected, everything else flushes out too. TheApplication
object remains for the lifetime of your process.
Related Topics
Gridview with Two Columns and Auto Resized Images
Android Camera Preview Stretched
Background Service with Location Listener in Android
Slowing Speed of Viewpager Controller in Android
How to Get the Height and Width of the Android Navigation Bar Programmatically
Android Fragment Onattach() Deprecated
"Gradle Version 2.10 Is Required." Error
Reference One String from Another String in Strings.Xml
Get Referrer After Installing App from Android Market
Android Popup Window Dismissal
Viewpager with Previous and Next Page Boundaries
Android Fragments. Retaining an Asynctask During Screen Rotation or Configuration Change
Google Play on Android 4.0 Emulator
Meaning of Top, Ascent, Baseline, Descent, Bottom, and Leading in Android's Fontmetrics