Activity框架01-客户端事务管理
Tip
基于 android-14.0.0_r45
背景¶
Activity启动框架非常复杂,看了网上很多博客基本上都是用一篇文章讲完activity的启动流程。这样很多细节其实都没讲到,而且篇幅过长学习起来也很吃力。
在 Activity框架 系列文章中,我们将一点一点的拆分讲解跟 Activity启动有个的知识点。
那么我们先从一个最简单的 Activity客户端事务管理 讲起,为后续的Activity启动流程打下基础。
生命周期管理是google在Android 9才引入的设计,在Android 9之前,activity 存在生命周期的概念,但并无生命周期管理这一说法。
为了方便生命周期的切换以及相关业务的管理,google采用了事务的思想,将生命周期抽象为客户端事务的一部分来统一管理。
类图¶
下图是客户端事务管理完整的类图:
plantuml(点击展开详情)
mermaid
classDiagram
direction LR
class ActivityConfigurationChangeItem
class ActivityLifecycleItem
class ActivityRelaunchItem
class ActivityResultItem
class ActivityTransactionItem
class BaseClientRequest {
<<Interface>>
}
class ClientTransaction
class ClientTransactionItem
class ConfigurationChangeItem
class DestroyActivityItem
class EnterPipRequestedItem
class LaunchActivityItem
class MoveToDisplayItem
class NewIntentItem
class ObjectPoolItem {
<<Interface>>
}
class PauseActivityItem
class PipStateTransactionItem
class RefreshCallbackItem
class ResumeActivityItem
class StartActivityItem
class StopActivityItem
class TopResumedActivityChangeItem
class TransferSplashScreenViewStateItem
ActivityConfigurationChangeItem --> ActivityTransactionItem
ActivityLifecycleItem --> ActivityTransactionItem
ActivityRelaunchItem --> ActivityTransactionItem
ActivityResultItem --> ActivityTransactionItem
ActivityTransactionItem --> ClientTransactionItem
BaseClientRequest --> ObjectPoolItem
ClientTransaction ..> ObjectPoolItem
ClientTransactionItem ..> BaseClientRequest
ConfigurationChangeItem --> ClientTransactionItem
DestroyActivityItem --> ActivityLifecycleItem
EnterPipRequestedItem --> ActivityTransactionItem
LaunchActivityItem --> ClientTransactionItem
MoveToDisplayItem --> ActivityTransactionItem
NewIntentItem --> ActivityTransactionItem
PauseActivityItem --> ActivityLifecycleItem
PipStateTransactionItem --> ActivityTransactionItem
RefreshCallbackItem --> ActivityTransactionItem
ResumeActivityItem --> ActivityLifecycleItem
StartActivityItem --> ActivityLifecycleItem
StopActivityItem --> ActivityLifecycleItem
TopResumedActivityChangeItem --> ActivityTransactionItem
TransferSplashScreenViewStateItem --> ActivityTransactionItem
ActivityLifecycleItem类图¶
plantuml(点击展开详情)
mermaid
classDiagram
direction LR
class ActivityLifecycleItem {
+ int ON_CREATE
+ int ON_STOP
+ int ON_PAUSE
+ int PRE_ON_CREATE
+ int UNDEFINED
+ int ON_DESTROY
+ int ON_RESUME
+ int ON_RESTART
+ int ON_START
+ recycle() void
+ getTargetState() int
}
class ActivityTransactionItem {
+ execute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
~ getActivityClientRecord(ClientTransactionHandler, IBinder) ActivityClientRecord
}
class BaseClientRequest {
<<Interface>>
+ postExecute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
+ preExecute(ClientTransactionHandler, IBinder) void
+ execute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
}
class ClientTransaction {
- IApplicationThread mClient
- IBinder mActivityToken
- ActivityLifecycleItem mLifecycleStateRequest
+ Creator~ClientTransaction~ CREATOR
- List~ClientTransactionItem~ mActivityCallbacks
+ setLifecycleStateRequest(ActivityLifecycleItem) void
+ writeToParcel(Parcel, int) void
+ getLifecycleStateRequest() ActivityLifecycleItem
+ obtain(IApplicationThread, IBinder) ClientTransaction
+ dump(String, PrintWriter) void
+ getClient() IApplicationThread
+ addCallback(ClientTransactionItem) void
+ preExecute(ClientTransactionHandler) void
+ recycle() void
+ getCallbacks() List~ClientTransactionItem~
+ equals(Object) boolean
+ hashCode() int
+ schedule() void
+ getActivityToken() IBinder
+ describeContents() int
}
class ClientTransactionItem {
~ shouldHaveDefinedPreExecutionState() boolean
+ getPostExecutionState() int
+ describeContents() int
}
class DestroyActivityItem {
- boolean mFinished
- int mConfigChanges
+ Creator~DestroyActivityItem~ CREATOR
+ equals(Object) boolean
+ toString() String
+ recycle() void
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
+ obtain(boolean, int) DestroyActivityItem
+ hashCode() int
+ writeToParcel(Parcel, int) void
+ preExecute(ClientTransactionHandler, IBinder) void
+ getTargetState() int
}
class ObjectPoolItem {
<<Interface>>
+ recycle() void
}
class PauseActivityItem {
+ Creator~PauseActivityItem~ CREATOR
- String TAG
- boolean mFinished
- boolean mUserLeaving
- boolean mDontReport
- boolean mAutoEnteringPip
- int mConfigChanges
+ writeToParcel(Parcel, int) void
+ recycle() void
+ getTargetState() int
+ postExecute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
+ obtain(boolean, boolean, int, boolean, boolean) PauseActivityItem
+ equals(Object) boolean
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
+ hashCode() int
+ toString() String
+ obtain() PauseActivityItem
}
class ResumeActivityItem {
- boolean mUpdateProcState
- boolean mShouldSendCompatFakeFocus
- String TAG
- int mProcState
- boolean mIsForward
+ Creator~ResumeActivityItem~ CREATOR
+ obtain(int, boolean, boolean) ResumeActivityItem
+ toString() String
+ equals(Object) boolean
+ postExecute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
+ hashCode() int
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
+ getTargetState() int
+ obtain(boolean, boolean) ResumeActivityItem
+ preExecute(ClientTransactionHandler, IBinder) void
+ writeToParcel(Parcel, int) void
+ recycle() void
}
class StartActivityItem {
- String TAG
- ActivityOptions mActivityOptions
+ Creator~StartActivityItem~ CREATOR
+ recycle() void
+ equals(Object) boolean
+ writeToParcel(Parcel, int) void
+ obtain(ActivityOptions) StartActivityItem
+ toString() String
+ getTargetState() int
+ hashCode() int
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
}
class StopActivityItem {
- int mConfigChanges
+ Creator~StopActivityItem~ CREATOR
- String TAG
+ equals(Object) boolean
+ postExecute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
+ writeToParcel(Parcel, int) void
+ getTargetState() int
+ hashCode() int
+ toString() String
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
+ obtain(int) StopActivityItem
+ recycle() void
}
ActivityLifecycleItem --> ActivityTransactionItem
ActivityTransactionItem --> ClientTransactionItem
BaseClientRequest --> ObjectPoolItem
ClientTransaction ..> ObjectPoolItem
ClientTransactionItem ..> BaseClientRequest
DestroyActivityItem --> ActivityLifecycleItem
PauseActivityItem --> ActivityLifecycleItem
ResumeActivityItem --> ActivityLifecycleItem
StartActivityItem --> ActivityLifecycleItem
StopActivityItem --> ActivityLifecycleItem
ActivityTransactionItem类图¶
plantuml(点击展开详情)
mermaid
classDiagram
direction LR
class ActivityConfigurationChangeItem {
- Configuration mConfiguration
+ Creator~ActivityConfigurationChangeItem~ CREATOR
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
+ hashCode() int
+ toString() String
+ preExecute(ClientTransactionHandler, IBinder) void
+ writeToParcel(Parcel, int) void
+ equals(Object) boolean
+ obtain(Configuration) ActivityConfigurationChangeItem
+ recycle() void
}
class ActivityLifecycleItem {
+ int ON_CREATE
+ int ON_PAUSE
+ int ON_DESTROY
+ int ON_RESTART
+ int ON_STOP
+ int ON_START
+ int UNDEFINED
+ int PRE_ON_CREATE
+ int ON_RESUME
+ recycle() void
+ getTargetState() int
}
class ActivityRelaunchItem {
- int mConfigChanges
- List~ReferrerIntent~ mPendingNewIntents
- List~ResultInfo~ mPendingResults
- ActivityClientRecord mActivityClientRecord
- boolean mPreserveWindow
- String TAG
+ Creator~ActivityRelaunchItem~ CREATOR
- MergedConfiguration mConfig
+ writeToParcel(Parcel, int) void
+ equals(Object) boolean
+ recycle() void
+ postExecute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
+ obtain(List~ResultInfo~, List~ReferrerIntent~, int, MergedConfiguration, boolean) ActivityRelaunchItem
+ hashCode() int
+ preExecute(ClientTransactionHandler, IBinder) void
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
+ toString() String
}
class ActivityResultItem {
+ long CALL_ACTIVITY_RESULT_BEFORE_RESUME
- List~ResultInfo~ mResultInfoList
+ Creator~ActivityResultItem~ CREATOR
+ obtain(List~ResultInfo~) ActivityResultItem
+ writeToParcel(Parcel, int) void
+ equals(Object) boolean
+ toString() String
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
+ recycle() void
+ getPostExecutionState() int
+ hashCode() int
}
class ActivityTransactionItem {
+ execute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
~ getActivityClientRecord(ClientTransactionHandler, IBinder) ActivityClientRecord
}
class BaseClientRequest {
<<Interface>>
+ execute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
+ postExecute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
+ preExecute(ClientTransactionHandler, IBinder) void
}
class ClientTransaction {
- List~ClientTransactionItem~ mActivityCallbacks
- ActivityLifecycleItem mLifecycleStateRequest
- IBinder mActivityToken
- IApplicationThread mClient
+ Creator~ClientTransaction~ CREATOR
+ hashCode() int
+ obtain(IApplicationThread, IBinder) ClientTransaction
+ getLifecycleStateRequest() ActivityLifecycleItem
+ dump(String, PrintWriter) void
+ getActivityToken() IBinder
+ equals(Object) boolean
+ getCallbacks() List~ClientTransactionItem~
+ setLifecycleStateRequest(ActivityLifecycleItem) void
+ preExecute(ClientTransactionHandler) void
+ getClient() IApplicationThread
+ schedule() void
+ writeToParcel(Parcel, int) void
+ describeContents() int
+ recycle() void
+ addCallback(ClientTransactionItem) void
}
class ClientTransactionItem {
+ describeContents() int
~ shouldHaveDefinedPreExecutionState() boolean
+ getPostExecutionState() int
}
class EnterPipRequestedItem {
+ Creator~EnterPipRequestedItem~ CREATOR
+ obtain() EnterPipRequestedItem
+ recycle() void
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
+ equals(Object) boolean
+ toString() String
+ writeToParcel(Parcel, int) void
}
class MoveToDisplayItem {
- int mTargetDisplayId
- Configuration mConfiguration
+ Creator~MoveToDisplayItem~ CREATOR
+ preExecute(ClientTransactionHandler, IBinder) void
+ hashCode() int
+ toString() String
+ obtain(int, Configuration) MoveToDisplayItem
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
+ recycle() void
+ writeToParcel(Parcel, int) void
+ equals(Object) boolean
}
class NewIntentItem {
- List~ReferrerIntent~ mIntents
- boolean mResume
+ Creator~NewIntentItem~ CREATOR
+ obtain(List~ReferrerIntent~, boolean) NewIntentItem
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
+ hashCode() int
+ getPostExecutionState() int
+ writeToParcel(Parcel, int) void
+ toString() String
+ equals(Object) boolean
+ recycle() void
}
class ObjectPoolItem {
<<Interface>>
+ recycle() void
}
class PipStateTransactionItem {
+ Creator~PipStateTransactionItem~ CREATOR
- PictureInPictureUiState mPipState
+ obtain(PictureInPictureUiState) PipStateTransactionItem
+ recycle() void
+ toString() String
+ writeToParcel(Parcel, int) void
+ equals(Object) boolean
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
}
class RefreshCallbackItem {
+ Creator~RefreshCallbackItem~ CREATOR
- int mPostExecutionState
+ getPostExecutionState() int
+ writeToParcel(Parcel, int) void
~ shouldHaveDefinedPreExecutionState() boolean
+ recycle() void
+ toString() String
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
+ postExecute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
+ equals(Object) boolean
+ hashCode() int
+ obtain(int) RefreshCallbackItem
}
class TopResumedActivityChangeItem {
- boolean mOnTop
+ Creator~TopResumedActivityChangeItem~ CREATOR
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
+ postExecute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
+ toString() String
+ writeToParcel(Parcel, int) void
+ equals(Object) boolean
+ hashCode() int
+ obtain(boolean) TopResumedActivityChangeItem
+ recycle() void
}
class TransferSplashScreenViewStateItem {
- SplashScreenViewParcelable mSplashScreenViewParcelable
- SurfaceControl mStartingWindowLeash
+ Creator~TransferSplashScreenViewStateItem~ CREATOR
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
+ writeToParcel(Parcel, int) void
+ recycle() void
+ obtain(SplashScreenViewParcelable, SurfaceControl) TransferSplashScreenViewStateItem
}
ActivityConfigurationChangeItem --> ActivityTransactionItem
ActivityLifecycleItem --> ActivityTransactionItem
ActivityRelaunchItem --> ActivityTransactionItem
ActivityResultItem --> ActivityTransactionItem
ActivityTransactionItem --> ClientTransactionItem
BaseClientRequest --> ObjectPoolItem
ClientTransaction ..> ObjectPoolItem
ClientTransactionItem ..> BaseClientRequest
EnterPipRequestedItem --> ActivityTransactionItem
MoveToDisplayItem --> ActivityTransactionItem
NewIntentItem --> ActivityTransactionItem
PipStateTransactionItem --> ActivityTransactionItem
RefreshCallbackItem --> ActivityTransactionItem
TopResumedActivityChangeItem --> ActivityTransactionItem
TransferSplashScreenViewStateItem --> ActivityTransactionItem
ClientTransactionItem类图¶
plantuml(点击展开详情)
mermaid
classDiagram
direction LR
class ActivityTransactionItem {
+ execute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
~ getActivityClientRecord(ClientTransactionHandler, IBinder) ActivityClientRecord
+ execute(ClientTransactionHandler, ActivityClientRecord, PendingTransactionActions) void
}
class BaseClientRequest {
<<Interface>>
+ preExecute(ClientTransactionHandler, IBinder) void
+ execute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
+ postExecute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
}
class ClientTransaction {
- IBinder mActivityToken
- IApplicationThread mClient
+ Creator~ClientTransaction~ CREATOR
- List~ClientTransactionItem~ mActivityCallbacks
- ActivityLifecycleItem mLifecycleStateRequest
+ hashCode() int
+ preExecute(ClientTransactionHandler) void
+ getLifecycleStateRequest() ActivityLifecycleItem
+ obtain(IApplicationThread, IBinder) ClientTransaction
+ equals(Object) boolean
+ schedule() void
+ writeToParcel(Parcel, int) void
+ describeContents() int
+ addCallback(ClientTransactionItem) void
+ recycle() void
+ dump(String, PrintWriter) void
+ getCallbacks() List~ClientTransactionItem~
+ getActivityToken() IBinder
+ setLifecycleStateRequest(ActivityLifecycleItem) void
+ getClient() IApplicationThread
}
class ClientTransactionItem {
+ getPostExecutionState() int
+ describeContents() int
~ shouldHaveDefinedPreExecutionState() boolean
}
class ConfigurationChangeItem {
- Configuration mConfiguration
- int mDeviceId
+ Creator~ConfigurationChangeItem~ CREATOR
+ recycle() void
+ writeToParcel(Parcel, int) void
+ equals(Object) boolean
+ toString() String
+ preExecute(ClientTransactionHandler, IBinder) void
+ execute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
+ obtain(Configuration, int) ConfigurationChangeItem
+ hashCode() int
}
class LaunchActivityItem {
- Configuration mOverrideConfig
+ Creator~LaunchActivityItem~ CREATOR
- List~ResultInfo~ mPendingResults
- int mDeviceId
- Bundle mState
- ActivityOptions mActivityOptions
- boolean mIsForward
- IBinder mAssistToken
- String mReferrer
- IVoiceInteractor mVoiceInteractor
- Configuration mCurConfig
- int mIdent
- IBinder mTaskFragmentToken
- IBinder mShareableActivityToken
- boolean mLaunchedFromBubble
- IActivityClientController mActivityClientController
- ProfilerInfo mProfilerInfo
- Intent mIntent
- ActivityInfo mInfo
- PersistableBundle mPersistentState
- List~ReferrerIntent~ mPendingNewIntents
- int mProcState
- setValues(LaunchActivityItem, Intent, int, ActivityInfo, Configuration, Configuration, int, String, IVoiceInteractor, int, Bundle, PersistableBundle, List~ResultInfo~, List~ReferrerIntent~, ActivityOptions, boolean, ProfilerInfo, IBinder, IActivityClientController, IBinder, boolean, IBinder) void
+ equals(Object) boolean
+ execute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
- areBundlesEqualRoughly(BaseBundle, BaseBundle) boolean
+ hashCode() int
+ obtain(Intent, int, ActivityInfo, Configuration, Configuration, int, String, IVoiceInteractor, int, Bundle, PersistableBundle, List~ResultInfo~, List~ReferrerIntent~, ActivityOptions, boolean, ProfilerInfo, IBinder, IActivityClientController, IBinder, boolean, IBinder) LaunchActivityItem
+ writeToParcel(Parcel, int) void
- activityInfoEqual(ActivityInfo) boolean
+ recycle() void
+ toString() String
+ preExecute(ClientTransactionHandler, IBinder) void
- getRoughBundleHashCode(BaseBundle) int
+ postExecute(ClientTransactionHandler, IBinder, PendingTransactionActions) void
}
class ObjectPoolItem {
<<Interface>>
+ recycle() void
}
ActivityTransactionItem --> ClientTransactionItem
BaseClientRequest --> ObjectPoolItem
ClientTransaction ..> ObjectPoolItem
ClientTransactionItem ..> BaseClientRequest
ConfigurationChangeItem --> ClientTransactionItem
LaunchActivityItem --> ClientTransactionItem
小结¶
ActivityLifecycleItem¶
ActivityLifecycleItem 是一个抽象类,表示一个生命周期事件。它的子类用于具体的生命周期事件,例如 ResumeActivityItem、PauseActivityItem、StopActivityItem 等。
这个类的实例在 ClientTransaction 中被使用,用于描述某个 Activity 生命周期的变化。
ActivityTransactionItem¶
ActivityTransactionItem 是一个抽象类,表示一个 Activity 事务项。这类事务项可以涉及到 Activity 的启动、停止、重建、配置变化等操作。它是 ClientTransactionItem 的子类。
ClientTransactionItem¶
ClientTransactionItem 是一个抽象类,表示可以在客户端(应用进程)处理的事务项。它是 ClientTransaction 中的一个基本构件,具体的子类包括 ActivityLifecycleItem 和 ActivityTransactionItem。这个类定义了一些基本的方法来执行和处理事务。
ClientTransaction¶
ClientTransaction 是一个用于描述客户端(应用进程)事务的类。它包含了一系列 ClientTransactionItem,这些 ClientTransactionItem 描述了应用需要执行的一系列操作或生命周期变化。
ClientTransaction 类通过 Binder 传输到应用进程中的 ClientTransactionHandler 进行处理。
/**
* 一个包含一系列消息的容器,这些消息可能会发送到客户端。
* 包括一个回调列表和一个最终的生命周期状态。
*
* @see com.android.server.am.ClientLifecycleManager
* @see ClientTransactionItem
* @see ActivityLifecycleItem
* @hide
*/
public class ClientTransaction implements Parcelable, ObjectPoolItem {
/** 发送到客户端的单个回调列表。 */
@UnsupportedAppUsage
private List<ClientTransactionItem> mActivityCallbacks;
/**
* 事务执行后客户端活动应处于的最终生命周期状态。
*/
private ActivityLifecycleItem mLifecycleStateRequest;
/** 目标客户端。 */
private IApplicationThread mClient;
/** 目标客户端活动。如果整个事务目标是应用程序,可能为空。 */
private IBinder mActivityToken;
/**
* 获取事务的目标客户端。
* @return 目标客户端。
*/
public IApplicationThread getClient() {
return mClient;
}
/**
* 将消息添加到回调序列的末尾。
* @param activityCallback 可以包含生命周期请求/回调的单个消息。
*/
public void addCallback(ClientTransactionItem activityCallback) {
if (mActivityCallbacks == null) {
mActivityCallbacks = new ArrayList<>();
}
mActivityCallbacks.add(activityCallback);
}
/**
* 获取回调列表。
* @return 回调列表。
*/
@Nullable
@VisibleForTesting
@UnsupportedAppUsage
public List<ClientTransactionItem> getCallbacks() {
return mActivityCallbacks;
}
/**
* 获取目标活动。
* @return 目标活动标识符。
*/
@Nullable
@UnsupportedAppUsage
public IBinder getActivityToken() {
return mActivityToken;
}
/**
* 获取目标状态的生命周期请求。
* @return 生命周期状态请求。
*/
@VisibleForTesting
@UnsupportedAppUsage
public ActivityLifecycleItem getLifecycleStateRequest() {
return mLifecycleStateRequest;
}
/**
* 设置事务执行后客户端应处于的生命周期状态。
* @param stateRequest 用正确参数初始化的生命周期请求。
*/
public void setLifecycleStateRequest(ActivityLifecycleItem stateRequest) {
mLifecycleStateRequest = stateRequest;
}
/**
* 在事务调度到客户端时需要执行的操作。
* @param clientTransactionHandler 在客户端执行事务项请求的处理程序。
*/
public void preExecute(ClientTransactionHandler clientTransactionHandler) {
if (mActivityCallbacks != null) {
final int size = mActivityCallbacks.size();
for (int i = 0; i < size; ++i) {
mActivityCallbacks.get(i).preExecute(clientTransactionHandler, mActivityToken);
}
}
if (mLifecycleStateRequest != null) {
mLifecycleStateRequest.preExecute(clientTransactionHandler, mActivityToken);
}
}
/**
* 在初始化后调度事务。它将发送到客户端,所有的个别部分将按以下顺序应用:
* 1. 客户端调用 {@link #preExecute(ClientTransactionHandler)},触发在调度事务之前需要完成的所有工作。
* 2. 调度事务消息。
* 3. 客户端调用 {@link TransactionExecutor#execute(ClientTransaction)},执行所有回调和必要的生命周期转换。
* @throws RemoteException 如果事务无法调度。
*/
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
private ClientTransaction() {}
public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
// 从对象池中获取一个 ClientTransaction 实例
ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
// 如果对象池中没有可用的实例,则创建一个新的实例
if (instance == null) {
instance = new ClientTransaction();
}
// 初始化实例的属性
instance.mClient = client;
instance.mActivityToken = activityToken;
// 返回初始化后的实例
return instance;
}
}
这里稍微解释了 ClientTransaction 类的代码,通过 IApplicationThread 主要是把事务项列表发送到客户端。 看到这里可能会觉得云里雾里,我们直接找一个案例来分析。
代码案例¶
了解 Activity 启动的同学都知道,不管是热启动还是冷启动,最终都是通过 ActivityTaskSupervisor.realStartActivityLocked() 来启动 activity的。
public class ActivityTaskSupervisor implements RecentTasks.Callbacks {
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
...
// Create activity launch transaction.
final ClientTransaction clientTransaction = ClientTransaction.obtain(
proc.getThread(), r.token);
final boolean isTransitionForward = r.isTransitionForward();
final IBinder fragmentToken = r.getTaskFragment().getFragmentToken();
final int deviceId = getDeviceIdForDisplayId(r.getDisplayId());
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
// TODO: Have this take the merged configuration instead of separate global
// and override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), deviceId,
r.getFilteredReferrer(r.launchedFromPackage), task.voiceInteractor,
proc.getReportedProcState(), r.getSavedState(), r.getPersistentSavedState(),
results, newIntents, r.takeOptions(), isTransitionForward,
proc.createProfilerInfoIfNeeded(), r.assistToken, activityClientController,
r.shareableActivityToken, r.getLaunchedFromBubble(), fragmentToken));
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(isTransitionForward,
r.shouldSendCompatFakeFocus());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
...
}
}
- mService
是 ActivityTaskManagerService,而 ActivityTaskManagerService 的 getLifecycleManager() 函数返回的是 mLifecycleManager;也就是 ClientLifecycleManager
- proc.getThread()
这个是 ActivityThread.attach() 调用 ActivityManagerService.attachApplication() 一路传到 ProcessRecord 的成员变量 mThread 里。 所以这里拿到的其实就是客户端的 ApplicationThread 也就是 IApplicationThread.Stub。
-
LaunchActivityItem
-
ResumeActivityItem
ClientTransaction.obtain()¶
/**
* 一个包含一系列消息的容器,这些消息可能会发送到客户端。
* 包括一个回调列表和一个最终的生命周期状态。
*
* @see com.android.server.am.ClientLifecycleManager
* @see ClientTransactionItem
* @see ActivityLifecycleItem
* @hide
*/
public class ClientTransaction implements Parcelable, ObjectPoolItem {
/** 目标客户端。 */
private IApplicationThread mClient;
/** 目标客户端活动。如果整个事务目标是应用程序,可能为空。 */
private IBinder mActivityToken;
private ClientTransaction() {}
public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
// 从对象池中获取一个 ClientTransaction 实例
ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
// 如果对象池中没有可用的实例,则创建一个新的实例
if (instance == null) {
instance = new ClientTransaction();
}
// 初始化实例的属性
instance.mClient = client;
instance.mActivityToken = activityToken;
// 返回初始化后的实例
return instance;
}
}
这里的 mClient 就是客户端的 ApplicationThread 也就是 IApplicationThread.Stub。
mActivityToken 就是传进来的 r.token ,r 是 ActivityRecord,所以是 WindowToken 里的成员变量 token。
这个 r.token 我们后面会详细解释。
ClientTransaction.addCallback()¶
public class ClientTransaction implements Parcelable, ObjectPoolItem {
/** 发送到客户端的单个回调列表。 */
@UnsupportedAppUsage
private List<ClientTransactionItem> mActivityCallbacks;
/**
* 将消息添加到回调序列的末尾。
* @param activityCallback 可以包含生命周期请求/回调的单个消息。
*/
public void addCallback(ClientTransactionItem activityCallback) {
if (mActivityCallbacks == null) {
mActivityCallbacks = new ArrayList<>();
}
mActivityCallbacks.add(activityCallback);
}
}
ClientTransaction.setLifecycleStateRequest()¶
public class ClientTransaction implements Parcelable, ObjectPoolItem {
/**
* 事务执行后客户端活动应处于的最终生命周期状态。
*/
private ActivityLifecycleItem mLifecycleStateRequest;
/**
* 设置事务执行后客户端应处于的生命周期状态。
* @param stateRequest 用正确参数初始化的生命周期请求。
*/
public void setLifecycleStateRequest(ActivityLifecycleItem stateRequest) {
mLifecycleStateRequest = stateRequest;
}
}
ClientLifecycleManager.scheduleTransaction()¶
/**
* 能够合并多个客户端生命周期过渡请求和/或回调,并将它们作为单个事务执行的类。
*
* @see ClientTransaction
*/
class ClientLifecycleManager {
// TODO(lifecycler): 实现构建事务或全局事务。
// TODO(lifecycler): 使用对象池来管理事务和事务项。
/**
* 调度一个事务,该事务可能包含多个回调和一个生命周期请求。
* @param transaction 一系列客户端事务项。
* @throws RemoteException
*
* @see ClientTransaction
*/
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
// 获取目标客户端
final IApplicationThread client = transaction.getClient();
// 调度事务
transaction.schedule();
// 如果客户端不是 Binder 的实例,则表示这是一个远程调用
// 在此时可以安全地回收对象。所有用于本地调用的对象将在事务在
// ActivityThread 上的客户端执行后回收。
if (!(client instanceof Binder)) {
transaction.recycle();
}
}
}
ClientLifecycleManager 类用于处理客户端生命周期的多个过渡请求和/或回调,并将它们作为一个单独的事务执行。
通过 transaction.getClient() 就获取到客户端的 ApplicationThread 也就是 IApplicationThread.Stub。
ClientTransaction.schedule()¶
public class ClientTransaction implements Parcelable, ObjectPoolItem {
/**
* 在事务初始化后调度事务。它将被发送到客户端,所有的部分将按以下顺序应用:
* 1. 客户端调用 {@link #preExecute(ClientTransactionHandler)},这将触发在实际调度事务之前需要完成的所有工作。
* 2. 事务消息被调度。
* 3. 客户端调用 {@link TransactionExecutor#execute(ClientTransaction)},执行所有回调和必要的生命周期转换。
*/
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
}
这里的 mClient 就是 ApplicationThread。
这里还是 system_server 进程
ApplicationThread.scheduleTransaction()¶
public final class ActivityThread extends ClientTransactionHandler
implements ActivityThreadInternal {
private class ApplicationThread extends IApplicationThread.Stub {
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
}
}
需要注意的是,这里走到了 APP 进程。
ClientTransactionHandler.scheduleTransaction()¶
public abstract class ClientTransactionHandler {
/** Prepare and schedule transaction for execution. */
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
}
这里主线任务是跟 handler 发送一条 EXECUTE_TRANSACTION 信息。 在这之前要先执行 item 的 preExecute() 函数。
ClientTransaction.preExecute()¶
public class ClientTransaction implements Parcelable, ObjectPoolItem {
/**
* 在事务调度到客户端时需要执行的操作。
* @param clientTransactionHandler 在客户端执行事务项请求的处理程序。
*/
public void preExecute(ClientTransactionHandler clientTransactionHandler) {
if (mActivityCallbacks != null) {
final int size = mActivityCallbacks.size();
for (int i = 0; i < size; ++i) {
mActivityCallbacks.get(i).preExecute(clientTransactionHandler, mActivityToken);
}
}
if (mLifecycleStateRequest != null) {
mLifecycleStateRequest.preExecute(clientTransactionHandler, mActivityToken);
}
}
}
在我们这里案例中,mActivityCallbacks 是 LaunchActivityItem ;mLifecycleStateRequest 是 ResumeActivityItem。
所以这里是先后调到了 LaunchActivityItem.preExecute() 和 ResumeActivityItem.preExecute()。
这里只是支线任务,我们不深入分析。
handleMessage(EXECUTE_TRANSACTION)¶
public final class ActivityThread extends ClientTransactionHandler
implements ActivityThreadInternal {
private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
class H extends Handler {
public static final int EXECUTE_TRANSACTION = 159;
public void handleMessage(Message msg) {
switch (msg.what) {
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
if (isSystem()) {
// Client transactions inside system process are recycled on the client side
// instead of ClientLifecycleManager to avoid being cleared before this
// message is handled.
transaction.recycle();
}
// TODO(lifecycler): Recycle locally scheduled transactions.
break;
}
}
}
}
这里的 mTransactionExecutor 就是 TransactionExecutor。
public final class ActivityThread extends ClientTransactionHandler
implements ActivityThreadInternal {
private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
}
ActivityThread 继承抽象类 ClientTransactionHandler,我们再接着看 TransactionExecutor 构造函数。
TransactionExecutor构造函数¶
public class TransactionExecutor {
private ClientTransactionHandler mTransactionHandler;
public TransactionExecutor(ClientTransactionHandler clientTransactionHandler) {
mTransactionHandler = clientTransactionHandler;
}
}
mTransactionHandler 其实就是 ActivityThread。
TransactionExecutor.execute()¶
/**
* 该类负责以正确的顺序管理事务执行。
*/
public class TransactionExecutor {
/**
* 解析事务。
* 首先,所有回调将按它们在列表中出现的顺序执行。如果回调需要某个前置或后置执行状态,
* 则客户端将相应地进行过渡。然后,客户端将循环到最终的生命周期状态(如果有提供)。
* 否则,它将保持在初始状态或回调所需的最后状态。
*/
public void execute(ClientTransaction transaction) {
...
// 执行回调
executeCallbacks(transaction);
// 执行生命周期状态
executeLifecycleState(transaction);
...
}
}
TransactionExecutor.executeCallbacks()¶
public class TransactionExecutor {
/**
* 遍历所有由回调请求的状态,并在适当的时间执行它们。
*/
@VisibleForTesting
public void executeCallbacks(ClientTransaction transaction) {
// 获取事务中的所有回调
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
if (callbacks == null || callbacks.isEmpty()) {
// 如果没有回调,提前返回
return;
}
// 如果启用了调试日志,记录解析回调的日志
if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Resolving callbacks in transaction");
// 获取事务的 Activity token
final IBinder token = transaction.getActivityToken();
// 获取对应的 ActivityClientRecord
ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
// 获取事务中请求的最终状态
final ActivityLifecycleItem finalStateRequest = transaction.getLifecycleStateRequest();
final int finalState = finalStateRequest != null ? finalStateRequest.getTargetState()
: UNDEFINED;
// 获取最后一个请求了某种后置执行状态的回调的索引
final int lastCallbackRequestingState = lastCallbackRequestingState(transaction);
// 获取回调的数量
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Resolving callback: " + item);
final int postExecutionState = item.getPostExecutionState();
// 如果回调需要定义的前置执行状态
if (item.shouldHaveDefinedPreExecutionState()) {
final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
item.getPostExecutionState());
if (closestPreExecutionState != UNDEFINED) {
cycleToPath(r, closestPreExecutionState, transaction);
}
}
// 执行回调
item.execute(mTransactionHandler, token, mPendingActions);
// 执行回调后的操作
item.postExecute(mTransactionHandler, token, mPendingActions);
if (r == null) {
// 启动活动请求将创建一个活动记录
r = mTransactionHandler.getActivityClient(token);
}
// 如果回调有后置执行状态且活动记录不为空
if (postExecutionState != UNDEFINED && r != null) {
// 跳过最后一个过渡,并通过显式状态请求执行它
final boolean shouldExcludeLastTransition =
i == lastCallbackRequestingState && finalState == postExecutionState;
cycleToPath(r, postExecutionState, shouldExcludeLastTransition, transaction);
}
}
}
}
closestPreExecutionState 和 postExecutionState 都是 UNDEFINED,所以我们只关心高亮的代码部分,也就是 item.execute() 和 item.postExecute() 。
这里主线任务是调用 item 的 execute(),支线任务是调用 item 的 postExecute() 。
item 是 LaunchActivityItem。
LaunchActivityItem.execute()¶
public class LaunchActivityItem extends ClientTransactionItem {
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mActivityOptions, mIsForward, mProfilerInfo,
client, mAssistToken, mShareableActivityToken, mLaunchedFromBubble,
mTaskFragmentToken);
client.handleLaunchActivity(r, pendingActions, mDeviceId, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
}
这里的 client 就是 TransactionExecutor 构造函数拿到的 ActivityThread。
所以这里最终调到了 ActivityThread.handleLaunchActivity(),走 Activity 的 onCreate() 生命周期。
LaunchActivityItem.postExecute()¶
public class LaunchActivityItem extends ClientTransactionItem {
@Override
public void postExecute(@NonNull ClientTransactionHandler client,
@NonNull PendingTransactionActions pendingActions) {
client.countLaunchingActivities(-1);
}
}
计数-1
到这里执行完第一个 item 了,我们回到 TransactionExecutor.executeTransactionItems() 中继续for循环。
TransactionExecutor.executeLifecycleState()¶
当前案例中,ActivityLifecycleItem 是 ResumeActivityItem 。
public class TransactionExecutor {
/**
* 如果事务请求了最终状态,转换到该最终状态。
*/
private void executeLifecycleState(ClientTransaction transaction) {
// 获取事务中请求的生命周期状态
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
if (lifecycleItem == null) {
// 如果没有生命周期请求,提前返回
return;
}
// 获取事务的 Activity token
final IBinder token = transaction.getActivityToken();
// 获取对应的 ActivityClientRecord
final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
// 如果启用了调试日志,记录解析生命周期状态的日志
if (DEBUG_RESOLVER) {
Slog.d(TAG, tId(transaction) + "Resolving lifecycle state: "
+ lifecycleItem + " for activity: "
+ getShortActivityName(token, mTransactionHandler));
}
if (r == null) {
// 如果客户端记录不存在,忽略请求
return;
}
// 转换到最终请求状态之前的状态
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
// 使用正确的参数执行最终的过渡
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
}
这里跟 TransactionExecutor.executeLifecycleState() 思路差不多,主线任务是调用 item 的 execute(),支线任务是调用 item 的 postExecute() 。
但在这之前调用了 cycleToPath() ,这点很有意思哈。
刚才 LaunchActivityItem 只是走 Activity 的 onCreate() 生命周期。 而这里 ResumeActivityItem 从字面意思显然是要执行 Activity 的 onResume() 生命周期。但这两者之间还缺少了一个生命周期 onStart()。
所以 cycleToPath() 的作用就是计算 Activity 的生命周期路径,如果要走的路径跟现在的路径中间还有,则先补齐。
简单点,onCreate 是第一步,onStart 是第二步,onResume 是第三步;现在只走到了第一步,要走到第三步,必现先走到第二步,才能从第二步走到第三步。
TransactionExecutor.cycleToPath()¶
public class TransactionExecutor {
/**
* 在状态之间转换客户端,并且可以选择不执行序列中的最后一步。
* 这是在解析生命周期状态请求时使用的,当最后一步需要用一些特定的参数执行时。
*
* @param r 当前的 ActivityClientRecord 实例。
* @param finish 最终状态。
* @param excludeLastState 是否排除最后的状态。
* @param transaction 当前的 ClientTransaction 实例。
*/
private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
ClientTransaction transaction) {
// 获取当前的生命周期状态
final int start = r.getLifecycleState();
...
// 获取从 start 到 finish 的生命周期路径,可能会排除最后的状态
final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
// 执行生命周期序列
performLifecycleSequence(r, path, transaction);
}
}
回到刚才调用这个函数的地方:
- r
就是 ActivityThread 里的 ActivityClientRecord,
- lifecycleItem.getTargetState()
因为 lifecycleItem 是 ResumeActivityItem,使用返回的就是 ON_RESUME,也就是3。 所以传给 cycleToPath() 函数的 finish = 3
回到 cycleToPath() 函数里,我们继续分析 start 和 path 是怎么得到的。
ActivityClientRecord.getLifecycleState()¶
public final class ActivityThread extends ClientTransactionHandler
implements ActivityThreadInternal {
public static final class ActivityClientRecord {
public int getLifecycleState() {
return mLifecycleState;
}
public void setState(@LifecycleState int newLifecycleState) {
mLifecycleState = newLifecycleState;
}
}
}
在 onCeate() 流程中设置了状态。
public final class ActivityThread extends ClientTransactionHandler
implements ActivityThreadInternal {
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...
r.setState(ON_CREATE);
...
}
}
所以 cycleToPath() 函数里 start 就是 ON_CREATE,也就是1
TransactionExecutorHelper.getLifecyclePath()¶
public class TransactionExecutorHelper {
/**
* 计算活动在主要生命周期状态之间的路径,并用值填充 {@link #mLifecycleSequence},这些值从初始状态后的状态开始。
* <p>注意:返回值在此类中内部使用,并不是副本。在调用此类的其他方法后,其内容可能会改变。</p>
*
* @param start 初始状态。
* @param finish 最终状态。
* @param excludeLastState 是否排除最后的状态。
* @return 包含生命周期路径的 IntArray。
* @throws IllegalArgumentException 如果状态是未定义的或非法的,则抛出此异常。
*/
@VisibleForTesting
public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
// 如果初始状态或最终状态是未定义的,抛出异常。
if (start == UNDEFINED || finish == UNDEFINED) {
throw new IllegalArgumentException("Can't resolve lifecycle path for undefined state");
}
// 如果状态是 ON_RESTART,抛出异常。
if (start == ON_RESTART || finish == ON_RESTART) {
throw new IllegalArgumentException("Can't start or finish in intermittent RESTART state");
}
// 如果最终状态是 PRE_ON_CREATE 且初始状态不等于最终状态,抛出异常。
if (finish == PRE_ON_CREATE && start != finish) {
throw new IllegalArgumentException("Can only start in pre-onCreate state");
}
// 清空生命周期序列
mLifecycleSequence.clear();
// 如果最终状态大于等于初始状态
if (finish >= start) {
// 特殊情况:从 ON_START 到 ON_STOP,不需要经过 ON_RESUME 和 ON_PAUSE 状态。
if (start == ON_START && finish == ON_STOP) {
mLifecycleSequence.add(ON_STOP);
} else {
// 正常情况下,依次添加状态。
for (int i = start + 1; i <= finish; i++) {
mLifecycleSequence.add(i);
}
}
} else { // 如果最终状态小于初始状态,不能简单地逆序循环
// 特殊情况:从 ON_PAUSE 到 ON_RESUME,直接跳到 ON_RESUME。
if (start == ON_PAUSE && finish == ON_RESUME) {
mLifecycleSequence.add(ON_RESUME);
} else if (start <= ON_STOP && finish >= ON_START) {
// 重新启动并转到所需状态。
// 首先进入停止状态。
for (int i = start + 1; i <= ON_STOP; i++) {
mLifecycleSequence.add(i);
}
// 重启
mLifecycleSequence.add(ON_RESTART);
// 转到所需状态
for (int i = ON_START; i <= finish; i++) {
mLifecycleSequence.add(i);
}
} else {
// 重新启动并转到所需状态。
// 首先进入销毁状态。
for (int i = start + 1; i <= ON_DESTROY; i++) {
mLifecycleSequence.add(i);
}
// 转到所需状态
for (int i = ON_CREATE; i <= finish; i++) {
mLifecycleSequence.add(i);
}
}
}
// 如果需要排除最后的状态转换,并且生命周期序列不为空,移除最后一个状态。
if (excludeLastState && mLifecycleSequence.size() != 0) {
mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
}
return mLifecycleSequence;
}
}
经过前面的分析,我们知道 start = 1 和 finish = 3 。 所以 mLifecycleSequence 添加了 2 和 3,请注意看代码高亮部分。
TransactionExecutor.performLifecycleSequence()¶
public class TransactionExecutor {
/**
* 通过预先初始化的状态序列来转换客户端。
*
* @param r 表示活动的 ActivityClientRecord 对象
* @param path 表示生命周期路径的 IntArray 对象
* @param transaction 表示当前事务的 ClientTransaction 对象
*/
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,
Context.DEVICE_ID_INVALID, null /* customIntent */);
break;
case ON_START:
mTransactionHandler.handleStartActivity(r, mPendingActions,
null /* activityOptions */);
break;
case ON_RESUME:
mTransactionHandler.handleResumeActivity(r, false /* finalStateRequest */,
r.isForward, false /* shouldSendCompatFakeFocus */,
"LIFECYCLER_RESUME_ACTIVITY");
break;
case ON_PAUSE:
mTransactionHandler.handlePauseActivity(r, false /* finished */,
false /* userLeaving */, 0 /* configChanges */,
false /* autoEnteringPip */, mPendingActions,
"LIFECYCLER_PAUSE_ACTIVITY");
break;
case ON_STOP:
mTransactionHandler.handleStopActivity(r, 0 /* configChanges */,
mPendingActions, false /* finalStateRequest */,
"LIFECYCLER_STOP_ACTIVITY");
break;
case ON_DESTROY:
mTransactionHandler.handleDestroyActivity(r, false /* finishing */,
0 /* configChanges */, false /* getNonConfigInstance */,
"performLifecycleSequence. cycling to:" + path.get(size - 1));
break;
case ON_RESTART:
mTransactionHandler.performRestartActivity(r, false /* start */);
break;
default:
throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
}
}
}
}
由前面可知,path有两个元素,值分别为2和3,也就是 ON_START 和 ON_RESUME。
-
ON_START
调的是 ClientTransactionHandler.handleStartActivity(),最终调到了 ActivityThread.handleStartActivity(),走 Activity 的 onStart() 生命周期。
-
ON_RESUME
调的是 ClientTransactionHandler.handleResumeActivity(),最终调到了 ActivityThread.handleResumeActivity(),走 Activity 的 onResume() 生命周期。
到这里 TransactionExecutor.cycleToPath() 的使命完成了,继续回到调用其地方,也就是 TransactionExecutor.executeLifecycleState()。
ResumeActivityItem.execute()¶
TransactionExecutor.executeLifecycleState() 调用 TransactionExecutor.cycleToPath() 之后,接着调用
lifecycleItem.execute(mTransactionHandler, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, mPendingActions);
执行接下来的操作。
前面我们提到过 lifecycleItem 就是 ResumeActivityItem,所以先看 ResumeActivityItem.execute() 都干了什么。
@Override
public void execute(@NonNull ClientTransactionHandler client, @NonNull ActivityClientRecord r,
@NonNull PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
client.handleResumeActivity(r, true /* finalStateRequest */, mIsForward,
mShouldSendCompatFakeFocus, "RESUME_ACTIVITY");
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
所以这里最终调到了 ActivityThread.handleResumeActivity(),走 Activity 的 onResume() 生命周期。
Warning
前面执行 cycleToPath() 时已经走了走 Activity 的 onResume() 生命周期,这里再走一次不是重复了吗?
其实不然,在 ActivityThread.handleResumeActivity() 中会判断是否已经执行过了,如果是就不再执行。
ResumeActivityItem.postExecute()¶
@Override
public void postExecute(@NonNull ClientTransactionHandler client,
@NonNull PendingTransactionActions pendingActions) {
// TODO(lifecycler): Use interface callback instead of actual implementation.
ActivityClient.getInstance().activityResumed(getActivityToken(),
client.isHandleSplashScreenExit(getActivityToken()));
}
到这里基本上就知道了 system_server 是如何通过 server transaction 来启动 Activity 的各种生命周期的。
总结¶
今后只要看到在 system_server 要通过 server transaction 来执行这些 item,可以不用一点点跟进其调用流程,直接跳转到 ActivityThread对应的 Handle方法 和 Perform方法 。
关于执行 Activity 生命周期的相关 item 如下:
Lifecycle | Item | Handle方法 | Perform方法 |
---|---|---|---|
ON_CREATE | LaunchActivityItem | handleLaunchActivity | performLaunchActivity |
ON_START | StartActivityItem | handleStartActivity | 无 |
ON_RESUME | ResumeActivityItem | handleResumeActivity | performResumeActivity |
ON_PAUSE | PauseActivityItem | handlePauseActivity | performPauseActivity |
ON_STOP | StopActivityItem | handleStopActivity | performStopActivityInner |
ON_DESTROY | DestroyActivityItem | handleDestroyActivity | performDestroyActivity |