What is the role of attachBaseContext?

断了今生、忘了曾经 提交于 2020-02-23 10:25:11

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/51759985/what-is-the-role-of-attachbasecontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!