AMS剖析(3):AMS与ActivityThread的交互

前言:前面追溯了Activity在AMS中的启动流程,接下来分析AMS与ActivityThread的交互,并详细讲解Activity的生命周期;

还是以"Launcher中启动Settings"为例;

1.Launcher.onPause()

AMS与ActivityThread的第一次交互就是Launcher的暂停,发生在ActivityStack.startPausingLocked()方法中;

final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
        ActivityRecord resuming, boolean pauseImmediately) {
    ..........
    if (prev.app != null && prev.app.thread != null) {//条件满足
    ............
        try {
            ............

            //下面的代码,就是暂停Launcher,这是AMS与ActivityThread交互的内容,暂时不讨论
            //prev.appToken为IApplicationToken.Stub,prev.finishing为false,userLeaving为true,异步执行
            mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
                    PauseActivityItem.obtain(prev.finishing, userLeaving,
                            prev.configChangeFlags, pauseImmediately));
            .........
        }
    } else {
        ............
    }
............
}

其中:mService.getLifecycleManager()返回的是ClientLifecycleManager;

PauseActivityItem继承自ActivityLifecycleItem,它封装了一系列将要进行IPC的操作;

来看ClientLifecycleManager.scheduleTransaction():

void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
        @NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
    //ClientTransaction封装传进来的参数
    final ClientTransaction clientTransaction = transactionWithState(client, activityToken,
            stateRequest);
    //执行传输操作
    scheduleTransaction(clientTransaction);
}

void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    //client就是IApplicationThread
    final IApplicationThread client = transaction.getClient();
    //下面这句代码就是跨进程了
    transaction.schedule();
    if (!(client instanceof Binder)) {
        transaction.recycle();
    }
}

调用ClientTransaction .schedule():

public void schedule() throws RemoteException {
    //mClient就是我们传进来的IApplicationThread,接下来会通过IPC的方式调用
    //Launcher的ActivityThread.ApplicationThread.scheduleTransaction方法;
    //从AMS进程,进入App进程
    mClient.scheduleTransaction(this);
}

接下来就是IPC了,mClient就是我们传进来的IApplicationThread,mClient.scheduleTransaction()方法的实现在客户端的ApplicationThread中,接下来就要进入ActivityThread.ApplicationThread了;

public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    //终于从AMS进程,进入到了App进程
    ActivityThread.this.scheduleTransaction(transaction);
}

void scheduleTransaction(ClientTransaction transaction) {
    //准备工作,它会执行ActivityLifecycleItem的preExecute()方法,这里就是PauseActivityItem
    transaction.preExecute(this);
    //发送通知,由ActivityThread接收
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

scheduleTransaction()是ActivityThread.ApplicationThread的方法,在scheduleTransaction()中调用ActivityThread.this.scheduleTransaction(),在该方法里面,发送ActivityThread.H.EXECUTE_TRANSACTION的消息:

case EXECUTE_TRANSACTION:
    //取出传递过来的ClientTransaction
    final ClientTransaction transaction = (ClientTransaction) msg.obj;
    //执行transaction
    mTransactionExecutor.execute(transaction);
    if (isSystem()) {
        transaction.recycle();
    }
    break;

拿到AMS端的ClientTransaction,调用mTransactionExecutor.execute(transaction):

public void execute(ClientTransaction transaction) {
    //token就是IApplicationToken.Stub
    final IBinder token = transaction.getActivityToken();

    //执行Callbacks,后面分析的LaunchActivityItem就是在这里执行的,本例中暂时没有Callbacks
    executeCallbacks(transaction);

    //我们要看的是这个
    executeLifecycleState(transaction);
    mPendingActions.clear();
}

executeCallbacks(transaction)与后面分析的LaunchActivityItem有关,继续来看executeLifecycleState():

private void executeLifecycleState(ClientTransaction transaction) {
        //得到ActivityLifecycleItem,本例中是PauseActivityItem
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        if (lifecycleItem == null) {
            // No lifecycle request, return early.
            return;
        }
        log("Resolving lifecycle state: " + lifecycleItem);

        //得到token
        final IBinder token = transaction.getActivityToken();
        final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);

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

        //Activity.onStart方法就是在这里面调用的,后面会看到;
        //本次流程中的lifecycleItem是PauseActivityItem,所以lifecycleItem.getTargetState()为4;
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);

        //将动作传递给lifecycleItem执行,lifecycleItem在AMS进程当中,这里又进行了IPC
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        //上面的execute方法主要是app进程中的pause操作,当app进程中的pause操作结束之后,需要通知AMS进程,进行下一步操作
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }

executeLifecycleState()主要有三个内容:

①cycleToPath():

从方法名的释义是循环路径,我们可以理解为将Activity的生命周期圆满,有点强拼硬凑的意思;这个方法有啥用呢?

比如某一个Activity A,它现在的生命周期是onCreate阶段,用1来表示;lifecycleItem.getTargetState()跟lifecycleItem的类型有关,PauseActivityItem与ResumeActivityItem的getTargetState()返回值是不一样的,假如这里的lifecycleItem是ResumeActivityItem,ResumeActivityItem对应的生命周期是Activity的onResume,那lifecycleItem.getTargetState()的返回值是3,由于onCreate代表1,1和3之间差个2,所以onCreate和onResume中间还差一个生命周期,这个生命周期就是onStart();

