四.Activity的启动流程-ActivityThread启动Activity的过程

Activity的启动一般分为普通Activity的启动,根Activity的启动.而根Activity是指应用启动的第一个Activity过程,所以也可以理解为应用的启动过程.

相关内容链接:android系统启动流程

应用的启动流程大致分为如下四个阶段:

一.应用进程(Launcher)调用ATMS系统进程的过程

二.ActivityTaskManagerService到ApplicationThread的调用过程

三.AMS向Zygote发送启动应用进程的过程

四.ActivityThread启动Activity的过程

Activity启动过程涉及到进程之间的关系:

四.ActivityThread启动Activity的过程

类名: android.app.ActivityThread.ApplicationThread

ApplicationThread类可以看作是AMS所在进程(SystemServer进程)和应用进程通信的桥梁,通过Binder的方式来执行

ActivityThread主要用来处理Activity生命周期等一些逻辑,ActivityThread继承自抽象类ClientTransactionHandler,将以前ActivityThread里面的handleLaunchActivity、handleStartActivity、handleResumeActivity和handleStopActivity等方法抽取出来,作为ClientTransactionHandler类的抽象方法.

1. scheduleTransaction

ApplicationThread继承自IApplicationThread.Stub,第二阶段中IApplicationThread的Binder调用就会执行到这里,这块代码比较简单,调用ActivityThread的scheduleTransaction方法,而ActivityThread是继承自抽象类ClientTransactionHandler, ActivityThread没有重写该方法,所以这里就会调用到ClientTransactionHandler的scheduleTransaction方法.

    @Override
    public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        ActivityThread.this.scheduleTransaction(transaction);
    }

类名: android.app.ClientTransactionHandler:

2. scheduleTransaction

    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }

类名: android.app.ActivityThread.H

3. handleMessage()

        class H extends Handler {
            public void handleMessage(Message msg) {
                // ... ...
                case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    mTransactionExecutor.execute(transaction);
                    if (isSystem()) {
                        // Client transactions inside system process are recycled on the client side
                        // instead of ClientLifecycleManager to avoid being cleared before this
                        // message is handled.
                        transaction.recycle();
                    }
                    // TODO(lifecycler): Recycle locally scheduled transactions.
                    break;
                    // ... ...
            }
        }

类名: android.app.servertransaction.TransactionExecutor

4: execute(ClientTransaction)

这里的executeCallbacks主要是用来实例化和初始化activity,而executeLifecycleState主要是回调Activity的声明周期方法.

 public void execute(ClientTransaction transaction) {
        // ... ...
        executeCallbacks(transaction);

        executeLifecycleState(transaction);
        mPendingActions.clear();
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
    }

5. executeCallbacks()

这里callbacks列表中存放的是第二阶段(序号15.realStartActivityLocked方法)中创建事务时设置进去的,即LaunchActivityItem.所以这里是执行LaunchActivityItem对象的execute方法

 public void executeCallbacks(ClientTransaction transaction) {
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
        // ... ...
        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);    // LaunchActivityItem是继承自LaunchActivityItem
            if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Resolving callback: " + item);
            final int postExecutionState = item.getPostExecutionState();
            final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
                    item.getPostExecutionState());
            if (closestPreExecutionState != UNDEFINED) {
                cycleToPath(r, closestPreExecutionState, transaction);
            }

            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
            if (r == null) {
                // Launch activity request will create an activity record.
                r = mTransactionHandler.getActivityClient(token);
            }

            if (postExecutionState != UNDEFINED && r != null) {
                // Skip the very last transition and perform it by explicit state request instead.
                final boolean shouldExcludeLastTransition =
                        i == lastCallbackRequestingState && finalState == postExecutionState;
                cycleToPath(r, postExecutionState, shouldExcludeLastTransition, transaction);
            }
        }
    }

类名: android.app.servertransaction.LaunchActivityItem

6. execute(ClientTransactionHandler, IBinder, PendingTransactionActions)

类名: android.app.ActivityThread

7. handleLaunchActivity(ActivityClientRecord , PendingTransactionActions, Intent)

类名: android.app.ActivityThread

8. performLaunchActivity()

