Android ContextWrapper的attachBaseContext(Context base)方法

陶修洁
2023-12-01

一般以ContextWrapper的attachBaseContext为入口反向追踪,具体方法链接查看context装饰器模式时看到的文章,如果只想看结果,可以参考如下过程

调用方向如下:
1.ActivityThread中的performLaunchActivity(ActivityThread.ActivityClientRecord r, Intent customIntent)方法作为起始点,其中包含这一句

private Activity performLaunchActivity(ActivityThread.ActivityClientRecord r, Intent customIntent) {
    ......
        Application app = r.packageInfo.makeApplication(false, this.mInstrumentation);
    ......
}

 2.接着我们ctrl+鼠标左键查看packageInfo这个变量发现是LoadApk类型,我们在其中查看makeApplication方法

public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) {
    ......
        ContextImpl appContext = ContextImpl.createAppContext(this.mActivityThread, this);
        app = this.mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);
    ......
}

3.crtl+鼠标左键点击newApplication进入到Instrumentation中查看该方法:

public Application newApplication(ClassLoader cl, String className, Context context) throws 
    InstantiationException, IllegalAccessException, ClassNotFoundException {
    Application app = this.getFactory(context.getPackageName()).instantiateApplication(cl, className);
    app.attach(context);
    return app;
}

4.crtl+鼠标左键点击attach进入到Application 中查看该方法:

final void attach(Context context) {
    this.attachBaseContext(context);
    this.mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
}

5.crtl+鼠标左键点击attachBaseContext进入到ContextWrapper 中查看该方法:

protected void attachBaseContext(Context base) {
    if (this.mBase != null) {
        throw new IllegalStateException("Base context already set");
    } else {
        this.mBase = base;
    }
}

从第2点与第5点可以看出ContextWrapper中的mBase对象实例其实是ContextImpl

 类似资料: