在Activity中的startActivityForResult()調用Instrumentation的execStartActivity():java
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options); 複製代碼
在Instrumentation的execStartActivity()調用ATMS的startActivity():android
int result = ActivityTaskManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); 複製代碼
其中ATMS實例是從AMS中得到的:web
/** @hide */
public static IActivityTaskManager getService() { return IActivityTaskManagerSingleton.get(); } @UnsupportedAppUsage(trackingBug = 129726065) private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton = new Singleton<IActivityTaskManager>() { @Override protected IActivityTaskManager create() { final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE); return IActivityTaskManager.Stub.asInterface(b); } }; 複製代碼
在ATMS的startActivityAsUser()調用ActivityStarter的execute():算法
微信
// TODO: Switch to user app stacks here. return getActivityStartController().obtainStarter(intent, "startActivityAsUser") .setCaller(caller) .setCallingPackage(callingPackage) .setResolvedType(resolvedType) .setResultTo(resultTo) .setResultWho(resultWho) .setRequestCode(requestCode) .setStartFlags(startFlags) .setProfilerInfo(profilerInfo) .setActivityOptions(bOptions) .setMayWait(userId) .execute(); 複製代碼複製代碼
在ActivityStarter的startActivityUnchecked()調用RootActivityContainer的resumeFocusedStacksTopActivities():app
mRootActivityContainer.resumeFocusedStacksTopActivities();
複製代碼
在RootActivityContainer的resumeFocusedStacksTopActivities()調用ActivityStack 的resumeTopActivityUncheckedLocked():編輯器
boolean result = false;
if (targetStack != null && (targetStack.isTopStackOnDisplay()
|| getTopDisplayFocusedStack() == targetStack)) {
result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
複製代碼
在ActivityStack的startPausingLocked()調用ClientLifecycleManager的scheduleTransaction(),此處操做對應生命週期的onPause()流程:ide
mService.getLifecycleManager().scheduleTransaction(prev.app.getThread(),
prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving,
prev.configChangeFlags, pauseImmediately));
複製代碼
或者先在ActivityStack的resumeTopActivityInnerLocked()調用ActivityStackSupervisor的startSpecificActivityLocked():post
mStackSupervisor.startSpecificActivityLocked(next, true, false);
複製代碼
而後在ActivityStackSupervisor的realStartActivityLocked()調用ClientLifecycleManager的scheduleTransaction(),此處操做對應生命週期的onCreate()流程:學習
// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
複製代碼
在ClientLifecycleManager的scheduleTransaction()中調用ClientTransaction的schedule():
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule();
}
複製代碼
在ClientTransaction的schedule()中調用ActivityThread內部類ApplicationThread的scheduleTransaction():
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
複製代碼
在ApplicationThread的scheduleTransaction()調用了ActivityThread也就是其父類ClientTransactionHandler的scheduleTransaction():
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
複製代碼
在ClientTransactionHandler的scheduleTransaction(),經過H發送了EXECUTE_TRANSACTION消息:
/** Prepare and schedule transaction for execution. */
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
複製代碼
在H中接收EXECUTE_TRANSACTION消息,並調用了TransactionExecutor的execute():
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;
複製代碼
若是對應的是onPause()流程,將會在TransactionExecutor的execute()調用executeLifecycleState(),並繼續調用ActivityLifecycleItem也就是子類PauseActivityItem的execute():
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
複製代碼
在PauseActivityItem的execute()調用ClientTransactionHandler也就是子類ActivityThread的handlePauseActivity():
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
"PAUSE_ACTIVITY_ITEM");
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
複製代碼
然後將繼續在ActivityThread的performPauseActivityIfNeeded()調用Instrumentation的callActivityOnPause():
mInstrumentation.callActivityOnPause(r.activity);
複製代碼
然後調用Activity的performPause():
public void callActivityOnPause(Activity activity) {
activity.performPause();
}
複製代碼
最後調用Activity的onPause():
final void performPause() {
dispatchActivityPrePaused();
mDoReportFullyDrawn = false;
mFragments.dispatchPause();
mCalled = false;
onPause();
writeEventLog(LOG_AM_ON_PAUSE_CALLED, "performPause");
mResumed = false;
if (!mCalled && getApplicationInfo().targetSdkVersion
>= android.os.Build.VERSION_CODES.GINGERBREAD) {
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onPause()");
}
dispatchActivityPostPaused();
}
複製代碼
若是對應的是onCreate()流程,將會在TransactionExecutor的execute()調用executeCallbacks(),並繼續調用ClientTransactionItem 也就是子類LaunchActivityItem的execute():
item.execute(mTransactionHandler, token, mPendingActions);
複製代碼
在LaunchActivityItem的execute()調用ClientTransactionHandler也就是子類ActivityThread的handleLaunchActivity():
@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, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client, mAssistToken);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
複製代碼
然後將繼續在ActivityThread的performLaunchActivity()調用Instrumentation的newActivity()使用反射來建立Activity實例:
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
複製代碼
public Activity newActivity(ClassLoader cl, String className,
Intent intent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
String pkg = intent != null && intent.getComponent() != null
? intent.getComponent().getPackageName() : null;
return getFactory(pkg).instantiateActivity(cl, className, intent);
}
複製代碼
public @NonNull Activity instantiateActivity(@NonNull ClassLoader cl, @NonNull String className,
@Nullable Intent intent)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return (Activity) cl.loadClass(className).newInstance();
}
複製代碼
然後繼續在ActivityThread的performLaunchActivity()調用Activity的attach():
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback,
r.assistToken);
複製代碼
建立好Activity實例後,將會調用Instrumentation的callActivityOnCreate():
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
複製代碼
然後調用Activity的performCreate():
public void callActivityOnCreate(Activity activity, Bundle icicle,
PersistableBundle persistentState) {
prePerformCreate(activity);
activity.performCreate(icicle, persistentState);
postPerformCreate(activity);
}
複製代碼
最後調用Activity的onCreate():
@UnsupportedAppUsage final void performCreate(Bundle icicle, PersistableBundle persistentState) { dispatchActivityPreCreated(icicle); mCanEnterPictureInPicture = true; restoreHasCurrentPermissionRequest(icicle); if (persistentState != null) { onCreate(icicle, persistentState); } else { onCreate(icicle); } writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate"); mActivityTransitionState.readState(icicle);複製代碼mVisibleFromClient = !mWindow.getWindowStyle().getBoolean( com.android.internal.R.styleable.Window_windowNoDisplay, false); mFragments.dispatchActivityCreated(); mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions()); dispatchActivityPostCreated(icicle); 複製代碼} 複製代碼mVisibleFromClient = !mWindow.getWindowStyle().getBoolean( com.android.internal.R.styleable.Window_windowNoDisplay, false); mFragments.dispatchActivityCreated(); mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions()); dispatchActivityPostCreated(icicle); 複製代碼
喜歡就點個「在看」吧 ▽