说完了它的逻辑,后面就再分析下它的代码吧:

private void cycleToPath(ActivityClientRecord r, int finish,
        boolean excludeLastState) {
    //此时Launcher的状态是onResume,所以start为3
    final int start = r.getLifecycleState();
    log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
    final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
    performLifecycleSequence(r, path);
}

看下mHelper.getLifecyclePath():

public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
    //本次流程传递进来的参数是3,4,true
    ............

    mLifecycleSequence.clear();
    if (finish >= start) {//4>=3,成立
        for (int i = start + 1; i <= finish; i++) {
            mLifecycleSequence.add(i);//①本例中mLifecycleSequence有1个元素,就是onPause
        }
    } else { 
        .........
    }

    if (excludeLastState && mLifecycleSequence.size() != 0) {//成立
        //②由于excludeLastState为true,即不包含最后一个元素,所以将mLifecycleSequence中的
        //最后一个元素去掉,此时mLifecycleSequence中没有元素
        mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
    }

    return mLifecycleSequence;
}

从上得知,此时的path中没有元素,所以performLifecycleSequence()方法没有意义;

②lifecycleItem.execute():

调用PauseActivityItem.execute()方法,lifecycleItem在AMS进程当中,这里又进行了IPC;

PauseActivityItem.java
public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
    //从app进程又回到了AMS进程,client是在app进程中的,ActivityThread实现
    //了ClientTransactionHandler.handlePauseActivity()方法
    client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
            "PAUSE_ACTIVITY_ITEM");
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}

又回到了ActivityThread.handlePauseActivity():

ActivityThread.java
public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
        int configChanges, PendingTransactionActions pendingActions, String reason) {
    ActivityClientRecord r = mActivities.get(token);
    if (r != null) {
        if (userLeaving) {//成立
            //调用onUserInteraction()和onUserLeaveHint()函数
            performUserLeavingActivity(r);
        }

        r.activity.mConfigChangeFlags |= configChanges;
        //执行暂停Launcher的操作
        performPauseActivity(r, finished, reason, pendingActions);

        // Make sure any pending writes are now committed.
        //isPreHoneycomb()判断SDK版本是否是HONEYCOMB之前的版本
        if (r.isPreHoneycomb()) {
            //等待要暂停的应用进程的异步操作完成,保持数据完整
            QueuedWork.waitToFinish();
        }
        mSomeActivitiesChanged = true;
    }
}

点评:终于开始生命周期了:

①performUserLeavingActivity(r):

ActivityThread.java
final void performUserLeavingActivity(ActivityClientRecord r) {
    mInstrumentation.callActivityOnUserLeaving(r.activity);
}

Instrumentation.java
public void callActivityOnUserLeaving(Activity activity) {
    activity.performUserLeaving();
}

Activity.java
final void performUserLeaving() {
    onUserInteraction();
    onUserLeaveHint();
}

出现了onUserInteraction()和onUserLeaveHint();

②performPauseActivity(r, finished, reason, pendingActions):

private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
        PendingTransactionActions pendingActions) {
    if (r.paused) {
        if (r.activity.mFinished) {
            return null;
        }
        RuntimeException e = new RuntimeException(
                "Performing pause of activity that is not resumed: "
                + r.intent.getComponent().toShortString());
        Slog.e(TAG, e.getMessage(), e);
    }
    if (finished) {
        r.activity.mFinished = true;
    }

    final boolean shouldSaveState = !r.activity.mFinished && r.isPreHoneycomb();
    //暂停前保存状态
    if (shouldSaveState) {
        //调用onSaveInstanceState()保存Activity的状态
        callActivityOnSaveInstanceState(r);
    }

    //真正的暂停执行操作在这里
    performPauseActivityIfNeeded(r, reason);

    //通知OnActivityPausedListener执行其监听操作
    ArrayList<OnActivityPausedListener> listeners;
    synchronized (mOnPauseListeners) {
        listeners = mOnPauseListeners.remove(r.activity);
    }
    int size = (listeners != null ? listeners.size() : 0);
    for (int i = 0; i < size; i++) {
        listeners.get(i).onPaused(r.activity);
    }

    final Bundle oldState = pendingActions != null ? pendingActions.getOldState() : null;
    if (oldState != null) {
        if (r.isPreHoneycomb()) {
            r.state = oldState;
        }
    }

    return shouldSaveState ? r.state : null;
}

1)先看下callActivityOnSaveInstanceState()函数:

ActivityThread.java
private void callActivityOnSaveInstanceState(ActivityClientRecord r) {
    r.state = new Bundle();
    r.state.setAllowFds(false);
    if (r.isPersistable()) {
        r.persistentState = new PersistableBundle();
        //调用callActivityOnSaveInstanceState()
        mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state,
                r.persistentState);
    } else {
        mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
    }
}

Instrumentation.java
public void callActivityOnSaveInstanceState(Activity activity, Bundle outState,
        PersistableBundle outPersistentState) {
    activity.performSaveInstanceState(outState, outPersistentState);
}

Activity.java
final void performSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    //调用onSaveInstanceState
    onSaveInstanceState(outState, outPersistentState);
    //保存Dialog
    saveManagedDialogs(outState);
    storeHasCurrentPermissionRequest(outState);
}

