Search code examples
androidandroid-context

What is the role of attachBaseContext?


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.


Solution

  • 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.