8
One can, beyond the this
, get the context in several ways, with different methods. As shown in the code below, we have the getApplicationContext()
and the getBaseContext()
which apparently serves the same purpose.
public class MainActivity extends AppCompatActivity{
public Context context;
public void umMetodoQualquer() {
context = this;
context = getApplicationContext();
context = getBaseContext();
}
}
And in practice, what are the differences between the methods for obtaining a context?
getbaseContext also refers to Activity or it would be something more complex?
– viana
getbaseContext() returns the context created by the system, an instance of Contextimp that is created and configured(I suppose) depending on the type of component that will use it: Activity/Service or Application. It is accessed through the proxy Contextwrapper, from which they inherit. Each of them is a context but its "implementation/configuration" is provided externally.
– ramaral
I don’t know if the Acrivity class overwrites any of the Contextwrapper methods. If it doesn’t overwrite the Context returned by
getBaseContext()
will behave in the same way as(Context)this
.– ramaral
I did the following test using the logo:
this.getClass().getName()
returned the name of Activity;getApplicationContext().getClass().getName()
returnedandroid.app.application
;getBaseContext().getClass().getName()
returnedandroid.app.ContextImpl
. I would like to know in practice, how/when/where it is used. It would have as you exemplify?– viana
Use the Context of the component within which you are(this), provided that the reference to it does not extend beyond the life cycle of that component. If that is not the case, use getApplicationContext(). So far I have found no reason to use getBaseContext(). See this post where you have more complete information.
– ramaral
I still have a flea behind my ear, but I will validate the answer, then you put this link of the post (which is very interesting) to a question of deepening the subject, which is also a complement. Thank you.
– viana
What doubts you still have?
– ramaral
For example, this
getBaseContext()
nor should exist, because thethis
and thegetApplicationContext
are already enough considering its functionalities. So because of that, I also got to thinking. In the post you passed has no reference on it.– viana
Usually a wrapper/proxy does not expose the internal object(s). It is possible that there is some situation where it is useful/necessary to use
getBaseContext()
, I haven’t found any yet.– ramaral