framework之Activity 生命周期解析(基于Android11源码)
Posted 一代小强
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了framework之Activity 生命周期解析(基于Android11源码)相关的知识,希望对你有一定的参考价值。
引言
上一篇讲了Activity的创建过程(没看过的小伙伴移步 点我前往)。由于篇幅的问题,只分析到OnCreate周期,那这一篇就接着讲余下部分的周期。
在高版本上,activity的周期都是以事务的方式调用,activityThread里面H类的EXECUTE_TRANSACTION
消息正是接收、处理事务的入口,实际最终由TransactionExecutor 处理该事务。(PS:ATMS即ActivityTaskManagerService的简写)
public final class ActivityThread extends ClientTransactionHandler
private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
class H extends Handler
public void handleMessage(Message msg)
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
if (isSystem())
transaction.recycle();
.....
我们来看看整个activity启动过程会走哪些周期,请记住下面的周期和顺序,接下来就会讲讲这些周期是如何调用的
06-20 13:58:04.476 17073 17073 D MainActivity: onCreate:
06-20 13:58:04.481 17073 17073 D MainActivity: onStart:
06-20 13:58:04.483 17073 17073 D MainActivity: onPostCreate:
06-20 13:58:04.483 17073 17073 D MainActivity: onResume:
06-20 13:58:04.494 17073 17073 D MainActivity: onPostResume:
06-20 13:58:08.690 17073 17073 D MainActivity: onPause:
06-20 13:58:10.207 17073 17073 D MainActivity: onStop:
06-20 13:58:10.210 17073 17073 D MainActivity: onDestroy:
1、onCreate
framework之Activity启动流程,里面已经很详细描述了onCreate的调用流程,对应的流程如下
简单来讲,通过LaunchActivityItem调用了ActivityThread的handleLaunchActivity方法。ActivityThread在创建activity实例后,会设置config、window、resource、theme相关资源,在调用activity的attach方法后,会接着调用onCreate方法。
2、onStart
onCreate之后,onStart又是如何调用的呢?这里我们回顾一下TransactionExecutor#execute方法
// 以正确顺序管理事务执行的类。
public class TransactionExecutor
....
// 处理服务端传递过来的事务
public void execute(ClientTransaction transaction)
....
// 该方法中通过遍历 transaction#callbacks 获取到LaunchActivityItem,然后调用onCreate方法
executeCallbacks(transaction);
executeLifecycleState(transaction);
不知读者发现没有,executeLifecycleState方法还没分析过,很好,续杯 executeLifecycleState!
public class TransactionExecutor
// 将请求的事务转为最终的生命周期
private void executeLifecycleState(ClientTransaction transaction)
....
final IBinder token = transaction.getActivityToken();
// 通过token获取到对应的activityRecord
final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
// 循环到最终请求状态之前的状态。
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
// 使用适当的参数执行最终转换。
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
看看cycleToPath方法,这里在拿到lifeCyclePath后就交给了performLifecycleSequence
// 循环到最终请求状态之前的状态。
private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
ClientTransaction transaction)
final int start = r.getLifecycleState();
// 计算活动的主要生命周期状态的路径,并使用从初始状态之后的状态开始的值填充
// 比如onStart,onStop周期就是在这里额外加入的
final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
performLifecycleSequence(r, path, transaction);
我们来到了performLifecycleSequence 方法,看起来是处理全部周期的地方,问题来了,我们怎么知道走到哪个case?
public class TransactionExecutor
private PendingTransactionActions mPendingActions = new PendingTransactionActions();
private ClientTransactionHandler mTransactionHandler;
...
// 通过之前的序列状态过渡为客户端的状态
private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
ClientTransaction transaction)
final int size = path.size();
for (int i = 0, state; i < size; i++)
state = path.get(i);
switch (state)
case ON_CREATE:
mTransactionHandler.handleLaunchActivity(r, mPendingActions,
null /* customIntent */);
break;
case ON_START:
mTransactionHandler.handleStartActivity(r.token, 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, 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;
....
public abstract class ActivityLifecycleItem extends ClientTransactionItem
....
public static final int ON_CREATE = 1;
public static final int ON_START = 2;
public static final int ON_RESUME = 3;
public static final int ON_PAUSE = 4;
public static final int ON_STOP = 5;
public static final int ON_DESTROY = 6;
public static final int ON_RESTART = 7;
通过debug发现,path的size是1,mValues的第一个值是2,即state为2,显然走到ON_START case,调用mTransactionHandler#handleStartActivity方法。
ClientTransactionHandler其实是一个抽象类,ActivityThread才是具体实现类
public final class ActivityThread extends ClientTransactionHandler
@Override
public void handleStartActivity(IBinder token, PendingTransactionActions pendingActions)
final ActivityClientRecord r = mActivities.get(token);
final Activity activity = r.activity;
// Start,即调用start周期
activity.performStart("handleStartActivity");
// 更新当前的状态
r.setState(ON_START);
// 恢复实例的状态,即OnRestoreInstanceState周期
if (pendingActions.shouldRestoreInstanceState())
if (r.isPersistable())
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
r.persistentState);
else if (r.state != null)
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
// 调用 postOnCreate() 周期
if (pendingActions.shouldCallOnPostCreate())
if (r.isPersistable())
mInstrumentation.callActivityOnPostCreate(activity, r.state,
r.persistentState);
else
mInstrumentation.callActivityOnPostCreate(activity, r.state);
// 将activity设置为可见
updateVisibility(r, true /* show */);
// 设置activity的可见状态
private void updateVisibility(ActivityClientRecord r, boolean show)
View v = r.activity.mDecor;
if (v != null)
if (show)
if (r.newConfig != null)
// 回调onConfigurationChanged方法
performConfigurationChangedForActivity(r, r.newConfig);
r.newConfig = null;
....
从上面可以看到,handleStartActivity 方法主要调用onStart
、OnRestoreInstanceState
和 postOnCreate
周期。并在最后将activity设置为可见
public class Activity extends ContextThemeWrapper ....
// start 周期的入口
final void performStart(String reason)
// 将onStart周期开始事件分发给监听器ActivityLifecycleCallbacks
dispatchActivityPreStarted();
// 将onStart的逻辑交给mInstrumentation
mInstrumentation.callActivityOnStart(this);
// 将周期分发给fragment
mFragments.dispatchStart();
...
// 将onSart周期结束事件分发给监听器ActivityLifecycleCallbacks
dispatchActivityPostStarted();
Instrumentation 也只是调用activity的onStart方法,这样做的好处是,可以将周期调用的时机暴露出去。
public class Instrumentation
public void callActivityOnStart(Activity activity)
activity.onStart();
onRestart
至于onRestart周期,这里也贴一下对应的path值
其实就是在onStart的前面插入了onStart 下标值,对应的case调用的是performRestartActivity方法
public final class ActivityThread extends ClientTransactionHandler
@Override
public void performRestartActivity(IBinder token, boolean start)
ActivityClientRecord r = mActivities.get(token);
if (r.stopped)
r.activity.performRestart(start, "performRestartActivity");
if (start)
r.setState(ON_START);
Activity对应的方法是
public class Activity extends ContextThemeWrapper ....
final void performRestart(boolean start, String reason)
....
// 直接调用onRestart周期
mInstrumentation.callActivityOnRestart(this);
3、onResume
通过分析onStart周期调用,估计有些同学很快就会想到onResume也是在performLifecycleSequence方法中处理的。因为里面也有ON_RESUME的case。这么想就 大错特错了!!!
上面有debug出path的size是1,所以在处理onStart周期后,就会退出循环。那onResume是在哪里调用的呢?
我们回到executeLifecycleState方法,方法最后调用了lifecycleItem.execute。
public class TransactionExecutor
// 将请求的事务转为最终的生命周期
private void executeLifecycleState(ClientTransaction transaction)
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
....
final IBinder token = transaction.getActivityToken();
// 通过token获取到对应的activityRecord
final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
// 循环到最终请求状态之前的状态。
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
// 使用适当的参数执行最终转换。
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
// 通知ActivityTaskManager
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
而ActivityLifecycleItem是一个抽象类,那就再次debug看看lifecycleItem是哪个具体类吧
lifecycleItem是ResumeActivityItem的实例。
public class ResumeActivityItem extends ActivityLifecycleItem
.....
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions)
// 调用了ActivityThread的handleResumeActivity
client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
"RESUME_ACTIVITY");
@Override
public void postExecute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions)
try
// 通知ATMS 当前完成onResume
ActivityTaskManager.getService().activityResumed(token);
catch (RemoteException ex)
throw ex.rethrowFromSystemServer();
很好,又回到了ActivityThread(这家伙出镜率相当高)
public final class ActivityThread extends ClientTransactionHandler
@Override
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
String reason)
// 准备调用Resume周期
final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
....
handleResumeActivity 方法里面调用了performResumeActivity
public final class ActivityThread extends ClientTransactionHandler
public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
String reason)
final ActivityClientRecord r = mActivities.get(token);
....
try
// 调用activity的performResume
r.activity.performResume(r.startsNotResumed, reason);
....
catch (Exception e)
....
最后来到了activity的performResume,调用activity的onResume
public class Activity extends ContextThemeWrapper ....
final void performResume(boolean followedByPause, String reason)
// 将onResume开始事件分发给监听器ActivityLifecycleCallbacks
dispatchActivityPreResumed();
// 调用Activity的onResume方法
mInstrumentation.callActivityOnResume(this);
// 将OnResume周期分发给fragment
mFragments.dispatchResume();
// 调用onPostResume 周期
onPostResume();
// 将onResume结束的事件分发给监听器ActivityLifecycleCallbacks
dispatchActivityPostResumed();
4、中场小结
经过上面的分析,想必大家对activity周期调用链路有了一定的了解(绕晕了 doge),其中最重要的地方是这里
public class TransactionExecutor
// 是负责activity周期调用的总入口,处理ATMS 的周期事务请求,其中transaction 是ATMS传过来的参数
public void execute(ClientTransaction transaction)
final IBinder token = transaction.getActivityToken();
if (token != null)
// 处理activity onDestory的情况
final Map<IBinder, ClientTransactionItem> activitiesToBeDestroyed =
mTransactionHandler.getActivitiesToBeDestroyed();
final ClientTransactionItem destroyItem = activitiesToBeDestroyed.get(token);
if <以上是关于framework之Activity 生命周期解析(基于Android11源码)的主要内容,如果未能解决你的问题,请参考以下文章
framework之Activity 生命周期解析(基于Android11源码)