ContextImpl和ContextWrapper绑定过程

LoadedApk类中makeApplication()中,

public Application makeApplication(boolean forceDefaultAppClass,Instrumentation instrumentation)
 {
        if (mApplication != null) {
            return mApplication;
        }
        Application app = null;
        String appClass = mApplicationInfo.className;
        if (forceDefaultAppClass || (appClass == null)) {
            appClass = "android.app.Application";
        }

        try {
            java.lang.ClassLoader cl = getClassLoader();
            ContextImpl appContext = new ContextImpl();
            appContext.init(this, null, mActivityThread);
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);//此处会去初始化application
            appContext.setOuterContext(app);
        } catch (Exception e) {
            if (!mActivityThread.mInstrumentation.onException(app, e)) {
                throw new RuntimeException(
                    "Unable to instantiate application " + appClass
                    + ": " + e.toString(), e);
            }
        }
        mActivityThread.mAllApplications.add(app);
        mApplication = app;

        if (instrumentation != null) {
            try {
                instrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
                if (!instrumentation.onException(app, e)) {
                    throw new RuntimeException(
                        "Unable to create application " + app.getClass().getName()
                        + ": " + e.toString(), e);
                }
            }
        }
        return app;
    }

注意这句:app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);//此处会去初始化application
Instrumentation类中newApplication()中

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

注意这句:app.attach(context);
Application类中attach()函数

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

注意这句:attachBaseContext(context);
ContextWrapper类中attachBaseContext()函数

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

ContextWrapper类中定义了成员Context mBase;
其方法内部都是通过mBase调用ContextImpl的相关方法。如:

  public AssetManager getAssets()
   {
        return mBase.getAssets();
    }

你可能感兴趣的:(ContextImpl和ContextWrapper绑定过程)