Home » Android » android – What is the role of attachBaseContext?

android – What is the role of attachBaseContext?

Posted by: admin June 15, 2020 Leave a comment

Questions:

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.

How to&Answers:

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.

Answer:

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