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.
activity context vs application context
If I'm using a one activity multiple fragments design for my app, would the application context in this case be the same as the activity context?
No. The Application
singleton is an entirely separate class.
I know it's a bad idea to pass the activity context to a ViewModel but in this case is it valid?
No — use the Application
.
The app is always in portrait
Note that there are many configuration changes, not just orientation. The user can switch locale, enable "dark mode" on Android 10+, enter or leave split-screen mode, resize a Chrome OS window, etc.
Difference- ApplicationContext() VS. Activity Context in ANDROID..?
To have a gist over the application context and activity context read below:
The application context will live as long as your application is alive and does not depend on the activities life cycle. If you plan on keeping long-lived objects that need a context, remember the application object. You can obtain it easily by calling Context.getApplicationContext() or Activity.getApplication().
In summary, to avoid context-related memory leaks, remember the following:
1.Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
2.Try using the context-application instead of a context-activity
Reference & more Info
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.
What is the difference between Activity and Context?
As far as I understand:
Context is the Base Object. So every Activity same as Application derives from Context. This means that every Activity and every Application
IS a Context
;
From developer.android.com
Activity
java.lang.Object
↳ android.content.Context
↳ android.content.ContextWrapper
↳ android.view.ContextThemeWrapper
↳ android.app.Activity
And Application
java.lang.Object
↳ android.content.Context
↳ android.content.ContextWrapper
↳ android.app.Application
An Application context lasts, as long as your app is alive, while the Activity context dies with your Activity (it is not valid after onDestroy
of that Activity).
So if you need the Context across Activities (i.e. in a Singleton) you will be better off using an Application context.
Usually on Android Framework methods where a context is expected, it makes no difference which one you pass. But be always aware of MemoryLeaks if you're keeping long-living References to a Context
How to differentiate between ApplicationContext and Context?
Since both methods return instance of Context object but with
different capabilities, how can I differentiate if passed context
object is Activity Context or Application Context ?
you can check with instanceof
. It allows to check if the object is of a certain type. E.g.
if (context instanceof Activity) {
}
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.
Related Topics
Save Arraylist to Sharedpreferences
How to Send an Object from One Android Activity to Another Using Intents
How to Load an Imageview by Url in Android
How to Access My Localhost from My Android Device
Sending and Receiving Sms and Mms in Android (Pre Kit Kat Android 4.4)
Programmatically Obtain the Phone Number of the Android Phone
Checking If an Android Application Is Running in the Background
How to Retrieve Data from Firebase to My Adapter
Why Does an Image Captured Using Camera Intent Gets Rotated on Some Devices on Android
How to Enable Multidexing With the New Android Multidex Support Library
How to Use Putextra() and Getextra() For String Data
Android Marshmallow Request Permission
How to Make an Android Spinner With Initial Text "Select One"
Android: Show Soft Keyboard Automatically When Focus Is on an Edittext