在Android最新版本中,对于Activity的生命周期采用了事物控制来做处理
根据Activity生命周期对应生命周期事物
- LaunchActivityItem
- ResumeActivityItem
- PauseActivityItem
- StopActivityItem
- DestroyActivityItem
从类图中可以看出所有生命周期都是继承抽象出来的基类ClientTransactionItem。
// Create activity launch transaction.
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
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(), r.compat,
r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
r.persistentState, results, newIntents, mService.isNextTransitionForward(),
profilerInfo));
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
创建一个ClientTransaction,并将LaunchActivityItem作为callback添加到mActivityCallbacks,而ResumeActivityItem或者PauseActivityItem作为LifecycleStateRequesst传递给mLifecycleStateRequest。最后通过ClientLifecycleManager执行该事务。
//先看ClientTransaction.java
public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
if (instance == null) {
instance = new ClientTransaction();
}
instance.mClient = client;
instance.mActivityToken = activityToken;
return instance;
}
public void addCallback(ClientTransactionItem activityCallback) {
if (mActivityCallbacks == null) {
mActivityCallbacks = new ArrayList<>();
}
mActivityCallbacks.add(activityCallback);
}
public void setLifecycleStateRequest(ActivityLifecycleItem stateRequest) {
mLifecycleStateRequest = stateRequest;
}
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
obtain传入的参数IApplicationThread,是一个Binder的存根对象。实现它的ActivityThread的内部类,通过其可以实现跨进程的调用。
ClientLifecycleManager.java
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule();
if (!(client instanceof Binder)) {
// If client is not an instance of Binder - it's a remote call and at this point it is
// safe to recycle the object. All objects used for local calls will be recycled after
// the transaction is executed on client in ActivityThread.
transaction.recycle();
}
}
ClientLifecycleManager的执行也是通过ClientTransaction去执行,最终通过IApplicationThread实现到APP端。ApplicationThread是一个本地Binder对象。到了AMS中这个接口就象征着远程代理对象。换句话说,此时会调用App端的scheduleTransaction方法。
public final class ActivityThread extends ClientTransactionHandler {
private class ApplicationThread extends IApplicationThread.Stub {
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
class H extends Handler {
public void handleMessage(Message msg) {
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
if (isSystem()) {
transaction.recycle();
}
break;
}
}
}
public abstract class ClientTransactionHandler {
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
}
从上面节选代码分析:ApplicationThread.scheduleTransaction——> ClientTransactionHandler.scheduleTransaction——> SendMessage到ActivityThread.H——> ActivityThread.H.handleMessage
在handleMessage中调用了TransactionExecutor.execute:
TransactionExecutor.java
public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
executeCallbacks(transaction);//处理传递过来的ClientTransaction中的callback
executeLifecycleState(transaction);//处理ClientTransaction中的LifecycleStateRequest
mPendingActions.clear();
}
/** Cycle through all states requested by callbacks and execute them at proper times. */
@VisibleForTesting
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
if (callbacks == null) {
// No callbacks to execute, return early.
return;
}
log("Resolving callbacks");
final IBinder token = transaction.getActivityToken();
ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
......
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
......
}
}
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
final IBinder token = transaction.getActivityToken();
final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
// Execute the final transition with proper parameters.
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
按照上面处理顺序,对应之前添加到clientTransaction:先处理LaunchActivityItem然后处理ResumeActivityItem。
从TransactionExecutor.executeCallbacks与executeLifecycleState可以看出都将会分两步执行Item的execute与postExecute。
OnCreate
在LaunchActivityItem.execute中创建与AMS中ActivityRecord对应的APP端的ActivityClientRecord对象,并通过AppThread.handleLaunchActivity——> performLaunchActivity: 反射生成Activity实例,.获取当前的应用的Application对象并且调用attach绑定,.最后通过Instrument调用callActivityOnCreate调用到Activity实例中的onCreate方法。onStart
在类图中并没有生命周期中的onStart,其执行过程:
在executeLifecycleState执行lifecycleItem.execute前,会先执行cycleToPath,该函数会在start状态 ON_CREATE和后续finish状态ON_RESUME,补充遗漏的ON_START,然后通过performLifecycleSequence——>mTransactionHandler.handleStartActivity 调用ActivityThread.handleStartActivity执行Fragment的onStart以及通过Instrument调用onStart方法onResume
ResumeActivityItem作为lifecycleItem.execute,由ActivityThread.handleResumeActivity——>performResumeActivity,完成用Activity的onResume调用
lifecycleItem.postExecute则完成对AMS中的ActivityRecord中状态设置为resume状态,把对应的windowManager设置成resume完成状态
onPause
类似于onResume的执行过程,其也是由PauseActivityItem 来完成对Activity.onPause的调用以及对AMS中ActivityRecord的状态设置onStop
onStop是StopActivityItem来执行,但其StopActivityItem被执行者是在PauseActivityItem.postExecute中回调到AMS中的activityPaused,当执行完pause方法之后会执行completePauseLocked方法,其中会判断当前ActivityRecord已经绑定了App端的数据,说明已经启动了,并且当前的ActivityRecord的visible为false,或者点击了锁屏使其睡眠,都会调用ActivityStatck.addToStopping——> mStackSupervisor.scheduleIdleLocked() 通过向ActivityStackSupervisorHandler发送IDLE_NOW_MSG消息在其ActivityStackSupervisorHandler.handlemessage中处理IDLE消息调用activityIdleInternal——>ActivityStatck.stopActivityLocked,并在其中执行StopActivityItem事务。
StopActivityItem的执行类似其他几个Item。
6、onDestroy
在onStop启动过程中的activityIdleInternal在调用ActivityStatck.stopActivityLocked后,其还会调用stack.destroyActivityLocked,该函数中会启动执行DestroyActivityItem事务。
总结:
Activity的生命周期都是通过事务管理来执行,除了onStart,其他几个生命周期都对应一个ClientTransactionItem,包含execute和postExecute,其中execute要是通过IBinde与ActivityThread交互执行APP端周期的流程,而postExecute主要是更新AMS端的状态。