看到了Activity的onSaveInstanceState()调用;

2)继续看performPauseActivity()中的performPauseActivityIfNeeded(r, reason):

private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
    if (r.paused) {
        // You are already paused silly...
        return;
    }

    try {
        r.activity.mCalled = false;
        //重点在这里,Activity.onPause方法的调用
        mInstrumentation.callActivityOnPause(r.activity);
        if (!r.activity.mCalled) {
            throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
                    + " did not call through to super.onPause()");
        }
    } catch (SuperNotCalledException e) {
        throw e;
    } catch (Exception e) {
        if (!mInstrumentation.onException(r.activity, e)) {
            throw new RuntimeException("Unable to pause activity "
                    + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
        }
    }
    //设置当前的状态为ON_PAUSE
    r.setState(ON_PAUSE);
}

重点是mInstrumentation.callActivityOnPause(r.activity):

Instrumentation.java
public void callActivityOnPause(Activity activity) {
    activity.performPause();
}

Activity.java
final void performPause() {
    mDoReportFullyDrawn = false;
    //改变Fragment的状态
    mFragments.dispatchPause();
    mCalled = false;
    //调用Activity的生命周期onPause()方法
    onPause();
    writeEventLog(LOG_AM_ON_PAUSE_CALLED, "performPause");
    //此时已经是非mResumed状态
    mResumed = false;
    if (!mCalled && getApplicationInfo().targetSdkVersion
            >= android.os.Build.VERSION_CODES.GINGERBREAD) {
        throw new SuperNotCalledException(
                "Activity " + mComponent.toShortString() +
                " did not call through to super.onPause()");
    }
}

3)当Launcher处于onPause状态后,通知OnActivityPausedListener执行监听操作,这个跟NFC有关,先不讨论;

分析到了这里,我们来总结下目前遇到的Launcher的生命周期:

onUserInteraction(),onUserLeaveHint()-->onSaveInstanceState()-->onPause();

 

走到了这里,才刚分析完了lifecycleItem.execute()方法,继续看下面的 lifecycleItem.postExecute():

当app进程中的pause操作结束之后,需要通知AMS进程,进行下一步操作,调用PauseActivityItem.postExecute():

public void postExecute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    if (mDontReport) {
        return;
    }
    try {
        //调用AMS的activityPaused()方法
        ActivityManager.getService().activityPaused(token);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
}

这样,Launcher暂停就分析完了;

 

2.ActivityThread.attach()

当系统为Settings fork出一个进程之后,便会调用ActivityThread.main()方法:

public static void main(String[] args) {
    ............

    //设置临时进程名为<pre-initialized>
    Process.setArgV0("<pre-initialized>");

    //准备UI主线程的消息循环
    Looper.prepareMainLooper();

    ............

    //创建ActivityThread,并调用attach 方法,传入的参数为false
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);

    ............

    /// M: ANR Debug Mechanism
    mAnrAppManager.setMessageLogger(Looper.myLooper());
    //进入主线程消息循环
    Looper.loop();

    throw new RuntimeException("Main thread loop unexpectedly exited");
}

创建了ActivityThread,并调用attach方法:

private void attach(boolean system, long startSeq) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    if (!system) {//成立
        ViewRootImpl.addFirstDrawHandler(new Runnable() {
            @Override
            public void run() {
                ensureJitEnabled();
            }
        });
        //设置DDMS中显示的临时进程名
        android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                                                UserHandle.myUserId());
        /*mAppThread是在创建ActivityThread的时候初始化的,其类型为ApplicationThread,记录该应用程序,用于报告虚拟机错误*/
        RuntimeInit.setApplicationObject(mAppThread.asBinder());
        //获取ActivityManagerService的代理对象,即ActivityManager
        final IActivityManager mgr = ActivityManager.getService();
        try {
            //将应用进程attach到ActivityManagerService
            mgr.attachApplication(mAppThread, startSeq);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        ............
    } else {
        ............
}

看AMS.attachApplication();

 

3.ApplicationThread.bindApplication()

在AMS.attachApplication()中,会调用ActivityThread.ApplicationThread.bindApplication():

public final void bindApplication(String processName, .........) {
    ............

    //bindApplication将ActivityManagerService传入的数据封装到AppBindData中
    AppBindData data = new AppBindData();
    data.processName = processName;
 	............

    //通过BIND_APPLICATION消息发送给应用程序主线程的消息循环中,由ActivityThread的H.handleMessage处理。
    sendMessage(H.BIND_APPLICATION, data);
}

发送通知,由ActivityThread来接收:

public void handleMessage(Message msg) {
    switch (msg.what) {
        case BIND_APPLICATION:
            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
            AppBindData data = (AppBindData)msg.obj;
            //调用handleBindApplication()
            handleBindApplication(data);
            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            break;
    ............
    }
}

继续来看handleBindApplication()函数:

