What are the essential differences between the getContext()
, getApplicationContext()
, getBaseContext()
, and methods this
to get the context in Android
?
I know it may be a very trivial or very broad question, but I think that many of us are not completely clear about these concepts and I think it would be of great help to the community. Also, if possible, they can give some basic example of use of each case to improve their understanding.
PS: by this
I mean within a Activity
.
getContext() Returns the context in which the view is executed, usually the Activity, through this context you can access the current theme, resources, etc.
getApplicationContext() Returns the context of the current process's single global Application object. Using this context ensures that you have a context tied to the application lifecycle. It could be said that it is the most "light" context.
getBaseContext() : The base context set by the constructor or setBaseContext. To talk about this context, it is necessary to talk about ContextWrapper , which is a class through which one context can be accessed within another. The context referenced by the ContextWrapper is obtained via getBaseContext() . Obtaining the context through this method is related to that of the Activity.
This : This reference can be used in an Activity since Activity inherits from
Context
and is the reference to the Activity context:Because your class doesn't extend from
Activity
,AppCompactActivity
or even fromService
(where it's usedthis
to get the context), if your class doesn't extend any of those you must send your class the context using a constructor.Example:
The
getApplicationContext()
is used to obtain the Context associated with the application, so it will always be the same throughout the life cycle of the app. On the other hand,getBaseContext()
it is associated with the parent activity, and will not necessarily be the same since it is tied to its life cycle, so it can be destroyed.In summary, you can only have 2 types of Context, the one based on the application and the one based on the activity, so depending on the requirement you must use one or the other.
When you do
this
inside an Activity what you are actually doing is taking the objectActivity
of your activity and from this Android it already takes the context. One way to check is as follows:Let's try calling the method
getLayoutInflater()
inside your activity:You will see that with
context.getLayoutInflater();
gives you an error because this method needs to be called with an objectActivity
and not with aContext
.