赞
踩
四大组件启动流程系列的第一篇:Activity的启动流程
基于 Android 11 源码
Activity 的前世今生不做过多赘述,本系列文章主要面向有一定基础的 Android 开发者,如有疑问,欢迎交流学习。
当我们调用 startActivity 时表示要启动一个新的 Activity 啦,那它怎么把 Activity 启动起来的呢?
Activity 的启动流程分三部分来看
第一部分:Activity 到 ATMS
第二部分:ATMS 到 ActivityThread
第三部分:ActivityThread 到 Activity 启动
startActivity(new Intent(this, MainActivity.class));
Activity#startActivity(Intent)
@Override
public void startActivity(Intent intent) {
// 第二个参数为 null
this.startActivity(intent, null);
}
调用 startActivity 的重载方法
@Override public void startActivity(Intent intent, @Nullable Bundle options) { if (mIntent != null && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN) && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY)) { if (TextUtils.equals(getPackageName(), intent.resolveActivity(getPackageManager()).getPackageName())) { // Apply Autofill restore mechanism on the started activity by startActivity() final IBinder token = mIntent.getIBinderExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN); // Remove restore ability from current activity mIntent.removeExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN); mIntent.removeExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY); // Put restore token intent.putExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN, token); intent.putExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY, true); } } if (options != null) { startActivityForResult(intent, -1, options); } else { // Note we want to go through this call for compatibility with // applications that may have overridden the method. // 因为 options == null 所以走到这儿 startActivityForResult(intent, -1); } }
Activity#startActivityForResult(Intent, int)
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
startActivityForResult(intent, requestCode, null);
}
调用 startActivityForResult 的重载方法
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) { if (mParent == null) { options = transferSpringboardActivityOptions(options); // 关键来了 Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options); if (ar != null) { mMainThread.sendActivityResult( mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData()); } if (requestCode >= 0) { // If this start is requesting a result, we can avoid making // the activity visible until the result is received. Setting // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the // activity hidden during this time, to avoid flickering. // This can only be done when a result is requested because // that guarantees we will get information back when the // activity is finished, no matter what happens to it. mStartedActivity = true; } cancelInputsAndStartExitTransition(options); // TODO Consider clearing/flushing other event sources and events for child windows. } else { if (options != null) { mParent.startActivityFromChild(this, intent, requestCode, options); } else { // Note we want to go through this method for compatibility with // existing applications that may have overridden it. mParent.startActivityFromChild(this, intent, requestCode); } } }
关键调用 mInstrumentation.execStartActivity
Instrumentation#execStartActivity
@UnsupportedAppUsage public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { IApplicationThread whoThread = (IApplicationThread) contextThread; Uri referrer = target != null ? target.onProvideReferrer() : null; if (referrer != null) { intent.putExtra(Intent.EXTRA_REFERRER, referrer); } if (mActivityMonitors != null) { synchronized (mSync) { final int N = mActivityMonitors.size(); for (int i=0; i<N; i++) { final ActivityMonitor am = mActivityMonitors.get(i); ActivityResult result = null; if (am.ignoreMatchingSpecificIntents()) { result = am.onStartActivity(intent); } if (result != null) { am.mHits++; return result; } else if (am.match(who, null, intent)) { am.mHits++; if (am.isBlocking()) { return requestCode >= 0 ? am.getResult() : null; } break; } } } } try { intent.migrateExtraStreamToClipData(who); intent.prepareToLeaveProcess(who); int result = ActivityTaskManager.getService().startActivity(whoThread, who.getBasePackageName(), who.getAttributionTag(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); checkStartActivityResult(result, intent); } catch (RemoteException e) { throw new RuntimeException("Failure from system", e); } return null; }
最终通过 ActivityTaskManager.getService() 获取ATMS的服务代理并调用 ATMS.startActivity 方法,这时从 app 的进程进入到 SystemServer 进程,发生了一次跨进程!
ActivityTaskManagerService#startActivity
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
ActivityTaskManagerService#startActivityAsUser
@Override
public int startActivityAsUser(IApplicationThread caller, String callingPackage,
String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
Bundle bOptions, int userId) {
return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
true /*validateIncomingUser*/);
}
ActivityTaskManagerService#startActivityAsUser
private int startActivityAsUser(IApplicationThread caller, String callingPackage, @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) { assertPackageMatchesCallingUid(callingPackage); enforceNotIsolatedCaller("startActivityAsUser"); userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser, Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser"); // TODO: Switch to user app stacks here. return getActivityStartController().obtainStarter(intent, "startActivityAsUser") .setCaller(caller) .setCallingPackage(callingPackage) .setCallingFeatureId(callingFeatureId) .setResolvedType(resolvedType) .setResultTo(resultTo) .setResultWho(resultWho) .setRequestCode(requestCode) .setStartFlags(startFlags) .setProfilerInfo(profilerInfo) .setActivityOptions(bOptions) .setUserId(userId) .execute(); }
最后 return 的对象设置了那么多属性并在最后调用 excute() 执行。
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setCallingFeatureId(callingFeatureId)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setUserId(userId)
.execute();
先看看 getActivityStartController() 是个啥
ActivityStartController getActivityStartController() {
return mActivityStartController;
}
getActivityStartController().obtainStarter(intent, "startActivityAsUser")
ActivityStarter obtainStarter(Intent intent, String reason) {
return mFactory.obtain().setIntent(intent).setReason(reason);
}
mFactory.obtain() 使用工厂模式从 DefaultFactory 类的缓存池(最大缓存数量为3) 中取出 ActivityStarter 对象
getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
setCaller(caller) caller 是 IApplicationThread 类型的对象,等于 ActivityStarter 里缓存了与 app 进程连接的桥梁,之后可以进行跨进程调用 app 进程。
ApplicationThread是ActivityThread内部类,继承自IApplicationThread.Stub,作为服务端接受AMS发出的请求并执行,ApplicationThread是ActivityThread与AMS连接的桥梁。
再看最后的 execute()
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
...
.execute();
ActivityStarter#execute
int execute() {
try {
...
res = executeRequest(mRequest);
...
return getExternalResult(mRequest.waitResult == null ? res
: waitForResult(res, mLastStartActivityRecord));
} finally {
onExecutionComplete();
}
}
ActivityStarter#executeRequest
/** *执行活动启动请求,开始启动活动的旅程。在这里 *首先执行几个初步检查。正常的活动启动流程将 *通过{@link#startActivityUnchecked}到{@link#startactivitynner}。 */ private int executeRequest(Request request) { ... // 在这里创建 ActivityRecord 对象,用于描述 Activity 信息 final ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid, callingPackage, callingFeatureId, intent, resolvedType, aInfo, mService.getGlobalConfiguration(), resultRecord, resultWho, requestCode, request.componentSpecified, voiceSession != null, mSupervisor, checkedOptions, sourceRecord); .... mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession, request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask, restrictedBgActivity, intentGrants); .... return mLastStartActivityResult; }
ActivityStarter#startActivityUnchecked
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, Task inTask, boolean restrictedBgActivity, NeededUriGrants intentGrants) { int result = START_CANCELED; final ActivityStack startedActivityStack; try { mService.deferWindowLayout(); Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "startActivityInner"); // 关键 result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor, startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants); } finally { Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER); startedActivityStack = handleStartResult(r, result); mService.continueWindowLayout(); } postStartActivityProcessing(r, result, startedActivityStack); return result; }
ActivityStarter#startActivityInner
int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
....
mRootWindowContainer.resumeFocusedStacksTopActivities(
mTargetStack, mStartActivity, mOptions);
....
return START_SUCCESS;
}
调用了RootWindowContainer#resumeFocusedStacksTopActivities
boolean resumeFocusedStacksTopActivities(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
...
result |= focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
...
return result;
}
调用 ActivityStack#resumeTopActivityUncheckedLocked
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
...
result = resumeTopActivityInnerLocked(prev, options);
...
return result;
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
...
//关键关键!!! 传入了 next.app.getThread() 返回的是 IApplication
final ClientTransaction transaction =
ClientTransaction.obtain(next.app.getThread(), next.appToken);
transaction.setLifecycleStateRequest(
ResumeActivityItem.obtain(next.app.getReportedProcState(),
dc.isNextTransitionForward()));
mAtmService.getLifecycleManager().scheduleTransaction(transaction);
...
return true;
}
mStackSupervisor.startSpecificActivity(next, true, true);
ActivityStackSupervisor#startSpecificActivity
void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
...
realStartActivityLocked(r, wpc, andResume, checkConfig);
...
}
ActivityStackSupervisor#realStartActivityLocked
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) throws RemoteException { ... // Create activity launch transaction. // 关键关键!!! 传入了 proc.getThread() 返回的是 IApplication // 赋值给 ClientTransaction 的 mClient 对象 final ClientTransaction clientTransaction = ClientTransaction.obtain( proc.getThread(), r.appToken); final DisplayContent dc = r.getDisplay().mDisplayContent; 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, proc.getReportedProcState(), r.getSavedState(), r.getPersistentSavedState(), results, newIntents, dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(), r.assistToken, r.createFixedRotationAdjustmentsIfNeeded())); // Set desired final state. final ActivityLifecycleItem lifecycleItem; if (andResume) { lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward()); } else { lifecycleItem = PauseActivityItem.obtain(); } clientTransaction.setLifecycleStateRequest(lifecycleItem); // Schedule transaction. mService.getLifecycleManager().scheduleTransaction(clientTransaction); ... }
通过缓存池获取 ClientTransaction 类型的对象,并通过 mService.getLifecycleManager()调用 scheduleTransaction 方法开始执行任务
mService 是 ActivityTaskManagerService 类型的对象
ActivityTaskManagerService#getLifecycleManager
ClientLifecycleManager getLifecycleManager() {
return mLifecycleManager;
}
返回的 ClientLifecycleManager 类型对象,再看它的 scheduleTransaction 做了啥
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();
}
}
调用了 ClientTransaction 的 schedule 方法,简单粗暴。。。
要我们回头看 ClientTransaction 的 schedule 是怎么执行的
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
咦 又调用了 mClient 的 scheduleTransaction 。。。 额绕了一圈
又要回头看看 mClient 对象是啥了
在 ClientTransaction 中 mClient 是这样定义的
/** Target client. */
private IApplicationThread mClient;
IApplicationThread 对象 是与 app 进程沟通的桥梁!
刚刚在 调用 ActivityStack#resumeTopActivityUncheckedLocked 中将 IApplicationThread 传进 ClientTransaction 里了呢。
所以转了一圈 这个 ClientTransaction 对象会在 IApplicationThread 中调用,
同学们应该了解过 app 进程的 ApplicationThread 是 ActivityThread 内部类,并且实现了 IApplicationThread.Stub 。
mClient.scheduleTransaction(this); 实际上是 ApplicationThread#scheduleTransaction
这时候发生了跨进程:从 SystemServer 进程到 app 进程
ApplicationThread#scheduleTransaction
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
内部调用了 ActivityThread#scheduleTransaction
追代码发现 ActivityThread 并没有 scheduleTransaction 方法的具体实现,这时候需要看看 ActivityThread 的父类有没有
ActivityThread 继承了 ClientTransactionHandler
在 ClientTransactionHandler 中找到了 scheduleTransaction
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
调用 sendMessage 方法并且 what 的值为 ActivityThread.H.EXECUTE_TRANSACTION
ClientTransactionHandler#sendMessage
abstract void sendMessage(int what, Object obj);
sendMessage 是抽象方法,找找在 ActivityThread 的具体实现
ActivityThread#sendMessage
void sendMessage(int what, Object obj) { sendMessage(what, obj, 0, 0, false); } private void sendMessage(int what, Object obj, int arg1) { sendMessage(what, obj, arg1, 0, false); } private void sendMessage(int what, Object obj, int arg1, int arg2) { sendMessage(what, obj, arg1, arg2, false); } private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) { if (DEBUG_MESSAGES) { Slog.v(TAG, "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj); } Message msg = Message.obtain(); msg.what = what; msg.obj = obj; msg.arg1 = arg1; msg.arg2 = arg2; if (async) { msg.setAsynchronous(true); } mH.sendMessage(msg); } private void sendMessage(int what, Object obj, int arg1, int arg2, int seq) { if (DEBUG_MESSAGES) Slog.v( TAG, "SCHEDULE " + mH.codeToString(what) + " arg1=" + arg1 + " arg2=" + arg2 + "seq= " + seq); Message msg = Message.obtain(); msg.what = what; SomeArgs args = SomeArgs.obtain(); args.arg1 = obj; args.argi1 = arg1; args.argi2 = arg2; args.argi3 = seq; msg.obj = args; mH.sendMessage(msg); }
有一系列的重载方法,但最终都是调用 mH.sendMessage
final H mH = new H();
H 是 ActivityThread 的内部类,继承了 Handler
class H extends Handler
那刚刚 mH.sendMessage 发送的消息 ActivityThread.H.EXECUTE_TRANSACTION 会被 H 来处理
ActivityThread#H#handleMessage
public void handleMessage(Message msg) { if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what)); 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; ... } }
调用 TransactionExecutor 的 execute
public void execute(ClientTransaction transaction) {
...
executeCallbacks(transaction);
...
}
TransactionExecutor#executeCallbacks
/** Cycle through all states requested by callbacks and execute them at proper times. */ @VisibleForTesting public void executeCallbacks(ClientTransaction transaction) { // Callback 在 ActivityStackSupervisor#realStartActivityLocked中被添加 类型为 LaunchActivityItem final List<ClientTransactionItem> callbacks = transaction.getCallbacks(); if (callbacks == null || callbacks.isEmpty()) { // No callbacks to execute, return early. return; } 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); ... } }
所以在这里执行的是 LaunchActivityItem 的 execute
LaunchActivityItem#execute
@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, mFixedRotationAdjustments);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
内部调用 client.handleLaunchActivity ,client 的类型是 ClientTransactionHandler ,刚才梳理过 ActivityThread 继承的就是 ClientTransactionHandler。
ActivityThread#handleLaunchActivity
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
...
final Activity a = performLaunchActivity(r, customIntent);
...
return a;
}
ActivityThread#performLaunchActivity
/** Core implementation of activity launch. */ private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { ... // app 的 Context 在这儿创建的 ContextImpl appContext = createBaseContextForActivity(r); Activity activity = null; try { // 通过反射方式创建 Activity 对象 java.lang.ClassLoader cl = appContext.getClassLoader(); activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent); StrictMode.incrementExpectedActivityCount(activity.getClass()); r.intent.setExtrasClassLoader(cl); r.intent.prepareToEnterProcess(); if (r.state != null) { r.state.setClassLoader(cl); } } catch (Exception e) { if (!mInstrumentation.onException(activity, e)) { throw new RuntimeException( "Unable to instantiate activity " + component + ": " + e.toString(), e); } } ... // makeApplication 方法内部会判断 app 是否创建了 Application,若已创建则返回,若未创建则新建并返回 Application app = r.packageInfo.makeApplication(false, mInstrumentation); ... // attach 方法非常关键!!!内部创建了 PhoneWindow 对象 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); ... // 这里开始 Attach 的生命周期 onCreate if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); } ... }
Activity 的启动流程梳理差不多了。涉及的类真多。不过梳理一遍,可以加深对 Activity 的印象,增加记忆力,以后忘的慢 ~~
如果感觉文章可以学到东西,欢迎大佬关注小弟的公众号:Android 翻山之路
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。