private void handleBindApplication(AppBindData data) {
    ............

    //创建并初始化应用程序的ContextImpl 
    final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
    updateLocaleListFromAppContext(appContext,
            mResourcesManager.getConfiguration().getLocales());

    ............


    if (ii != null) {
        ............
    } else {
        //创建并且初始化mInstrumentation
        mInstrumentation = new Instrumentation();
        mInstrumentation.basicInit(this);
    }

    ............

    Application app;
    final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
    final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
    try {
        //创建应用程序Application,对应AndroidManifest.xml的Application
        app = data.info.makeApplication(data.restrictedBackupMode, null);

        app.setAutofillCompatibilityEnabled(data.autofillCompatibilityEnabled);

        //将第一个Application视为进程的初始Application
        mInitialApplication = app;

        //安装该应用程序的ContentProvider
        if (!data.restrictedBackupMode) {
            if (!ArrayUtils.isEmpty(data.providers)) {
                installContentProviders(app, data.providers);
                mH.sendEmptyMessageDelayed(H.ENABLE_JIT, 10*1000);
            }
        }

        try {
            //调用Instrumentation的onCreate方法
            mInstrumentation.onCreate(data.instrumentationArgs);
        }
        catch (Exception e) {
            ............
        }
        try {
            //调用Application的onCreate方法
            mInstrumentation.callApplicationOnCreate(app);
        } catch (Exception e) {
           ............
        }
    } finally {
       ............
    }
    ............
}

点评:总结下上面代码所做的事:

①创建Settings的ActivityThread,并调用ActivityThread.attach();

②通过AMS,调用ApplicationThread.bindApplication()--->发送BIND_APPLICATION消息-->handleBindApplication();

③创建并初始化ContextImpl--->创建并初始化mInstrumentation--->创建Application-->Instrumentation.onCreate()--->Application.onCreate();

④进入Looper循环;

 

4.Settings的onCreate,onStart和onResume

在AMS的attachApplication()中,通过IPC的方式进行了ActivityThread.ApplicationThread.bindApplication()之后,会调用mStackSupervisor.attachApplicationLocked(app),mStackSupervisor就是ActivityStackSupervisor,我们来看下代码:

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
        boolean andResume, boolean checkConfig) throws RemoteException {

    try {     
        ............
        try {
           
            ............

            // Create activity launch transaction.
            final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                    r.appToken);
            //①先将LaunchActivityItem做为Callback
            clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                    System.identityHashCode(r), r.info,
                    mergedConfiguration.getGlobalConfiguration(),
                    mergedConfiguration.getOverrideConfiguration(), r.compat,
                    r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                    r.persistentState, results, newIntents, mService.isNextTransitionForward(),
                    profilerInfo));

            final ActivityLifecycleItem lifecycleItem;
            if (andResume) {//andResume为true
                lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
            } else {
                lifecycleItem = PauseActivityItem.obtain();
            }
            //②再设置ResumeActivityItem
            clientTransaction.setLifecycleStateRequest(lifecycleItem);
            // Schedule transaction.
            //scheduleTransaction会一次调用LaunchActivityItem和ResumeActivityItem的execute()方法,
            //接下来调用Activity生命周期,主要包括onCreate、onStart和onResume
            mService.getLifecycleManager().scheduleTransaction(clientTransaction);

            ............

        } catch (RemoteException e) {

            ............

    } finally {
        ............
    }

    ............

    return true;
}

点评:创建了一个ClientTransaction,将LaunchActivityItem添加到它的mActivityCallbacks中,将ResumeActivityItem作为它的mLifecycleStateRequest,然后调用ClientTransaction.schedule()进行IPC,也就是调用ApplicationThread.scheduleTransaction(),这个流程跟Launcher暂停阶段是一样的,我们就不分析了,直接来看TransactionExecutor.execute();

public void execute(ClientTransaction transaction) {
    //token就是IApplicationToken.Stub
    final IBinder token = transaction.getActivityToken();
    log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);

    //执行Callbacks,LaunchActivityItem就是在这里执行的
    executeCallbacks(transaction);

    //我们要看的是这个
    executeLifecycleState(transaction);
    mPendingActions.clear();
    log("End resolving transaction");
}

点评:

①executeCallbacks(transaction)

由于我们将LaunchActivityItem添加到ClientTransaction的mActivityCallbacks中是,所以上述的executeCallbacks(transaction)是有意义的;

public void executeCallbacks(ClientTransaction transaction) {
    final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
    if (callbacks == null) {
        // No callbacks to execute, return early.
        return;
    }
    log("Resolving callbacks");

    final IBinder token = transaction.getActivityToken();
    ActivityClientRecord r = mTransactionHandler.getActivityClient(token);

    final ActivityLifecycleItem finalStateRequest = transaction.getLifecycleStateRequest();
    final int finalState = finalStateRequest != null ? finalStateRequest.getTargetState()
            : UNDEFINED;
    // Index of the last callback that requests some post-execution state.
    final int lastCallbackRequestingState = lastCallbackRequestingState(transaction);

    final int size = callbacks.size();//size为1
    for (int i = 0; i < size; ++i) {
        final ClientTransactionItem item = callbacks.get(i);
        log("Resolving callback: " + item);
        final int postExecutionState = item.getPostExecutionState();
        final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
                item.getPostExecutionState());
        if (closestPreExecutionState != UNDEFINED) {
            cycleToPath(r, closestPreExecutionState);
        }

        //item就是LaunchActivityItem,执行LaunchActivityItem的execute
        item.execute(mTransactionHandler, token, mPendingActions);
        //执行LaunchActivityItem的postExecute
        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);
        }
    }
}

