ActivityManagerService--Activity销毁流程

流程图

finish流程

ActivityFinish流程以及结果接收的流程

在调用完setResult以及finish之后,开始启动Activity销毁以及结果返回的流程。

setResult以及finish(用户进程)

保存resultCode以及data,并且通过finishActivity告知AMS开始销毁当前Activity,并且携带参数

public final void setResult(int resultCode, Intent data) {
        synchronized (this) {
            mResultCode = resultCode;
            mResultData = data;
        }
    }

private void finish(int finishTask) {
        if (mParent == null) {
            int resultCode;
            Intent resultData;
            synchronized (this) {
                resultCode = mResultCode;
                resultData = mResultData;
            }
            if (false) Log.v(TAG, "Finishing self: token=" + mToken);
            try {
                if (resultData != null) {
                    resultData.prepareToLeaveProcess(this);
                }
                if (ActivityManager.getService()
                        .finishActivity(mToken, resultCode, resultData, finishTask)) {
                    mFinished = true;
                }
            } catch (RemoteException e) {
                // Empty
            }
        } else {
            mParent.finishFromChild(this);
        }
    }
ActivityManagerService.finishActivity(System_Server进程)

ActivityManagerService中,会判断是否要finish整个Task,如果是的话,则直接把Task从ActivityStackSupervisor中移除,如果不是的话,则调用requestFinishActivityLoacked销毁Activity,并且将resultData传入。

 final boolean finishWithRootActivity =
                        finishTask == Activity.FINISH_TASK_WITH_ROOT_ACTIVITY;
                if (finishTask == Activity.FINISH_TASK_WITH_ACTIVITY
                        || (finishWithRootActivity && r == rootR)) {
                    //  判断是否要结束整个Task
                    res = mStackSupervisor.removeTaskByIdLocked(tr.taskId, false, finishWithRootActivity);
                    if (!res) {
                        Slog.i(TAG, "Removing task failed to finish activity");
                    }
                } else {
                    //  如果不清除Task的话,则只清理单独的Activity
                    res = tr.getStack().requestFinishActivityLocked(token, resultCode,resultData, "app-request", true);
                    if (!res) {
                        Slog.i(TAG, "Failed to finish by app-request");
                    }
                }
ActivityStack.finishActivityLocked(System_Server进程)

ActivityStack.requestFinishActivityLocked最终会调用到finishActivityLocked函数中。

  • 修改ActivityRecord中的finishing标识位为true
  • 停止接收Key事件
  • 将Result结果保存到接收者中
  • 开始暂停当前Activity
