Activity生命周期-AndroidS解读

Activity生命周期

由系统端ActivityRecord生命周期管理应用程序端的Activity生命周期。

enum ActivityState {
    INITIALIZING,
    STARTED,
    RESUMED,
    PAUSING,
    PAUSED,
    STOPPING,
    STOPPED,
    FINISHING,
    DESTROYING,
    DESTROYED,
    RESTARTING_PROCESS
}

下图是系统端和应用程序端,Activity生命周期管理函数调用的逻辑示意图

image-20210711083436287.png
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
public class ActivityTaskSupervisor implements RecentTasks.Callbacks {

realStartActivityLocked

realStartActivityLocked是启动Activity的入口函数。ClientTransaction,与Client的会话

proc.getThread(),即IApplicationThread 应用程序与服务端通信的线程,binder代理保存在服务端

r.appToken,即Token extends IApplicationToken.Stub,标识一个Activity窗口,binder代理保存在wm、am和客户端

                // Create activity launch transaction.
                final ClientTransaction clientTransaction = ClientTransaction.obtain(
                        proc.getThread(), r.appToken);

ActivityRecord

是客户端activity在服务端的实例代表,同时也是一个窗口令牌

/**
 * An entry in the history stack, representing an activity.
 */
final class ActivityRecord extends WindowToken implements WindowManagerService.AppFreezeListener {
    // Non-null only for application tokens.
    // TODO: rename to mActivityToken
    final ActivityRecord.Token appToken;

    static class Token extends IApplicationToken.Stub {
        private WeakReference weakActivity;
        private final String name;
        private final String tokenString;
        // 对显示组件(客户端)而言,Token,是任意一个Binder的实例,
        // 对显示组件(客户端)来说仅仅是一个创建窗口的令牌,没有其他的含义。
        
ActivityRecord初始化时赋值。
        super(_service.mWindowManager, new Token(_intent).asBinder(), TYPE_APPLICATION, 
        mAtmService = _service;
        appToken = (Token) token;

addCallback,先执行launch Activity,这是一个暂态

r.appToken 通过LaunchActivityItem从wm传递到应用端

clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),

最终Activity生命周期状态:如果是resume状态,则ResumeActivityItem。不是,则PauseActivityItem,从create状态进入到pause状态

                // Set desired final state.
                final ActivityLifecycleItem lifecycleItem;
                if (andResume) {
                    lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
                } else {
                    lifecycleItem = PauseActivityItem.obtain();
                }
                clientTransaction.setLifecycleStateRequest(lifecycleItem);

                // Schedule transaction.
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);

ClientLifecycleManager

服务端对Activity生命周期的事件转发管理类,通过IApplicationThread与应用程序的主线程对象ActivityThread通信

class ClientLifecycleManager {
     * @see ClientTransaction
     */
    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        transaction.schedule();

ClientTransaction

服务端与客户端的会话,对IApplicationThread的包装。封装callback和LifecycleStateRequest两个状态回调

public class ClientTransaction implements Parcelable, ObjectPoolItem {

    /** A list of individual callbacks to a client. */
    @UnsupportedAppUsage
    private List mActivityCallbacks;

    /**
     * Final lifecycle state in which the client activity should be after the transaction is
     * executed.
     */
    private ActivityLifecycleItem mLifecycleStateRequest;

    /** Target client. */
    private IApplicationThread mClient;

    /** Target client activity. Might be null if the entire transaction is targeting an app. */
    private IBinder mActivityToken;

