1.前言
2.Activity啓動過程的時序圖
3.源碼分析
3.1 ActivityManagerService:
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq) {
//...
//通知ActivityThread啓動application
thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
null, null, null, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, isAutofillCompatEnabled);// 1
// 啓動第一個Activity
if (normalMode) {
try {
//Application初始化以後,初始化&啓動第一個Activity
if (mStackSupervisor.attachApplicationLocked(app)) {// 2
didSomething = true;
}
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
badApp = true;
}
}
}
- 註釋1:通知ActivityThread啓動application;
- 註釋2:調用ActivityStackSupervisor,啓動第一個Activity;
3.2 ActivityStackSupervisor 啓動Activity:
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
//獲取應用的進行名稱
final String processName = app.processName;
boolean didSomething = false;
for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = display.getChildAt(stackNdx);
if (!isFocusedStack(stack)) {
continue;
}
stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
final ActivityRecord top = stack.topRunningActivityLocked();
final int size = mTmpActivityList.size();
for (int i = 0; i < size; i++) {
final ActivityRecord activity = mTmpActivityList.get(i);
if (activity.app == null && app.uid == activity.info.applicationInfo.uid
&& processName.equals(activity.processName)) {
try {
// Application初始化以後,啓動第一個Activity
if (realStartActivityLocked(activity, app,
top == activity /* andResume */, true /* checkConfig */)) { // 1
didSomething = true;
}
} catch (RemoteException e) {
Slog.w(TAG, "Exception in new application when starting activity "
+ top.intent.getComponent().flattenToShortString(), e);
throw e;
}
}
}
}
}
if (!didSomething) {
ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
}
return didSomething;
}
- 註釋1:調用自身的realStartActivityLocked(),真正的啓動Activity;
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
//...
// Create activity launch transaction.
//通知ActivityThread建立activity的實例 ;調用Activity的OnCreate; 建立對應PhoneWindow實例
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)); // 2
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward()); // 3
} else {
lifecycleItem = PauseActivityItem.obtain(); // 4
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// 編制啓動Activity實例的事務,並按順序調用onCreate();onStart();onResume();
mService.getLifecycleManager().scheduleTransaction(clientTransaction);// 5
}
- 註釋2:封裝啓動Activity的相關數據與Activity的啓動流程(LaunchActivityItem 下面會介紹該類);
- 註釋3:封裝Activity啓動以後生命週期變化爲Resume的流程(ResumeActivityItem下面會介紹該類);
- 註釋4:封裝Activity啓動以後生命週期變化爲Pause的流程;
- 註釋5:真正開始啓動Activity與調用相關的生命週期方法;
3.3 ClientLifecycleManager管理ClientTransaction:
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();// 1
transaction.schedule();// 2
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();
}
}
- 註釋1:獲取須要啓動Activity進程的代理對象IApplicationThread;
- 註釋2:調用ClientTransaction中的schedule();
3.4 ClientTransaction中schedule函數:
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);// 1
}
- 註釋1:mClient就是與ActivityThread通信的代理對象(IApplicationThread),因此這裏實際上是調用ActivityThread類中ApplicationThread內部類的scheduleTransaction();
3.5 ApplicationThread的scheduleTransaction函數:
private class ApplicationThread extends IApplicationThread.Stub {
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);// 1
}
}
- 註釋1:這裏其實最後仍是調用了ActivityThread的scheduleTransaction(),而這個scheduleTransaction()其實真正的實現是ClientTransactionHandler,由於ActivityThread是繼承ClientTransactionHandler類的;
public abstract class ClientTransactionHandler {
/** Prepare and schedule transaction for execution. */
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);// 2
}
}
- 註釋2:調用ActivityThread的sendMessage(),將ClientTransaction參數經過Handler機制切換至主線程進行處理;
3.6 ActivityThread的H類:
class H extends Handler {
//...
public void handleMessage(Message msg) {
switch (msg.what) {
case EXECUTE_TRANSACTION: // 1
final ClientTransaction transaction = (ClientTransaction) msg.obj;// 2
mTransactionExecutor.execute(transaction);// 3
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;
}
}
}
- 註釋1:接收ClientTransactionHandler發送的EXECUTE_TRANSACTION事件;
- 註釋2:接收ClientTransactionHandler發送的ClientTransaction參數;
- 註釋3:經過TransactionExecutor真正處理ClientTransaction中封裝的Activity相關信息;
3.7 TransactionExecutor處理ClientTransaction:
public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
executeCallbacks(transaction);
executeLifecycleState(transaction);
mPendingActions.clear();
log("End resolving transaction");
}
3.8 executeCallbacks()啓動Activity:
@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);
// In case when post-execution state of the last callback matches the final state requested
// for the activity in this transaction, we won't do the last transition here and do it when
// moving to final state instead (because it may contain additional parameters from server).
final ActivityLifecycleItem finalStateRequest = transaction.getLifecycleStateRequest();
final int finalState = finalStateRequest != null ? finalStateRequest.getTargetState()
: UNDEFINED;
// Index of the last callback that requests some post-execution state.
final int lastCallbackRequestingState = lastCallbackRequestingState(transaction);
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);// 1
log("Resolving callback: " + item);
final int postExecutionState = item.getPostExecutionState();
final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
item.getPostExecutionState());
if (closestPreExecutionState != UNDEFINED) {
cycleToPath(r, closestPreExecutionState);
}
item.execute(mTransactionHandler, token, mPendingActions);// 2
item.postExecute(mTransactionHandler, token, mPendingActions);
if (r == null) {
// Launch activity request will create an activity record.
r = mTransactionHandler.getActivityClient(token);
}
if (postExecutionState != UNDEFINED && r != null) {
// Skip the very last transition and perform it by explicit state request instead.
final boolean shouldExcludeLastTransition =
i == lastCallbackRequestingState && finalState == postExecutionState;
cycleToPath(r, postExecutionState, shouldExcludeLastTransition);
}
}
}
- 註釋1:獲取ClientTransaction中的ClientTransactionItem對象(其實這裏的對象就上面3.2介紹中的LaunchActivityItem);
- 註釋2:調用LaunchActivityItem類的execute(),下面咱們看看LaunchActivityItem;
public class LaunchActivityItem extends ClientTransactionItem {
@Override
public void execute(ClientTransactionHandler client, IBinder token,// 1
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);// 2
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
}
- 註釋1:剛剛說了ClientTransactionHandler是被ActivityThread繼承,因此這裏傳入進來就是ActivityThread;
- 註釋2:看到了吧,通過屢次不一樣層次相互調用,最終真正調用ActivityThread的handleLaunchActivity(),啓動應用的第一個Activity;
3.8 executeLifecycleState()改變Activity的生命週期:
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();// 1
if (lifecycleItem == null) {
// No lifecycle request, return early.
return;
}
log("Resolving lifecycle state: " + lifecycleItem);
final IBinder token = transaction.getActivityToken();
final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
if (r == null) {
// Ignore requests for non-existent client records for now.
return;
}
// Cycle to the state right before the final requested state.
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
// Execute the final transition with proper parameters.
lifecycleItem.execute(mTransactionHandler, token, mPendingActions); // 2
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
- 註釋1:獲取ClientTransaction中的ActivityLifecycleItem 對象(其實這裏的對象就上面3.2介紹中的ResumeActivityItem);
- 註釋2:調用ResumeActivityItem的execute(),下面咱們看看ResumeActivityItem;
public class ResumeActivityItem extends ActivityLifecycleItem {
//...
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward, // 1
"RESUME_ACTIVITY");
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
}
- 註釋1:其實就是調用Activity的handleResumeActivity(),最終就會調用Activity的onStart()與onResume();
4.類關係
- 經過上圖發現,Activity啓動過程就是AMS與ActivityThread不一樣的進程交互實現的。
5.總結
做者:Linhaojian 連接:https://www.jianshu.com/p/7d0d548ebbb4 來源:簡書 簡書著做權歸做者全部,任何形式的轉載都請聯繫做者得到受權並註明出處。