attachBaseContext的作用是什么? [英] What is the role of attachBaseContext?

查看:3347
本文介绍了attachBaseContext的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对为什么在Android中使用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.

推荐答案

ContextWrapper类的attachBaseContext函数确保上下文仅被附加一次. ContextThemeWrapper应用来自应用程序或活动的主题,该主题在AndroidManifest.xml文件中定义为android:theme. 由于应用程序和服务都不需要主题,因此它们直接从ContextWrapper继承主题.在活动创建,应用程序和服务启动期间,每次都会创建一个新的ContextImpl对象,并在Context中实现功能.

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.

这篇关于attachBaseContext的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