先是执行LaunchActivityItem的execute(),再执行LaunchActivityItem的postExecute(),由于LaunchActivityItem的postExecute()并没有具体实现,所以只看LaunchActivityItem.execute():

public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
    ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
            mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
            mPendingResults, mPendingNewIntents, mIsForward,
            mProfilerInfo, client);
    //调用ActivityThread.ApplicationThread的handleLaunchActivity
    client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}

通过IPC,调用调用ActivityThread.ApplicationThread的handleLaunchActivity():

public Activity handleLaunchActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions, Intent customIntent) {
    unscheduleGcIdler();
    mSomeActivitiesChanged = true;

    if (r.profilerInfo != null) {
        mProfiler.setProfiler(r.profilerInfo);
        mProfiler.startProfiling();
    }

    handleConfigurationChanged(null, null);

    if (!ThreadedRenderer.sRendererDisabled) {
        GraphicsEnvironment.earlyInitEGL();
    }

    //获取WMS
    WindowManagerGlobal.initialize();

    //调用performLaunchActivity()方法,本例为com.android.settings.Settings
    final Activity a = performLaunchActivity(r, customIntent);

    if (a != null) {
        //创建Configuration
        r.createdConfig = new Configuration(mConfiguration);
        reportSizeConfigurations(r);
        if (!r.activity.mFinished && pendingActions != null) {
            pendingActions.setOldState(r.state);
            pendingActions.setRestoreInstanceState(true);
            pendingActions.setCallOnPostCreate(true);
        }
    } else {
        //Activity启动失败,直接销毁
        try {
            ActivityManager.getService()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                            Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }

    return a;
}

点评:主要做了两件事,一是创建Configuration,并且调用Activity.onConfigurationChanged(),二是调用performLaunchActivity()方法,Activity.onConfigurationChanged()我们暂时就不分析了,主要看performLaunchActivity()函数:

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    //获取Activity信息
    ActivityInfo aInfo = r.activityInfo;
    if (r.packageInfo == null) {
        //获取应用程序Activity的LoadedApk
        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);
    }
    //得到Activity对应的Context
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        /*通过Java反射机制加载并创建Activity对象,本例中创建com.android.settings.Settings*/
        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 {
        /*app中存储要启动的应用程序包名、Activity名、APK文件名等信息,
        本例中主要包含以下信息com.android.settings/com.android.settings Settingsdir=/system/app/Settings.apk*/
        //得到Application 
        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) {
            //activity的title
            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;
            }
            //Activity与ContextImpl进行关联
            appContext.setOuterContext(activity);
            //将其他信息附加(attach)到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) {
                //调用setTheme()方法
                activity.setTheme(theme);
            }

            activity.mCalled = false;
            //回调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;
        }
        //设置Settings的状态为ON_CREATE
        r.setState(ON_CREATE);

        /*在应用程序主线程中记录当前Activity,r.token是AMS中存储的ActivityRecord的BinderProxy*/
        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.attach(),并且调用mInstrumentation.callActivityOnCreate()方法;我们来分析下Activity.attach()和mInstrumentation.callActivityOnCreate();

(1)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) {
    //Activity关联到Context
    attachBaseContext(context);

    mFragments.attachHost(null /*parent*/);

    //创建Activity对应的Window,对于手机,这个窗口是PhoneWindow
    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);
    }
    if (info.uiOptions != 0) {
        mWindow.setUiOptions(info.uiOptions);
    }

    //当前线程视为UI线程
    mUiThread = Thread.currentThread();

    //当前ActivityThread视为主线程
    mMainThread = aThread;
    mInstrumentation = instr;
    //ActivityManagerService中ActivityRecord的BinderProxy
    mToken = token;
    mIdent = ident;
    mApplication = application;
    mIntent = intent;
    mReferrer = referrer;
    mComponent = intent.getComponent();
    mActivityInfo = info;
    mTitle = title;
    //本例为null
    mParent = parent;
    mEmbeddedID = id;
    mLastNonConfigurationInstances = lastNonConfigurationInstances;
    if (voiceInteractor != null) {
        if (lastNonConfigurationInstances != null) {
            mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
        } else {
            mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
                    Looper.myLooper());
        }
    }

    //窗口需要使用WindowManager,PhoneWindow与WindowManager进行绑定
    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);

    setAutofillCompatibilityEnabled(application.isAutofillCompatibilityEnabled());
    enableAutofillCompatibilityIfNeeded();
}

(2)mInstrumentation.callActivityOnCreate()

public void callActivityOnCreate(Activity activity, Bundle icicle) {
    prePerformCreate(activity);
    //调用activity.performCreate()
    activity.performCreate(icicle);
    postPerformCreate(activity);
}
final void performCreate(Bundle icicle) {
    performCreate(icicle, null);
}

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    mCanEnterPictureInPicture = true;
    restoreHasCurrentPermissionRequest(icicle);
    if (persistentState != null) {
        //调用onCreate()方法
        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()
    mFragments.dispatchActivityCreated();
    mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
}

我们终于把executeCallbacks(transaction)函数分析完了,下面分析executeLifecycleState();

 

②executeLifecycleState():

