今日同享面试中常见AMS和Activity,首要考察Android开发是否了解AMS、Activity的相关常识,比如AMS的基本常识和Activity的启动和销毁流程

Acitvity的生命周期,如何炸毁一个Activity?

问题正解:

注意事项:本节内容会涉及到AMS的内容,假设不了解主张先学习相关内容

Activity销毁的相关流程图

每日一题:Acitvity的生命周期,如何炸毁一个Activity?

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中,会判别是否要中止整个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;
       }

今日同享到此结束,对你有协助的话,点个赞再走呗,下期更精彩~

重视群众号:Android老皮
解锁 《Android十大板块文档》 ,让学习更贴近未来实战。已形成PDF版

内容如下

1.Android车载运用开发系统学习指南(附项目实战)
2.Android Framework学习指南,助力成为系统级开发高手
3.2023最新Android中高级面试题汇总+解析,离别零offer
4.企业级Android音视频开发学习道路+项目实战(附源码)
5.Android Jetpack从入门到知晓,构建高质量UI界面
6.Flutter技术解析与实战,跨渠道首要之选
7.Kotlin从入门到实战,全方面提高架构根底
8.高级Android插件化与组件化(含实战教程和源码)
9.Android 性能优化实战+360全方面性能调优
10.Android零根底入门到知晓,高手进阶之路

敲代码不易,重视一下吧。ღ( ・ᴗ・` )