美文网首页
android深入理解Context

android深入理解Context

作者: Peakmain | 来源:发表于2019-08-09 16:30 被阅读0次

    Context概述

    使用场景
    使用场景主要有两个:

    • 使用context调用某个方法,比如startActivity,访问资源等
    • 调用方法的时候作为参数,比如Toast,Dialog等

    context家族史图

    context家族史.png
    ContextWrapper内部包含有Context类型的mBase对象,mBase具体指向的是ContextImpl。ContextWrapper是个装饰类,它主要是对ContextImpl进行包装,它是起了方法传递作用,ContextWrapper中几乎所有的方法实现都是调用ContextImpl的相应方法来实现的。

    Application Context创建过程

    对于具体相关源码大家可以看我这篇文章App启动——Activity的启动流程
    我们其实可以知道,启动activity实际会调用到ActivityThread中的performLaunchActivity

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

    实际调用的是LoadedApk中的makeApplication

        public Application makeApplication(boolean forceDefaultAppClass,
                Instrumentation instrumentation) {
          //第一次的时候application肯定为空
            if (mApplication != null) {
                return mApplication;
            }
            Application app = null;
            try {
                java.lang.ClassLoader cl = getClassLoader();
             ....
              //创建ContextImpl对象
                ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
         //newApplication实际是创建了Application对象
                app = mActivityThread.mInstrumentation.newApplication(
                        cl, appClass, appContext);
            //将application传给ContextImpl的上下文mOuterContext
                appContext.setOuterContext(app);
            } catch (Exception e) {
            }
            mActivityThread.mAllApplications.add(app);
          //将application赋值给mApplicaion
            mApplication = app;
    
            if (instrumentation != null) {
                try {
                  //会调用oncreate方法
                    instrumentation.callApplicationOnCreate(app);
                } catch (Exception e) {
                }
            }
            return app;
        }
    

    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;
        }
    

    attach源码分析

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

    contextWrapper的attachBaseContext方法

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

    由此我们可以知道实际最终ContextWrapper中的mBase是ContextImpl对象

    Application Context获取过程

    ContextWrapper

        @Override
        public Context getApplicationContext() {
            return mBase.getApplicationContext();
        }
    

    实际是ContextImpl中的getApplication方法

        @Override
        public Context getApplicationContext() {
            return (mPackageInfo != null) ?
                    mPackageInfo.getApplication() : mMainThread.getApplication();
        }
    

    mPackageInfo实际是LoadedApk,此时App都启动了,则肯定不会为空了,则会走mPackageInfo.getApplication

      Application getApplication() {
            return mApplication;
        }
    

    实际返回的是我们之前创建的application

    Activity的Context创建过程

    继续回到performLaunchActivity

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
           ...
            Activity activity = null;
            try {
                java.lang.ClassLoader cl = appContext.getClassLoader();
            //创建activity实例
                activity = mInstrumentation.newActivity(
                        cl, component.getClassName(), r.intent);
                  ...
            } catch (Exception e) {
            ....
            }
    
            try {
                //创建application
                Application app = r.packageInfo.makeApplication(false, mInstrumentation);
                if (activity != null) {
                    //将context实例变成activity
                    appContext.setOuterContext(activity);
                    activity.attach(appContext, this, getInstrumentation(), r.token,
                            r.ident, app, r.intent, r.activityInfo, title, r.parent,
                            r.embeddedID, r.lastNonConfigurationInstances, config,
                            r.referrer, r.voiceInteractor, window, r.configCallback);
    
                   ....
                    if (r.isPersistable()) {
                       //activity的onCreate方法
                        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                    } else {
                        mInstrumentation.callActivityOnCreate(activity, r.state);
                    }
             
            } catch (Exception e) {
               ....
            }
    
            return activity;
        }
    

    appContext.setOuterContext实际会将activity赋值给ContextImpl上下文,此时ContextImpl就可以访问到activity中的方法了,查看activity.attach方法

     final void attach(Context context, ActivityThread aThread,
                Instrumentation instr, IBinder token, int ident,
                Application application, Intent intent, ActivityInfo info,
                CharSequence title, Activity parent, String id,
                NonConfigurationInstances lastNonConfigurationInstances,
                Configuration config, String referrer, IVoiceInteractor voiceInteractor,
                Window window, ActivityConfigCallback activityConfigCallback) {
            //主要关注这个
            attachBaseContext(context);
             //创建一个phone window
            mWindow = new PhoneWindow(this, window, activityConfigCallback);
         //设置一系列事件
            mWindow.setWindowControllerCallback(this);
            mWindow.setCallback(this);
            mWindow.setOnWindowDismissedCallback(this);
            mWindow.getLayoutInflater().setPrivateFactory(this);
            if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
                mWindow.setSoftInputMode(info.softInputMode);
            }
              ...
            mWindow.setWindowManager(
    (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
                    mToken, mComponent.flattenToString(),
                    (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
            if (mParent != null) {
                mWindow.setContainer(mParent.getWindow());
            }
            mWindowManager = mWindow.getWindowManager();
            mCurrentConfig = config;
    
            mWindow.setColorMode(info.colorMode);
           ...
        }
    

    attachBaseContext实际最终调用的是ContextThemeWrapper->ContextWrapper中的attachBase方法

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

    Service的Context创建过程

    实际最终会走到ActivityThread中的handleCreateService

      private void handleCreateService(CreateServiceData data) {
            // If we are getting ready to gc after going to the background, well
            // we are back active so skip it.
            unscheduleGcIdler();
    
            LoadedApk packageInfo = getPackageInfoNoCheck(
                    data.info.applicationInfo, data.compatInfo);
            Service service = null;
            try {
                java.lang.ClassLoader cl = packageInfo.getClassLoader();
                service = packageInfo.getAppFactory()
                        .instantiateService(cl, data.info.name, data.intent);
            } catch (Exception e) {
               ...
            }
    
            try {
                ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
                context.setOuterContext(service);
    
                Application app = packageInfo.makeApplication(false, mInstrumentation);
                service.attach(context, this, data.info.name, data.token, app,
                        ActivityManager.getService());
                service.onCreate();
                mServices.put(data.token, service);
                try {
                    ActivityManager.getService().serviceDoneExecuting(
                            data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
                } catch (Exception e) {
            }
    }
    

    service.attach源码分析

       public final void attach(
                Context context,
                ActivityThread thread, String className, IBinder token,
                Application application, Object activityManager) {
            attachBaseContext(context);
            mThread = thread;           // NOTE:  unused - remove?
            mClassName = className;
            mToken = token;
            mApplication = application;
            mActivityManager = (IActivityManager)activityManager;
            mStartCompatibility = getApplicationInfo().targetSdkVersion
                    < Build.VERSION_CODES.ECLAIR;
        }
    

    attachBaseContext(context);源码分析

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

    实际Service的Context和Activity的Context创建极其相似,所以不再阐述

    相关文章

      网友评论

          本文标题:android深入理解Context

          本文链接:https://www.haomeiwen.com/subject/qozcjctx.html