    /** Get the target client of the transaction. */
    public IApplicationThread getClient() {
        return mClient;
    }
  • preExecute
  • transaction message is scheduled
  • execute 先callback再LifecycleStateRequest
  • postExecute 报告状态给服务端
    /**
     * Schedule the transaction after it was initialized. It will be send to client and all its
     * individual parts will be applied in the following sequence:
     * 1. The client calls {@link #preExecute(ClientTransactionHandler)}, which triggers all work
     *    that needs to be done before actually scheduling the transaction for callbacks and
     *    lifecycle state request.
     * 2. The transaction message is scheduled.
     * 3. The client calls {@link TransactionExecutor#execute(ClientTransaction)}, which executes
     *    all callbacks and necessary lifecycle transitions.
     */
    public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }

ActivityThread

应用程序主线程对象,执行服务端的管理请求

ApplicationThread 匿名服务,接收服务端的管理请求,并将消息通过Handler转发到应用程序主线程处理

/**
 * This manages the execution of the main thread in an
 * application process, scheduling and executing activities,
 * broadcasts, and other operations on it as the activity
 * manager requests.
 *
 * {@hide}
 */
public final class ActivityThread extends ClientTransactionHandler {
       // An executor that performs multi-step transactions.
    private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
        private class ApplicationThread extends IApplicationThread.Stub {

ApplicationThread接收到服务端的会话,调用ActivityThread父类的scheduleTransaction

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

ClientTransactionHandler

scheduleTransaction 和 executeTransaction都是调用到TransactionExecutor

/**
 * Defines operations that a {@link android.app.servertransaction.ClientTransaction} or its items
 * can perform on client.
 * @hide
 */
public abstract class ClientTransactionHandler {
    /** Prepare and schedule transaction for execution. */
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
    
    public void executeTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        getTransactionExecutor().execute(transaction);
    }

ApplicationThread转发消息到主线程

                case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    mTransactionExecutor.execute(transaction);

TransactionExecutor

/**
 * Class that manages transaction execution in the correct order.
 * @hide
 */
public class TransactionExecutor {
     * Resolve transaction.
     * First all callbacks will be executed in the order they appear in the list. If a callback
     * requires a certain pre- or post-execution state, the client will be transitioned accordingly.
     * Then the client will cycle to the final lifecycle state if provided. Otherwise, it will
     * either remain in the initial state, or last state needed by a callback.
     */
    public void execute(ClientTransaction transaction) {
        executeCallbacks(transaction);
        executeLifecycleState(transaction);
    }
    /** Transition to the final state if requested by the transaction. */
    private void executeLifecycleState(ClientTransaction transaction) {
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        final IBinder token = transaction.getActivityToken();
        final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);

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

execute会在主线程执行相应的回调,一直到Activity对应的生命周期回调

postExecute将client端activity状态报告给server,封装相应的方法。S上是ActivityClientController,负责与服务端通信

/**
 * Request to move an activity to resumed state.
 * @hide
 */
public class ResumeActivityItem extends ActivityLifecycleItem {
    @Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
                "RESUME_ACTIVITY");
    }

    @Override
    public void postExecute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        try {
            // TODO(lifecycler): Use interface callback instead of AMS.
            ActivityTaskManager.getService().activityResumed(token);
    }

调用activity的attch方法将token传递给activity
这样token就保存在ams,wms和app中

Activity中Token主要用于在请求AMS服务时用于定位到具体到AMS中正确的ActivityRecord

public class LaunchActivityItem extends ClientTransactionItem {
    @Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
                mPendingResults, mPendingNewIntents, mIsForward,
                mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
以ResumeActivityItem为例

ActivityTask的resumeTopActivityInnerLocked是系统切换Activity的入口

启动与应用线程的scheduleTransaction

ActivityTask

                final ClientTransaction transaction =
                        ClientTransaction.obtain(next.app.getThread(), next.appToken);
                // Well the app will no longer be stopped.
                // Clear app token stopped state in window manager if needed.
                next.notifyAppResumed(next.stopped);

                EventLogTags.writeWmResumeActivity(next.mUserId, System.identityHashCode(next),
                        next.getTask().mTaskId, next.shortComponentName);
                transaction.setLifecycleStateRequest(
                        ResumeActivityItem.obtain(next.app.getReportedProcState(),
                                dc.isNextTransitionForward()));
                mAtmService.getLifecycleManager().scheduleTransaction(transaction);

ActivityThread

    /** Prepare and schedule transaction for execution. */
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }

TransactionExecutor

TransactionExecutor

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

ResumeActivityItem

public class ResumeActivityItem extends ActivityLifecycleItem {
    @Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {

        client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward, "RESUME_ACTIVITY");

    }
    
