Activity的启动流程分析(二)

在上一篇中已经讲了Activity从AMS到ActivityThread,这里从ActivityThread中分析Activity的创建过程。
如果想要看完整的流程请先看Activity的启动流程分析(一)https://www.jianshu.com/p/995e767e4383然后再看这里就是Activity的完整启动流程了。
AMS到ActivityThread是通过ActivityStackSupervisor中的realStartActivityLocked()方法调到了ActivityThread中的内部类ApplicationThread中的scheduleLaunchActivity方法来处理Activity的启动和创建。代码具体路径在:/frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor中;感兴趣的可以去看一下。

ActivityThread启动Activity

上面已经提到了AMS处理完Activity的相关信息后会调用ActivityThread中的内部类ApplicationThread中的scheduleLauncherActivity方法交到ApplicationThread中处理Activity的创建和启动工作;代码如下:

private class ApplicationThread extends IApplicationThread.Stub {
    .........................
        @Override
        public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
                CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
                int procState, Bundle state, PersistableBundle persistentState,
                List pendingResults, List pendingNewIntents,
                boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
            updateProcessState(procState, false);
            ActivityClientRecord r = new ActivityClientRecord();
            r.token = token;
            r.ident = ident;
            r.intent = intent;
            r.referrer = referrer;
            r.voiceInteractor = voiceInteractor;
            r.activityInfo = info;
            r.compatInfo = compatInfo;
            r.state = state;
            r.persistentState = persistentState;

            r.pendingResults = pendingResults;
            r.pendingIntents = pendingNewIntents;

            r.startsNotResumed = notResumed;
            r.isForward = isForward;

            r.profilerInfo = profilerInfo;

            r.overrideConfig = overrideConfig;
            updatePendingConfiguration(curConfig);

            sendMessage(H.LAUNCH_ACTIVITY, r);//具体到Handler中处理了
        }
..............................
}

该内部类的代码篇幅较长这里只给出要关心的代码其它的可以到源码中查看,源码地址在:/frameworks/base/core/java/android/app/ActivityThread.java感兴趣的可以自行到该类中查看其它方法。
从上面的源码中看到把AMS中传过来的信息用ActivityClientRecord保存起来后调到了sendMessage()方法处进行下一步的操作。
这个sendMessage其实就是对Handler中的sendMessage进行再封装了一下原型如下:

   private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
        if (DEBUG_MESSAGES) {
            Slog.v(TAG,
                    "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj);
        }
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            msg.setAsynchronous(true);
        }
        mH.sendMessage(msg);
    }

可以看到最后调了mH中的sendMessage方法把消息发到Handler中处理,代码中的mH就是ActivityThread中的H内部类,该类是继承了Handler重写了handleMessage方法;在scheduleLaunchActivity中看了Message中的what是H.LAUNCH_ACTIVITY转到H类看H.LAUNCH_ACTIVITY具体干了什么;可以看到在handleMessage中调用了handleLaunchActivity方法;(在8.0以上的版本用H.RELAUNCH_ACTIVITY代替了H.LAUNCH_ACTIVITY)代码如下:

private class H extends Handler{
          .............
           public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
                case LAUNCH_ACTIVITY: {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } 
              break;
            }
      }
        ...................
}

handleLauncherActivity代码如下:

    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
       .........................
        WindowManagerGlobal.initialize();
         //在这是调用了preformLauncheActivity创建Activity
        Activity a = performLaunchActivity(r, customIntent);
        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            reportSizeConfigurations(r);
            Bundle oldState = r.state;
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);

            if (!r.activity.mFinished && r.startsNotResumed) {
         
                performPauseActivityIfNeeded(r, reason);

                if (r.isPreHoneycomb()) {
                    r.state = oldState;
                }
            }
        } else {
            // If there was an error, for any reason, tell the activity manager to stop us.
          //如果activity返回是null就销毁activity的相关信息
            try {
                ActivityManager.getService()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                            Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        }
    }

从上面的代码可以看到Activity的创建又调用了performLaunchActivity方法,代码如下:

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
          .................................
          ContextImpl appContext = createBaseContextForActivity(r);//Context在这里创建
        Activity activity = null;
        try {
             //Activity在这里通过反射创建出来
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess();
            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);
            }
        }
try {
            //Application在这里创建出来
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            if (activity != null) {
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                if (r.overrideConfig != null) {
                    config.updateFrom(r.overrideConfig);
                }
                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                        + r.activityInfo.name + " with config " + config);
                Window window = null;
                if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                    window = r.mPendingRemoveWindow;
                    r.mPendingRemoveWindow = null;
                    r.mPendingRemoveWindowManager = null;
                }
                appContext.setOuterContext(activity);//activity和context进行绑定
                //这里对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 (customIntent != null) {
                    activity.mIntent = customIntent;
                }
                r.lastNonConfigurationInstances = null;
                checkAndBlockForNetworkAccess();
                activity.mStartedActivity = false;
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    activity.setTheme(theme);
                }
                activity.mCalled = false;
                //这里调用Activity的onCreate方法
                if (r.isPersistable()){
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    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.isPersistable()) {
                        if (r.state != null || r.persistentState != null) {
                            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                                    r.persistentState);
                        }
                    } else if (r.state != null) {
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                    }
                }
                if (!r.activity.mFinished) {
                    activity.mCalled = false;
                    if (r.isPersistable()) {
                        mInstrumentation.callActivityOnPostCreate(activity, r.state,
                                r.persistentState);
                    } else {
                        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是通过反射创建出来的,同时也知道先有Activity才能有Application的这里面就有面试点了,有时会问先有Activity还是先有Application,如果在不看源码前应该有不少小伙伴都觉得是先创建Application才创建Activity的;performLaunchActivity方法执行完Activity就已经真正的启动完成了;在上面看到mInstrumentation创建了Activity类那里面究竟是不是使用反射的呢接下看一下Instrumentation中的newActivity方法,该方法两个重载下面主要是看使用类加载器的,因为上面的代码中使用的是类加载器的方法进行创建的:Instrumentation的代码路径:/frameworks/base/core/java/android/app/Instrumentation.java

public Activity newActivity(ClassLoader cl, String className,
            Intent intent)
            throws InstantiationException, IllegalAccessException,
            ClassNotFoundException {
        return (Activity)cl.loadClass(className).newInstance();
    }

还有Acvitiy的其它生命周期也是通过该类进行调用的,所以这个类是一个工具类比如OnCreate方法在performLaunchActivity中也看到了,接下来就看一下原型吧:

  public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        activity.performCreate(icicle);//这里就调用了Activity的onCreate方法了
        postPerformCreate(activity);
    }

在这里Activity就已经调用了OnCreate方法了,Activity也就启动完成了;今天就分析到这里了。如果你看完后觉得有收获就给作者点赞关注一下吧!

你可能感兴趣的:(Activity的启动流程分析(二))