这里主要是获取当前Activity的信息,创建Activity的上下文和实例,创建Application,调用Activity的attach方法初始化activity,在attach方法中会创建Window对象(PhoneWindow)并与Activity关联起来,最后调用callActivityOnCreate()方法来启动Activity.

    /**  Core implementation of activity launch. */
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ActivityInfo aInfo = r.activityInfo;    //记录Manifest设置的Activity和Receiver节点信息,比如theme和launchMode
        if (r.packageInfo == null) {
            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                    Context.CONTEXT_INCLUDE_CODE);  //获取APK文件描述类LoadedApk
        }

        ComponentName component = r.intent.getComponent();  // 获取Activity的ComponentName(记录了包名和类名)
        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);
        }

        ContextImpl appContext = createBaseContextForActivity(r);   // 创建启动Activity的上下文
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);    // 使用ClassLoader创建Activity实例
            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 app = r.packageInfo.makeApplication(false, mInstrumentation);   // 创建Application

            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) {
                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.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,
                        r.assistToken); // 初始化Activity

                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;
                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.setState(ON_CREATE);

            // updatePendingActivityConfiguration() reads from mActivities to update
            // ActivityClientRecord which runs in a different thread. Protect modifications to
            // mActivities to avoid race.
            synchronized (mResourcesManager) {
                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;
    }

类名: android.app.Instrumentation

9. callActivityOnCreate(Activity, Bundle, PersistableBundle)

类名: android.app.Activity

10. performCreate(Bundle)()

performCreate中会调用Activity的onCreate.Activity的启动就完成了,应用也就启动了.

    @UnsupportedAppUsage
    final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        dispatchActivityPreCreated(icicle);
        mCanEnterPictureInPicture = true;
        restoreHasCurrentPermissionRequest(icicle);
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
        writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
        mActivityTransitionState.readState(icicle);

        mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
                com.android.internal.R.styleable.Window_windowNoDisplay, false);
        mFragments.dispatchActivityCreated();
        mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
        dispatchActivityPostCreated(icicle);
    }

代码跟到了Activity的onCreate方法,那onStart和onResume呢? 继续来看序号4: execute方法中的executeLifecycleState方法.

android.app.servertransaction.TransactionExecutor

11. executeLifecycleState()

这段代码首先会取出lifecycleItem,而它是在第二阶段(序号15.realStartActivityLocked方法)中设置进去的,即ResumeActivityItem.所以这里会执行ResumeActivityItem对象的execute方法,ResumeActivityItem跟之前的LaunchActivityItem类似,所以执行lifecycleItem.execute最后也会调用到Activity的onResume方法,所以这里就不贴出来调用过程了.

在跟回调onResume方法的代码过程中,看到ActivityThread的handleResumeActivity方法里面会获取Activity的DecorView的过程.

private void executeLifecycleState(ClientTransaction transaction) {
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        if (lifecycleItem == null) {
            // No lifecycle request, return early.
            return;
        }

        final IBinder token = transaction.getActivityToken();
        final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
        if (DEBUG_RESOLVER) {
            Slog.d(TAG, tId(transaction) + "Resolving lifecycle state: "
                    + lifecycleItem + " for activity: "
                    + getShortActivityName(token, mTransactionHandler));
        }

        if (r == null) {
            // Ignore requests for non-existent client records for now.
            return;
        }

        // Cycle to the state right before the final requested state.
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);

        // Execute the final transition with proper parameters.
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }

12. cycleToPath(ActivityClientRecord, int, boolean, ClientTransaction)

13. performLifecycleSequence(ActivityClientRecord, IntArray, ClientTransaction)

跟到这里,Activity onStart生命周期的回调就找到了.

/** Transition the client through previously initialized state sequence. */
    private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
            ClientTransaction transaction) {
        final int size = path.size();
        for (int i = 0, state; i < size; i++) {
            state = path.get(i);
            if (DEBUG_RESOLVER) {
                Slog.d(TAG, tId(transaction) + "Transitioning activity: "
                        + getShortActivityName(r.token, mTransactionHandler)
                        + " to state: " + getStateName(state));
            }
            switch (state) {
                case ON_CREATE:
                    mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                            null /* customIntent */);
                    break;
                case ON_START:
                    mTransactionHandler.handleStartActivity(r, mPendingActions);
                    break;
                case ON_RESUME:
                    mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
                            r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                    break;
                case ON_PAUSE:
                    mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
                            false /* userLeaving */, 0 /* configChanges */, mPendingActions,
                            "LIFECYCLER_PAUSE_ACTIVITY");
                    break;
                case ON_STOP:
                    mTransactionHandler.handleStopActivity(r.token, false /* show */,
                            0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
                            "LIFECYCLER_STOP_ACTIVITY");
                    break;
                case ON_DESTROY:
                    mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
                            0 /* configChanges */, false /* getNonConfigInstance */,
                            "performLifecycleSequence. cycling to:" + path.get(size - 1));
                    break;
                case ON_RESTART:
                    mTransactionHandler.performRestartActivity(r.token, false /* start */);
                    break;
                default:
                    throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
            }
        }
    }