private void executeLifecycleState(ClientTransaction transaction) {
        //此时得到lifecycleItem为ResumeActivityItem
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        if (lifecycleItem == null) {
            // No lifecycle request, return early.
            return;
        }
        log("Resolving lifecycle state: " + lifecycleItem);

        //得到token
        final IBinder token = transaction.getActivityToken();
        final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);

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

        //本次流程中的lifecycleItem是ResumeActivityItem,所以lifecycleItem.getTargetState()为3;
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);

        //将动作传递给ResumeActivityItem执行,ResumeActivityItem在AMS进程当中,这里又进行了IPC
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        //通知AMS进程,进行下一步操作
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }

再来看下cycleToPath(),这次和Laucher中的PauseActivityItem不一样了;

private void cycleToPath(ActivityClientRecord r, int finish,
        boolean excludeLastState) {
    //此时Settings的状态是onCreate,所以start为1
    final int start = r.getLifecycleState();
    log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
    final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
    performLifecycleSequence(r, path);
}
public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {//本次流程传递进来的参数是1,3,true
        if (start == UNDEFINED || finish == UNDEFINED) {
            throw new IllegalArgumentException("Can't resolve lifecycle path for undefined state");
        }
        if (start == ON_RESTART || finish == ON_RESTART) {
            throw new IllegalArgumentException(
                    "Can't start or finish in intermittent RESTART state");
        }
        if (finish == PRE_ON_CREATE && start != finish) {
            throw new IllegalArgumentException("Can only start in pre-onCreate state");
        }

        mLifecycleSequence.clear();
        if (finish >= start) {//3>=1,成立
            // just go there
            for (int i = start + 1; i <= finish; i++) {
                mLifecycleSequence.add(i);//①mLifecycleSequence有两个元素,2和3,也就是ON_START和ON_RESUME
            }
        } else { // finish < start, can't just cycle down
            if (start == ON_PAUSE && finish == ON_RESUME) {
                // Special case when we can just directly go to resumed state.
                mLifecycleSequence.add(ON_RESUME);
            } else if (start <= ON_STOP && finish >= ON_START) {
                // Restart and go to required state.

                // Go to stopped state first.
                for (int i = start + 1; i <= ON_STOP; i++) {
                    mLifecycleSequence.add(i);
                }
                // Restart
                mLifecycleSequence.add(ON_RESTART);
                // Go to required state
                for (int i = ON_START; i <= finish; i++) {
                    mLifecycleSequence.add(i);
                }
            } else {
                // Relaunch and go to required state

                // Go to destroyed state first.
                for (int i = start + 1; i <= ON_DESTROY; i++) {
                    mLifecycleSequence.add(i);
                }
                // Go to required state
                for (int i = ON_CREATE; i <= finish; i++) {
                    mLifecycleSequence.add(i);
                }
            }
        }

        // Remove last transition in case we want to perform it with some specific params.
        if (excludeLastState && mLifecycleSequence.size() != 0) {//成立
            //②将mLifecycleSequence中的最后一个元素去掉,mLifecycleSequence中只剩下ON_START
            mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
        }

        return mLifecycleSequence;
    }

由上面的代码得知,path中只有一个元素ON_START,继续看performLifecycleSequence(r, path):

private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
    final int size = path.size();
    for (int i = 0, state; i < size; i++) {
        state = path.get(i);
        log("Transitioning to state: " + state);
        switch (state) {
            case ON_CREATE:
                mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                        null /* customIntent */);
                break;
            case ON_START://成立
                //调用ActivityTread.handleStartActivity()方法
                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);
        }
    }
}

mTransactionHandler.handleStartActivity(r, mPendingActions)中,mTransactionHandler就是ActivityThread,继续看ActivityThread.handleStartActivity()方法:

public void handleStartActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions) {
    final Activity activity = r.activity;
    if (r.activity == null) {
        // TODO(lifecycler): What do we do in this case?
        return;
    }
    if (!r.stopped) {
        throw new IllegalStateException("Can't start activity that is not stopped.");
    }
    if (r.activity.mFinished) {
        // TODO(lifecycler): How can this happen?
        return;
    }

    // Start
    //回调onstart方法
    activity.performStart("handleStartActivity");
    //设置当前状态为ON_START
    r.setState(ON_START);

    if (pendingActions == null) {
        // No more work to do.
        return;
    }

    // Restore instance state
    if (pendingActions.shouldRestoreInstanceState()) {
        //回调onRestoreInstanceState 方法
        if (r.isPersistable()) {
            if (r.state != null || r.persistentState != null) {//本例为false
                mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                        r.persistentState);
            }
        } else if (r.state != null) {
            mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
        }
    }

    // Call postOnCreate()
    if (pendingActions.shouldCallOnPostCreate()) {
        activity.mCalled = false;
        //回调onPostCreate 方法
        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()");
        }
    }
}

分析完了cycleToPath(),接下来再看ResumeActivityItem.execute()和ResumeActivityItem.postExecute();

public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
    //调用ActivityThread.ApplicationThread的handleResumeActivity()方法
    client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
            "RESUME_ACTIVITY");
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}

继续看ActivityThread.ApplicationThread的handleResumeActivity()方法:

public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
        String reason) {
    unscheduleGcIdler();
    mSomeActivitiesChanged = true;

    //调用performResumeActivity,回调onResume方法
    final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
    if (r == null) {
        return;
    }

    final Activity a = r.activity;

    final int forwardBit = isForward
            ? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;

    /*此时mStartedActivity为false。如果该值为true,说明上一个Activity还在执行onResume方法*/
    boolean willBeVisible = !a.mStartedActivity;
    if (!willBeVisible) {//本例为true,表示该Activity可见

        try {
            willBeVisible = ActivityManager.getService().willActivityBeVisible(
                    a.getActivityToken());
        } catch (RemoteException e) {
            throw e.rethrowFromSystemServer();
        }
    }
    if (r.window == null && !a.mFinished && willBeVisible) {
        r.window = r.activity.getWindow();
        View decor = r.window.getDecorView();//设置根view
        //此时的view不可见
        decor.setVisibility(View.INVISIBLE);
        ViewManager wm = a.getWindowManager();
        WindowManager.LayoutParams l = r.window.getAttributes();
        a.mDecor = decor;
        //Activity的窗口类型
        l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
        l.softInputMode |= forwardBit;
        if (r.mPreserveWindow) {
            a.mWindowAdded = true;
            r.mPreserveWindow = false;
            ViewRootImpl impl = decor.getViewRootImpl();
            if (impl != null) {
                impl.notifyChildRebuilt();
            }
        }
        if (a.mVisibleFromClient) {
            if (!a.mWindowAdded) {
                a.mWindowAdded = true;
                //向WMS中添加activity窗口
                wm.addView(decor, l);
            } else {
                a.onWindowAttributesChanged(l);
            }
        }

    } else if (!willBeVisible) {
        //如果Activity在onResume时,启动了另一个Activity,此时窗口不可见
        r.hideForNow = true;
    }

    cleanUpPendingRemoveWindows(r, false /* force */);

    if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
        if (r.newConfig != null) {
            //执行Activity的onConfigurationChanged()
            performConfigurationChangedForActivity(r, r.newConfig);
            r.newConfig = null;
        }
        WindowManager.LayoutParams l = r.window.getAttributes();
        if ((l.softInputMode
                & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
                != forwardBit) {
            l.softInputMode = (l.softInputMode
                    & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
                    | forwardBit;
            if (r.activity.mVisibleFromClient) {
                ViewManager wm = a.getWindowManager();
                View decor = r.window.getDecorView();
                //更新Acitivty的窗口
                wm.updateViewLayout(decor, l);
            }
        }

        r.activity.mVisibleFromServer = true;
        //当前屏幕可见Activity数,此时为1
        mNumVisibleActivities++;
        if (r.activity.mVisibleFromClient) {
            //根view由不可见变为可见
            r.activity.makeVisible();
        }
    }

    r.nextIdle = mNewActivities;
    mNewActivities = r;
    //onResume后进入Idle状态,此时将向主线程的消息队列注册IdleHandler
    Looper.myQueue().addIdleHandler(new Idler());
}

重点关注performResumeActivity()方法:

public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
        String reason) {
    final ActivityClientRecord r = mActivities.get(token);
    if (r == null || r.activity.mFinished) {
        return null;
    }
    if (r.getLifecycleState() == ON_RESUME) {
        if (!finalStateRequest) {
            final RuntimeException e = new IllegalStateException(
                    "Trying to resume activity which is already resumed");
        }
        return null;
    }
    if (finalStateRequest) {
        r.hideForNow = false;
        r.activity.mStartedActivity = false;
    }
    try {
        r.activity.onStateNotSaved();
        r.activity.mFragments.noteStateNotSaved();
        checkAndBlockForNetworkAccess();
        if (r.pendingIntents != null) {
            //调用Activity生命周期的onNewIntent方法
            deliverNewIntents(r, r.pendingIntents);
            r.pendingIntents = null;
        }
        if (r.pendingResults != null) {
            //调用Activity生命周期的onActivityResult方法
            deliverResults(r, r.pendingResults, reason);
            r.pendingResults = null;
        }
        //调用Activity生命周期的onResume方法
        r.activity.performResume(r.startsNotResumed, reason);

        r.state = null;
        r.persistentState = null;
        r.setState(ON_RESUME);
    } catch (Exception e) {
        if (!mInstrumentation.onException(r.activity, e)) {
            throw new RuntimeException("Unable to resume activity "
                    + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
        }
    }
    return r;
}

点评:ResumeActivityItem.execute()也分析完了,接下来就是ResumeActivityItem.postExecute():

public void postExecute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    try {
        //调用AMS的activityResumed(),通知AMS
        ActivityManager.getService().activityResumed(token);
    } catch (RemoteException ex) {
        throw ex.rethrowFromSystemServer();
    }
}

通知AMS,进入下一个生命周期;

总结,上面的流程过于复杂,我们先来归纳一下相关的Activity生命周期:

①创建Configuration,调用Activity.onConfigurationChanged()--->创建并初始化Activity对应的Context-->创建Activity对象--->创建并初始化Application--->Activity与ContextImpl进行关联;

②activity.attach();

创建并初始化PhoneWindow-->创建并初始化mUiThread和mMainThread--->创建并初始化mInstrumentation--->PhoneWindow与WindowManager进行绑定;

③activity.setTheme(theme)--->mInstrumentation.callActivityOnCreate(activity, r.state);也就是调用onCreate()--->设置Settings的状态为ON_CREAT;

