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<ActivityRecord> 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<ClientTransactionItem> 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状态
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,222评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,455评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,720评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,568评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,696评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,879评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,028评论 3 409
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,773评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,220评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,550评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,697评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,360评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,002评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,782评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,010评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,433评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,587评论 2 350

推荐阅读更多精彩内容