...
try {
            //  将ActivityRecord中的finishing置成true,表示正在处于Finishing状态
            r.makeFinishingLocked();
            ...
            //  停止接收Key事件的分发
            r.pauseKeyDispatchingLocked();
            //  重新调整FocusedActivity栈
            adjustFocusedActivityStackLocked(r, "finishActivity");
            //  将resultData也就是返回的数据保存到r.resultTo的ActivityRecord中
            finishActivityResultsLocked(r, resultCode, resultData);
            //  如果当前的Activity是该Task最后一个Activity的话,那么就需要销毁Task
            final boolean endTask = index <= 0;
            if (mResumedActivity == r) {
                ...
                //  准备Activity切换的窗口动画
                mWindowManager.prepareAppTransition(transit, false);
                //  告诉WindowManager准备当前的Activity准备移除
                r.setVisibility(false);
                //  如果当前没有Pausing的Activity的话
                if (mPausingActivity == null) {
                    //  开始Pausing当前的Activity
                    startPausingLocked(false, false, null, pauseImmediately);
                }
                // 如果需要销毁Task的话,那么就开始销毁
                if (endTask) {
                    mStackSupervisor.removeLockedTaskLocked(task);
                }
            } else if (r.state != ActivityState.PAUSING) {
                //  如果当前的Activity正处于Pausing 的状态的话,那么就会等它Pausing完成之后开始销毁,否则在这个地方直接销毁
                if (r.visible) {
                    prepareActivityHideTransitionAnimation(r, transit);
                }
                final int finishMode = (r.visible || r.nowVisible) ? FINISH_AFTER_VISIBLE
                        : FINISH_AFTER_PAUSE;
                //  直接调用finishCurrentActivityLocked销毁当前的Activity
                final boolean removedActivity = finishCurrentActivityLocked(r, finishMode, oomAdj)
                        == null;
                ...
            }
...
ActivityStack. startPausingLocked(System_Server进程)
  • 更新mResumedActivityprev.state
  • 调用schedulePauseActivity暂停Activity
  • 延迟发送消息,检测Pause超时
...
ActivityRecord prev = mResumedActivity;
if (prev == null) {
      if (resuming == null) {
         // 如果没有要暂停的Activity的话,就直接resume栈顶的Activity
         mStackSupervisor.resumeFocusedStackTopActivityLocked();
      }
      return false;
}
...
//  更新当前保存的ResumedActivity,因为即将进入Pausing状态
mResumedActivity = null;
//  将正在Pausing的Activity赋值为即将进入Pausing的Activity
mPausingActivity = prev;
mLastPausedActivity = prev;
mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
                || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null;
//  将当前Activity状态置成Pausing
prev.state = ActivityState.PAUSING;
... 
final ActivityRecord next = mStackSupervisor.topRunningActivityLocked();
if (prev.app != null && prev.app.thread != null) {
       ...
       //  回调Activity的Pause函数,pauseImmediately为false
       prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
                        userLeaving, prev.configChangeFlags, pauseImmediately);
           ...
        } else {
            mPausingActivity = null;
            mLastPausedActivity = null;
            mLastNoHistoryActivity = null;
        }
}
...
        if (mPausingActivity != null) {
            //  判断是否是立即暂停,如果是的话,则立即调用completePauseLocked
            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 {
                //  如果不是立即暂停的话,那么就会等待Activity的onPause完毕,并且检测超时
                //  如果pause超时的话,也会继续执行下面的流程
                schedulePauseTimeout(prev);
                return true;
            }
        } else {
            // This activity failed to schedule the
            // pause, so just treat it as being paused now.
            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Activity not running, resuming next.");
            if (resuming == null) {
                mStackSupervisor.resumeFocusedStackTopActivityLocked();
            }
            return false;
        }
ActivityStack.activityPausedLocked(System_Server进程)

当Activity进入Pause的状态后,会通过Binder回调到activityPausedLocked该接口。

        // 根据mToken找到ActivityRecord
        final ActivityRecord r = isInStackLocked(token);
        if (r != null) {
            //  接收到ActivityPause完成的回调后,清理PAUSE_TIMEOUT_MSG
            mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
        }
         //  判断当前Pausing的Activity是否是已经回调过Pause的Activity
         if (mPausingActivity == r) {
             ...
             //  如果是的话,则调用该函数
             completePauseLocked(true /* resumeNext */, null /* resumingActivity */);
         } else {
            ...
            if (r.state == ActivityState.PAUSING) {
                    r.state = ActivityState.PAUSED;
                    if (r.finishing) {
                        if (DEBUG_PAUSE) Slog.v(TAG,
                                "Executing finish of failed to pause activity: " + r);
                        finishCurrentActivityLocked(r, FINISH_AFTER_VISIBLE, false);
                    }
             }
        }
ActivityStack.completePauseLocked(System_Server进程)

如果Pause完毕之后,则开始处理Stop的流程。

  • 如果prev.finishing为true的话,则会调用finishCurrentActivityLocked开始销毁
  • 接着调用resumeFocusedStackTopActivityLocked开始Resume接下来的Activity
         ActivityRecord prev = mPausingActivity;
        if (prev != null) {
            //  判断当前是否是STOPPING的状态
            final boolean wasStopping = prev.state == STOPPING;
            //  将当前状态该成PAUSED
            prev.state = ActivityState.PAUSED;
            //  如果是finishing的话,则调用finishCurrentActivityLocked开始销毁
            if (prev.finishing) {
                if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Executing finish of activity: " + prev);
                prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
            } 
            ...
            //  将PausingActivity置空
             mPausingActivity = null;
        }
        //  开始resume下一个Activity
        if (resumeNext) {
            final ActivityStack topStack = mStackSupervisor.getFocusedStack();
            //  如果当前没有关机或者休眠的话
            if (!mService.isSleepingOrShuttingDownLocked()) {
                //  调用该函数开始resumeActivity
                mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);
            } else {
                mStackSupervisor.checkReadyForSleepLocked();
                ActivityRecord top = topStack.topRunningActivityLocked();
                if (top == null || (prev != null && top != prev)) {
                    mStackSupervisor.resumeFocusedStackTopActivityLocked();
                }
            }
        }