④onstart()-->设置当前状态为ON_START-->onRestoreInstanceState()--->onPostCreate();

⑤如有必要,调用onNewIntent()-->如有必要,onActivityResult()--->onResume()-->设置根View,向WMS中添加activity窗口--->

Activity.onConfigurationChanged();

 

4.Launcher的onStop()

Settings在onResume后就进入了Idle状态,此时将向主线程的消息队列注册IdleHandler,它会调用AMS.activityIdle()方法,在AMS.activityIdle()方法中,获取mStoppingActivities中存储的待停止的Activity,Launcher在onPause之后就被添加在了这个mStoppingActivities容器里面,接下来我们会看到这段代码:

mService.getLifecycleManager().scheduleTransaction(r.app.thread, r.appToken, StopActivityItem.obtain(r.visible, r.configChangeFlags));

从上面的分析得知,会调用StopActivityItem.execute()方法:

public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStop");
    client.handleStopActivity(token, mShowWindow, mConfigChanges, pendingActions,
            true /* finalStateRequest */, "STOP_ACTIVITY_ITEM");
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}

继而转向ActivityThread.ApplicationThread.handleStopActivity():

ActivityThread.java
public void handleStopActivity(IBinder token, boolean show, int configChanges,
        PendingTransactionActions pendingActions, boolean finalStateRequest, String reason) {
    final ActivityClientRecord r = mActivities.get(token);
    r.activity.mConfigChangeFlags |= configChanges;

    final StopInfo stopInfo = new StopInfo();
    
    //执行performStopActivityInner(),show为false
    performStopActivityInner(r, stopInfo, show, true /* saveState */, finalStateRequest,
            reason);


    //设置根view不可见
    updateVisibility(r, show);

    // Make sure any pending writes are now committed.
    if (!r.isPreHoneycomb()) {
        QueuedWork.waitToFinish();
    }

    stopInfo.setActivity(r);
    stopInfo.setState(r.state);
    stopInfo.setPersistentState(r.persistentState);
    pendingActions.setStopInfo(stopInfo);
    mSomeActivitiesChanged = true;
}


private void performStopActivityInner(ActivityClientRecord r, StopInfo info, boolean keepShown,
        boolean saveState, boolean finalStateRequest, String reason) {
    if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
    if (r != null) {
        if (!keepShown && r.stopped) {//不成立
            ............
        }

        //在stop执行,必须要先强制执行pause,如果已经是pause了,就返回
        performPauseActivityIfNeeded(r, reason);

        if (info != null) {
            ............
        }

        if (!keepShown) {//成立
            //调用callActivityOnStop(),完成stop的逻辑,saveState为true
            callActivityOnStop(r, saveState, reason);
        }
    }
}


private void callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason) {
    final boolean shouldSaveState = saveState && !r.activity.mFinished && r.state == null
            && !r.isPreHoneycomb();
    final boolean isPreP = r.isPreP();
    if (shouldSaveState && isPreP) {//不成立,r.state != null
        callActivityOnSaveInstanceState(r);
    }

    try {
        //调用activity的stop方法
        r.activity.performStop(false /*preserveWindow*/, reason);
    } catch (SuperNotCalledException e) {
        throw e;
    } catch (Exception e) {
        if (!mInstrumentation.onException(r.activity, e)) {
            throw new RuntimeException(
                    "Unable to stop activity "
                            + r.intent.getComponent().toShortString()
                            + ": " + e.toString(), e);
        }
    }

    //设置当前状态为ON_STOP
    r.setState(ON_STOP);

    if (shouldSaveState && !isPreP) {
        callActivityOnSaveInstanceState(r);
    }
}


Activity.java
final void performStop(boolean preserveWindow, String reason) {
    mDoReportFullyDrawn = false;
    mFragments.doLoaderStop(mChangingConfigurations /*retain*/);

    // Disallow entering picture-in-picture after the activity has been stopped
    mCanEnterPictureInPicture = false;

    if (!mStopped) {
        if (mWindow != null) {
            mWindow.closeAllPanels();
        }

        if (!preserveWindow && mToken != null && mParent == null) {
            WindowManagerGlobal.getInstance().setStoppedState(mToken, true);
        }

        mFragments.dispatchStop();

        mCalled = false;
        //调用mInstrumentation.callActivityOnStop()
        mInstrumentation.callActivityOnStop(this);
        writeEventLog(LOG_AM_ON_STOP_CALLED, reason);
        
        ............

        mStopped = true;
    }
    mResumed = false;
}


Instrumentation.java
public void callActivityOnStop(Activity activity) {
    activity.onStop();
}

Activity.java
protected void onStop() {
    if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStop " + this);
    if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
    mActivityTransitionState.onStop();
    //监听Settings的生命周期
    getApplication().dispatchActivityStopped(this);
    mTranslucentCallback = null;
    mCalled = true;

    if (mAutoFillResetNeeded) {
        getAutofillManager().onInvisibleForAutofill();
    }

    if (isFinishing()) {
       ............
    }
}

点评:上述代码,主要做了如下几件事情:

①在stop执行,必须要先强制执行pause,如果已经是pause了,就返回;

②调用activity的stop方法;
③设置当前状态为ON_STOP;

④设置根view不可见;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

renshuguo123723

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值