美文网首页
Activity启动过程(源码分析)

Activity启动过程(源码分析)

作者: ae12 | 来源:发表于2018-11-09 17:34 被阅读1次

    Activity的启动startActivity()构造函数很多,但最终回调的还是Activity.java中的都会调用startActivityForResult方法。
    Activity的启动过程接着转移到了Instrumentation中的execStartActivity方法
    太长,大概看一下,有篇博文讲的不错,可以看看
    https://blog.csdn.net/zizidemenghanxiao/article/details/50639025
    总结一下就是:

    1.instrumentation. execStartActivity()
    在Instrumentation的execStartActivity中用ActivityManagerNative的getDefault来获取一个IActivityManager的对象,
    而且这个IActivityManager的对象其实是一个Binder对象,它的具体实现是
    ActivityManagerService

    static public IActivityManager getDefault() {
        return gDefault.get();
    }
    

    2.再次转移到ActivityManagerService.startActivity()方法中
    3.接着转移过程如下图,不再赘述,实在太多,只看主要的脉络


    activity.jpeg

    4.接着是到了ActivtiyStackSupervisor的realStartActivityLocked()

    5.接着到了ApplicationThread通过scheduleLaunchActivity方法来启动Activity
    queueOrSendMessage(H.LAUNCH_ACTIVITY, r);

    这个方法是ActivityThread.java文件中的ApplicationThread内部类的scheduleLaunchActivity方法:scheduleLaunchActivity的实现很简单,就是发送一个启动Activity的消息交由Handler处理。这个Handler的名字很简洁,H。
    6.接下来是Handler H对消息的处理:

                     * 转到这里了:
                     * */
                    handleLaunchActivity(r, null);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    

    7.接着是handleLaunchActivity方法:
    /*
    * 启动Activity终极大Boss在此!!!!
    * */
    Activity a = performLaunchActivity(r, customIntent);

    8.performLaunchActivity这个方法主要完成了如下几件事:

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
            // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
     
            /*
             * 第一步:从ActivityClientRecord中获取待启动的Activity的组件信息:
             * */
            ActivityInfo aInfo = r.activityInfo;
            if (r.packageInfo == null) {
                r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                        Context.CONTEXT_INCLUDE_CODE);
            }
     
            ComponentName component = r.intent.getComponent();
            if (component == null) {
                component = r.intent.resolveActivity(
                    mInitialApplication.getPackageManager());
                r.intent.setComponent(component);
            }
     
            if (r.activityInfo.targetActivity != null) {
                component = new ComponentName(r.activityInfo.packageName,
                        r.activityInfo.targetActivity);
            }
     
            /*
             * 第二步:通过Instrumentation的newActivity方法使用类加载器创建Activity对象。
             * */
            Activity activity = null;
            try {
                java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
                /*
                 * 通过类加载器创建Activity的实例对象:
                 * */
                activity = mInstrumentation.newActivity(
                        cl, component.getClassName(), r.intent);
                StrictMode.incrementExpectedActivityCount(activity.getClass());
                r.intent.setExtrasClassLoader(cl);
                if (r.state != null) {
                    r.state.setClassLoader(cl);
                }
            } catch (Exception e) {
                if (!mInstrumentation.onException(activity, e)) {
                    throw new RuntimeException(
                        "Unable to instantiate activity " + component
                        + ": " + e.toString(), e);
                }
            }
     
            /*
             * 第三步:通过LoadedApk的makeApplication方法来尝试创建Application对象,
             * 而且一个应用只能有一个Application对象。
             * Application对象的创建也是通过Instrumentation来完成的,这个过程和Activity对象的创建一样,
             * 都是通过类加载器来实现的。
             * Application创建完毕后,系统会通过Instrumentation的callApplicationOnCreate来调用Application的onCreate方法。
             * */
            try {
                Application app = r.packageInfo.makeApplication(false, mInstrumentation);
     
                if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
                if (localLOGV) Slog.v(
                        TAG, r + ": app=" + app
                        + ", appName=" + app.getPackageName()
                        + ", pkg=" + r.packageInfo.getPackageName()
                        + ", comp=" + r.intent.getComponent().toShortString()
                        + ", dir=" + r.packageInfo.getAppDir());
     
                if (activity != null) {
                    /*
                     * 第四步:创建ContextImpl对象并通过Activity的attach方法来完成一些重要数据的初始化。
                     * 这里有一堆Activity运行过程中所依赖的上下文环境变量,
                     * 并通过Activity的attach方法来将这些环境变量与Activity相关联:
                     * (2)ContextImpl是一个很重要的数据结构,它是Context的具体实现,
                     * Context中改的大部分逻辑都是由ContextImpl来完成的。
                     * ContextImpl是通过Activity的attach方法来和Activity建立关联的。
                     * (3)此外,在attach方法中Activity还会完成Window的创建并建立自己和Window的关联,
                     * 这样当Window接收到外部输入事件后就可以将事件传递给Activity。
                     * */
                    Context appContext = createBaseContextForActivity(r, activity);
                    CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                    Configuration config = new Configuration(mCompatConfiguration);
                    if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                            + r.activityInfo.name + " with config " + config);
                    activity.attach(appContext, this, getInstrumentation(), r.token,
                            r.ident, app, r.intent, r.activityInfo, title, r.parent,
                            r.embeddedID, r.lastNonConfigurationInstances, config);
     
                    if (customIntent != null) {
                        activity.mIntent = customIntent;
                    }
                    r.lastNonConfigurationInstances = null;
                    activity.mStartedActivity = false;
                    int theme = r.activityInfo.getThemeResource();
                    if (theme != 0) {
                        activity.setTheme(theme);
                    }
     
                    activity.mCalled = false;
                    /*
                     * 第五步:调用Activity的onCreate方法:
                     * 到此为止,Activity也就完成了整个启动过程,
                     * 呵呵哒。
                     * */
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                    if (!activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onCreate()");
                    }
                    r.activity = activity;
                    r.stopped = true;
                    if (!r.activity.mFinished) {
                        activity.performStart();
                        r.stopped = false;
                    }
                    if (!r.activity.mFinished) {
                        if (r.state != null) {
                            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                        }
                    }
                    if (!r.activity.mFinished) {
                        activity.mCalled = false;
                        mInstrumentation.callActivityOnPostCreate(activity, r.state);
                        if (!activity.mCalled) {
                            throw new SuperNotCalledException(
                                "Activity " + r.intent.getComponent().toShortString() +
                                " did not call through to super.onPostCreate()");
                        }
                    }
                }
                r.paused = true;
     
                mActivities.put(r.token, r);
     
            } catch (SuperNotCalledException e) {
                throw e;
     
            } catch (Exception e) {
                if (!mInstrumentation.onException(activity, e)) {
                    throw new RuntimeException(
                        "Unable to start activity " + component
                        + ": " + e.toString(), e);
                }
            }
     
            return activity;
        }
    
    

    相关文章

      网友评论

          本文标题:Activity启动过程(源码分析)

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