ActivityStack. resumeTopActivityInnerLocked(System_Server进程)

当Pausing完毕后,会调用ActivityStackSupervisor.resumeFocusedStackTopActivityLocked来开始Resume下一个要显示的Activity。最终会调用到resumeTopActivityInnerLocked该函数。

  • 回调ActivityResult的结果,即回调onActivityResult处理返回数据
  • 回调newIntent,即回调onNewIntent
  • 最后开始处理resume流程
 // Deliver all pending results.
                ArrayList<ResultInfo> a = next.results;
                if (a != null) {
                    final int N = a.size();
                    if (!next.finishing && N > 0) {
                        if (DEBUG_RESULTS) Slog.v(TAG_RESULTS,
                                "Delivering results to " + next + ": " + a);
                        //  如果有ActivityResult需要回调的话,先回调onActivityResult
                        next.app.thread.scheduleSendResult(next.appToken, a);
                    }
                }

                if (next.newIntents != null) {
                    //  如果有newIntent的话,先回调onNewIntent
                    next.app.thread.scheduleNewIntent(
                            next.newIntents, next.appToken, false /* andPause */);
                }

               ... 
              //  开始回调onResume
                next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState,
                        mService.isNextTransitionForward(), resumeAnimOptions);
ActivityStack.finishCurrentActivityLocked(System_Server进程)

该函数主要用来完成销毁当前Activity。

//  获取下一个要Resume的Activity
final ActivityRecord next = mStackSupervisor.topRunningActivityLocked()

if (mode == FINISH_AFTER_VISIBLE && (r.visible || r.nowVisible)
                && next != null && !next.nowVisible) {
            //  如果要销毁的Activity目前还是可见的,而要Resume的Activity是不可见的
            //  那么就先把要销毁的Activity放到Stopping队列中,先把要展示的Activity
            //  先进行Resume操作,等Resume完后,回头再销毁这个Activity
            if (!mStackSupervisor.mStoppingActivities.contains(r)) {
                addToStopping(r, false /* scheduleIdle */, false /* idleDelayed */);
            }
            ...
            //  将要销毁的Activity改状态为STOPPING
            r.state = STOPPING;
            ...
            return r;
        }
//  如果mode不是FINISH_AFTER_VISIBLE的话,则从各种队列中先清除
        mStackSupervisor.mStoppingActivities.remove(r);
        mStackSupervisor.mGoingToSleepActivities.remove(r);
        mStackSupervisor.mActivitiesWaitingForVisibleActivity.remove(r);
        if (mResumedActivity == r) {
            mResumedActivity = null;
        }
        //  将状态从STOPPING变成FINISHING
       final ActivityState prevState = r.state;
        r.state = ActivityState.FINISHING;
if (mode == FINISH_IMMEDIATELY
                || (prevState == ActivityState.PAUSED
                    && (mode == FINISH_AFTER_PAUSE || mStackId == PINNED_STACK_ID))
                || finishingActivityInNonFocusedStack
                || prevState == STOPPING
                || prevState == STOPPED
                || prevState == ActivityState.INITIALIZING) {
          ... 
          //  开始销毁Activity
            boolean activityRemoved = destroyActivityLocked(r, true, "finish-imm");

            if (finishingActivityInNonFocusedStack) {
                //  如果Activity不在Focus的Stack中的话,则确保Resume的Activity窗口是可见的
                mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
            }
            if (activityRemoved) {
                mStackSupervisor.resumeFocusedStackTopActivityLocked();
            }
            return activityRemoved ? null : r;
        }
ActivityThread.handleResumeActivity(用户进程)

