attachBaseContext的作用是什么? [英] What is the role of 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屋!