I am confused about why do we use attachBaseContext in android. It would be a great help if someone could explain to me the meaning for the same.
Provides the central interface between an application and Android's data backup infrastructure. ContextThemeWrapper. A context wrapper that allows you to modify or replace the theme of the wrapped context.
getBaseContext() is the method of ContextWrapper . And ContextWrapper is, "Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context." (as per javadocs)..
The attachBaseContext
function of the ContextWrapper
class is making sure the context is attached only once. ContextThemeWrapper
applies theme from application or Activity which is defined as android:theme
in the AndroidManifest.xml
file.
Since both Application and Service do not need theme, they inherit it directly from ContextWrapper
. During the activity creation, application and service are initiated, a new ContextImpl
object is created each time and it implements functions in Context
.
public class ContextWrapper extends Context {
Context mBase;
public ContextWrapper(Context base) {
mBase = base;
}
/**
* Set the base context for this ContextWrapper. All calls will then be
* delegated to the base context. Throws
* IllegalStateException if a base context has already been set.
*
* @param base The new base context for this wrapper.
*/
protected void attachBaseContext(Context base) {
if (mBase != null) {
throw new IllegalStateException("Base context already set");
}
mBase = base;
}
}
For more details please look this.
ContextWrapper class is used to wrap any context(application context, activity context or base context) into the original context without disturbing it. Consider the below example:
override fun attachBaseContext(newBase: Context?) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase))
}
Here, newBase
is the original context which is wrapped by the CalligraphyContextWrapper
class' wrap
method which is returning the instance of the ContextWrapper
class. Now, the modified context is passed to the ContextWrapper
which is the indirect superclass of Activity by calling super.attachBaseContext()
. And now we can access the context of Calligraphy dependency as well as our original context.
Basically, if you want to make use of some other context in the current activity, application or service then do override attachBaseContext
method.
PS:
Calligraphy is just a dependency to get custom fonts calligraphy
Check this out to learn more about contexts dive deep into context
The official doc about attachBaseContext
is not thorough but you will get a tentative idea about it.ContextWrapper
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With