待Activity处于Resume状态时,ActivityThread会调用该函数。

  • 回调Activity的onRestartonStartonResume函数
  • 处理Activity Window相关的数据保存
  • 如果是ActivityManagerService来的请求,则会将Idler加到主线程队列中,等待主线程空闲时,回调ActivityManagerService.activityIdle
  • 回调ActivityManagerService. activityResumed告知已经处于Resume状态
//  获取Activity在用户进程的ActivityClientRecord
ActivityClientRecord r = mActivities.get(token);
...
//  回调Activity的onResume
 r = performResumeActivity(token, clearHide, reason);

if (r != null) {
            final Activity a = r.activity;
            ...
            //  处理Window相关的事情
            ...
            //  如果是从ActivityManagerService要求的Resume操作的话
            if (!r.onlyLocalRequest) {
                r.nextIdle = mNewActivities;
                mNewActivities = r;
                if (localLOGV) Slog.v(
                    TAG, "Scheduling idle handler for " + r);
                //  将Idler添加到Looper的队列中,而在Idler中
                //  当主线程队列空闲的时候会回调am.activityIdle
                Looper.myQueue().addIdleHandler(new Idler());
            }
            r.onlyLocalRequest = false;

            // Tell the activity manager we have resumed.
            if (reallyResume) {
                try { 
                    //  告知ActivityManagerService当前的Activity处于Resume状态了
                    ActivityManager.getService().activityResumed(token);
                } catch (RemoteException ex) {
                    throw ex.rethrowFromSystemServer();
                }
            }
ActivityStackSupervisor.activityIdleInternal(System_Server进程)

当用户进程处于空闲状态时,就会回调ActivityManagerService.activityIdle。而在该接口中,就会调用activityIdleInternalLocked函数。

//  根据token找到已经Resume的ActivityRecord
 ActivityRecord r = ActivityRecord.forTokenLocked(token);
 if (r != null) {
        //   先移除IDLE_TIMEOUT_MSG的消息
        mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
        ...
}
//  从mStoppingActivities列表中将要stop的Activity选出来
final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,true /* remove */, processPausingActivities);
//  获取StopActivity的数量
 NS = stops != null ? stops.size() : 0;
//  判断当前是否有Finishing的Activity
 if ((NF = mFinishingActivities.size()) > 0) {
        finishes = new ArrayList<>(mFinishingActivities);
         mFinishingActivities.clear();
 }
...
//  遍历所有的StopActivity
 for (int i = 0; i < NS; i++) {
            r = stops.get(i);
            final ActivityStack stack = r.getStack();
            if (stack != null) {
            //  判断是否要finish,之前有标记过该位
                if (r.finishing) {
                    // 如果finishing的话,则调用该函数立即finish
                    stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false);
                } else {
                    //  否则只是调用onStop
                    stack.stopActivityLocked(r);
                }
            }
        }
        //  销毁finishing队列中的Activity
        for (int i = 0; i < NF; i++) {
            r = finishes.get(i);
            final ActivityStack stack = r.getStack();
            if (stack != null) {
                activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
            }
        }
ActivityStack.destroyActivityLocked(System_Server进程)
//  清理ActivityRecord相关的队列与窗口
  cleanUpActivityLocked(r, false, false);
//  判断Activity进程是否存在
  final boolean hadApp = r.app != null;
if (hadApp) {
      //  如果是finishing的话,则是从Activities中移除
     if (removeFromApp) {
        //  移除该ActivityRecord
         r.app.activities.remove(r);
     }
     ...
      boolean skipDestroy = false;
      try {
                //  回调用户进程的scheduleDestroyActivity,开始销毁Activity
                r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
                        r.configChangeFlags);
      } catch (Exception e) {
                if (r.finishing) {
                    removeActivityFromHistoryLocked(r, reason + " exceptionInScheduleDestroy");
                    removedFromHistory = true;
                    //  如果销毁失败的话,置标识位
                    skipDestroy = true;
                }
       }
      ...
      if (r.finishing && !skipDestroy) {
               //  如果执行了Activity用户进程的onDestroy的话,
                r.state = ActivityState.DESTROYING;
               //  则需要定时检测用户进程将销毁成功的消息发送回来
                Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG, r);
                mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
            } else {
                //  如果出现意外了,则要清理app了
                r.state = ActivityState.DESTROYED;
                r.app = null;
            }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券