    @Override
    public void postExecute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        try {
            ActivityClient.getInstance().activityResumed(token);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }

执行onResume的流程

handleResumeActivity
    performResumeActivity
    reportTopResumedActivityChanged
        r.activity.performResume
            // mResumed is set by the instrumentation
            mInstrumentation.callActivityOnResume(this);// Instrumentation隔离Activity
                activity.onResume();

postExecute响应系统进程的请求

ActivityClient.getInstance().activityResumed(token);

ActivityRecord

ActivityRecord.activityResumedLocked(token);// notifyAppResumedFinished

以ResumeActivityItem为例

startPausingLocked是系统将Activity的onPausede入口

将现在处于resumed状态的Activity切换到pausing状态

ActivityRecord prev = mResumedActivity;
mPausingActivity = prev;
mLastPausedActivity = prev;
prev.setState(PAUSING, "startPausingLocked");

pauseImmediately变量代表是否立即进入completePauseLocked,不用等待应用程序完成onPause,再通知系统

// If the caller said they don't want to wait for the pause, then complete the pause now.

        if (prev.attachedToProcess()) {//当前Activity是有进程的
            try {
                EventLogTags.writeWmPauseActivity(prev.mUserId, System.identityHashCode(prev),
                        prev.shortComponentName, "userLeaving=" + userLeaving);

                mAtmService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),
                        prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving,
                                prev.configChangeFlags, pauseImmediately));
                
            if (pauseImmediately) {
                // If the caller said they don't want to wait for the pause, then complete
                // the pause now.
                completePauseLocked(false, resuming);
                return false;

            } else {
                prev.schedulePauseTimeout();//系统端对应用程序的onPause设置了一个定时器:预防client调用超时
                /*mAtmService.mH.postDelayed(mPauseTimeoutRunnable, PAUSE_TIMEOUT);*/
                return true;
            }

PauseActivityItem

public class PauseActivityItem extends ActivityLifecycleItem {
    @Override
    public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) {
        client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions, "PAUSE_ACTIVITY_ITEM");
    }

    @Override
    public void postExecute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) {
        if (mDontReport) { 即系统端的pauseImmediately
            return;
        }
        try {
            // TODO(lifecycler): Use interface callback instead of AMS.
            ActivityClient.getInstance().activityPaused(token);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }

ActivityThread

handlePauseActivity
    performPauseActivity
        performPauseActivityIfNeeded
        reportTopResumedActivityChanged
            mInstrumentation.callActivityOnPause(r.activity);
                activity.performPause()
                    onPause();
                    EventLogTags.writeWmOnPausedCalled(mIdent, getComponentName().getClassName(), "performPause");

postExecute 响应系统进程的请求

ActivityClient.getInstance().activityPaused(token);

ActivityRecord

final ActivityRecord r = ActivityRecord.forTokenLocked(token);
if (r != null) {
    r.activityPaused(false);
}

通过响应系统进程请求,可知应用程序处理onPause状态并没有超时,移出定时器removePauseTimeout()

    void activityPaused(boolean timeout) {
        final ActivityStack stack = getStack();
        if (stack != null) {
            removePauseTimeout(); // mAtmService.mH.removeCallbacks(mPauseTimeoutRunnable);

            if (stack.mPausingActivity == this) { 之前ing的Activity的,正是当前回调回来的Activity
                mAtmService.deferWindowLayout();//暂停布局
                try { //进一步完成onPause之后的处理
                    stack.completePauseLocked(true /* resumeNext */, null /* resumingActivity */);
                } finally {
                    mAtmService.continueWindowLayout();//继续布局
                }
                return;
            }

ActivityTask

makeFinishingLocked表示当前ActivityRecord需要销毁掉

    void makeFinishingLocked() {
        if (finishing) {
            return;
        }
        finishing = true;
        if (stopped) {
            clearOptionsLocked();
        }
    }

completePauseLocked执行完这个函数后,mPausingActivity = null

void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {
            ActivityRecord prev = mPausingActivity;

        if (prev != null) {
            final boolean wasStopping = prev.isState(STOPPING);
            prev.setState(PAUSED, "completePausedLocked"); //设置状态为ed。Activity在系统端进入Paused状态,可能需要将其加入stopping列表

          if (prev.finishing) {//如果activity已经要finishing,直接调用completeFinishing
                prev = prev.completeFinishing("completePausedLocked");
            }
            
                    // If we were visible then resumeTopActivities will release resources before
                    // stopping.
                    prev.addToStopping(true /* scheduleIdle */, false /* idleDelayed */, "completePauseLocked");

mPausingActivity = null;
            //这时,继续Activity 切换,启动下一个Activity
        if (resumeNext) {//寻找焦点task,将其队头Activity设置为resume状态

你可能感兴趣的:(Activity生命周期-AndroidS解读)