备注:Android 11源码
本文基于Android 11的源码分析,简要的跟踪以下Activity的启动流程,发现在一些细节已经发生变化,例如没有出现ActivityManagerService
,而是出现了ActivityTaskManagerService
。
客户端的调用
当我们调用startActivity
启动一个Actvity
时,都会调用到startActivityForResult
函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 public void startActivityForResult ( String who, Intent intent, int requestCode, @Nullable Bundle options) { ... Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this , mMainThread.getApplicationThread(), mToken, who, intent, requestCode, options); if (ar != null ) { mMainThread.sendActivityResult( mToken, who, requestCode, ar.getResultCode(), ar.getResultData()); } cancelInputsAndStartExitTransition(options); }
调用了Instrumentation
对象的execStartActivity
函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public ActivityResult execStartActivity ( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { IApplicationThread whoThread = (IApplicationThread) contextThread; ... try { 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().startActivity
函数。
1 2 3 4 5 6 7 8 9 10 11 12 public static IActivityTaskManager getService () { return IActivityTaskManagerSingleton.get(); } 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); } };
通过getService
函数实现,可见通过AIDL
的形式调用了服务端的ActivityTaskManagerService
的startActivity
函数。注释1得到名为activity_task
的Service
引用,也就是IBinder
类型的ATM
引用。注释2将其转换成IActivityTaskManager
类型对象,即服务端ATM在客户端的代表,客户端通过该代表与服务端交互。
服务端的处理
查看AIDL
服务端ActivityTaskManagerService
的startActivity
的调用。ActivityTaskManagerService
是用来管理Activity
和他们容器Stack
的系统服务。
1 2 3 4 5 6 7 8 9 @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()); }
startActivity
通过增加UserHandle.getCallingUserId()
获取到用户ID。并调用了startActivityAsUser
函数,主要进行一些权限检查,例如是否同个包名,是否在沙盒。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 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 ); } 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" ); 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().obtainStarter
函数返回了ActivityStarter
对象,通过构造者模式设置相关属性之后,调用了excute
函数。ActivityStarter
主要根据intent
和flags
负责如何启动Activity
,以及设置和它相关联的栈。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 int execute () { try { ... synchronized (mService.mGlobalLock) { ... res = executeRequest(mRequest); ... } ... return getExternalResult(mRequest.waitResult == null ? res : waitForResult(res, mLastStartActivityRecord)); } } finally { onExecutionComplete(); } }
execute
函数挺长的,主要根据之前的配置信息解析出必要的信息,例如从intent
中解析出要启动Activity
的相关信息activityInfo
。其中调用executeRequest
函数。该函数代码很长,主要进行几项检查,例如启动标志Flags
和权限,以及解析相关信息。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 private int executeRequest (Request request) { final int launchFlags = intent.getFlags(); if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null ) { ... 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); mLastStartActivityRecord = r; mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession, request.voiceInteractor, startFlags, true , checkedOptions, inTask, restrictedBgActivity, intentGrants); if (request.outActivity != null ) { request.outActivity[0 ] = mLastStartActivityRecord; } return mLastStartActivityResult; }
executeRequest
函数最终将Activity
相关信息封装到ActivityRecord
对象中,然后调用startActivityUnchecked
函数。
1 2 3 4 5 6 7 8 9 10 11 private int startActivityUnchecked (final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, Task inTask, boolean restrictedBgActivity, NeededUriGrants intentGrants) { ... result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor, startFlags, doResume, options, inTask,restrictedBgActivity,intentGrants); ... return result; }
调用了startActivityInner
函数。这里就是判断Activity
的启动模式,是添加到已有栈顶或者传递新的intent
给已启动的Activity
。
1 2 3 4 5 6 7 8 9 10 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
函数
1 2 3 4 5 6 7 boolean resumeFocusedStacksTopActivities ( ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) { ... result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions); ... return result; }
调用了ActivityStack
的resumeTopActivityUncheckedLocked
函数。此时就是将Activity
栈顶的Activity
进行resume
。
1 2 3 4 5 6 boolean resumeTopActivityUncheckedLocked (ActivityRecord prev, ActivityOptions options) { ... result = resumeTopActivityInnerLocked(prev, options); ... return result; }
调用了resumeTopActivityInnerLocked
函数,主要住一些ActivityRecord
类状态的判断和更新。
1 2 3 4 5 6 private boolean resumeTopActivityInnerLocked (ActivityRecord prev, ActivityOptions options) { ... mStackSupervisor.startSpecificActivity(next, true , true ); ... return true ; }
然后调用了ActivityStatckSupervisor
的startSpecificActivity
函数。
1 2 3 4 5 void startSpecificActivity (ActivityRecord r, boolean andResume, boolean checkConfig) { ... realStartActivityLocked(r, wpc, andResume, checkConfig); ... }
调用realStartActivityLocked
函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 boolean realStartActivityLocked (ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) throws RemoteException { ... final ClientTransaction clientTransaction = ClientTransaction.obtain( proc.getThread(), r.appToken); clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent), System.identityHashCode(r), r.info, 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())); final ActivityLifecycleItem lifecycleItem; if (andResume) { lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward()); } else { lifecycleItem = PauseActivityItem.obtain(); } clientTransaction.setLifecycleStateRequest(lifecycleItem); mService.getLifecycleManager().scheduleTransaction(clientTransaction); ... return true ; }
注释1创建了ClientTransaction
对象,主要保存一些发送给客户端的信息和回调。例如注释2添加了LaunchActivityItem
对象回调,该回调主要用来启动Activity
,也是我们关心的地方。然后注释3执行ClientTransaction
对象。mService.getLifecycleManager()
返回的是一个ClientLifecycleManager
对象。
1 2 3 4 5 6 7 void scheduleTransaction (ClientTransaction transaction) throws RemoteException { final IApplicationThread client = transaction.getClient(); transaction.schedule(); if (!(client instanceof Binder)) { transaction.recycle(); } }
调用了ClientTransaction
的schedule
函数。
1 2 3 public void schedule () throws RemoteException { mClient.scheduleTransaction(this ); }
这里的mClient
是IApplicationThread
,也就是以AIDL
跨进程通信。具体的实现类其实是ActivityThread
的内部类ApplicationThread
。
客户端的处理
1 2 3 public void scheduleTransaction (ClientTransaction transaction) throws RemoteException { ActivityThread.this .scheduleTransaction(transaction); }
调用了ActivityThread
的scheduleTransaction
函数,但ActivityThread
没有该方法,在其父类ClientTransactionHandler
找到。
1 2 3 4 void scheduleTransaction (ClientTransaction transaction) { transaction.preExecute(this ); sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); }
调用了抽象方法sendMessage
发送了参数为ActivityThread.H.EXECUTE_TRANSACTION
的消息。回到ActivityThread
。sendMessage
有很多重载函数。最终还是调用了mH
的sendMessage
函数。mH
是H类实例,是Handler
的子类。
1 2 3 4 private void sendMessage (int what, Object obj, int arg1, int arg2, boolean async) { ... mH.sendMessage(msg); }
定位到H的handleMessage
函数的EXECUTE_TRANSACTION
分支。
1 2 3 4 5 6 7 case EXECUTE_TRANSACTION: final ClientTransaction transaction = (ClientTransaction) msg.obj; mTransactionExecutor.execute(transaction); if (isSystem()) { transaction.recycle(); } break ;
调用execute
函数。
1 2 3 4 5 6 public void execute (ClientTransaction transaction) { ... executeCallbacks(transaction); executeLifecycleState(transaction); ... }
查看executeCallbacks
函数。
1 2 3 4 5 6 7 8 9 10 11 public void executeCallbacks (ClientTransaction transaction) { final List<ClientTransactionItem> callbacks = transaction.getCallbacks(); ... final int size = callbacks.size(); for (int i = 0 ; i < size; ++i) { ... item.execute(mTransactionHandler, token, mPendingActions); ... } } }
executeCallbacks
函数主要循环执行ClientTransitions
对象的所有的回调,而我们在前面看到设置了LaunchActivityItem
回调。
1 2 3 4 5 6 7 8 9 10 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 ); Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER); }
调用了ClientTransactionHandler
的handleLaunchActivity
函数,是一个抽象方法,定位到ActivityThread
。
1 2 3 4 5 6 7 8 @Override public Activity handleLaunchActivity (ActivityClientRecord r, ... final Activity a = performLaunchActivity(r, customIntent) ; ... return a; }
performLaunchActivity
函数就很熟悉了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 private Activity performLaunchActivity (ActivityClientRecord r, Intent customIntent) { ActivityInfo aInfo = r.activityInfo; if (r.packageInfo == null ) { r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo, Context.CONTEXT_INCLUDE_CODE); } ComponentName component = r.intent.getComponent(); if (component == null ) { component = r.intent.resolveActivity( mInitialApplication.getPackageManager()); r.intent.setComponent(component); } if (r.activityInfo.targetActivity != null ) { component = new ComponentName(r.activityInfo.packageName, r.activityInfo.targetActivity); } ContextImpl appContext = createBaseContextForActivity(r); Activity activity = null ; try { 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); } } Application app = r.packageInfo.makeApplication(false , mInstrumentation); if (activity != null ) { ... appContext.getResources().addLoaders( app.getResources().getLoaders().toArray(new ResourcesLoader[0 ])); appContext.setOuterContext(activity); 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); ... if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); } ... return activity; }
可以看到performLaunchActivity
创建了Activity
实例,调用了callActivityOnCreate
函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public void callActivityOnCreate (Activity activity, Bundle icicle, PersistableBundle persistentState) { prePerformCreate(activity); activity.performCreate(icicle, persistentState); postPerformCreate(activity); } final void performCreate (Bundle icicle, PersistableBundle persistentState) { ... if (persistentState != null ) { onCreate(icicle, persistentState); } else { onCreate(icicle); } ... }
可见,最后调用了Activity
的onCreate
函数。
总结
其实本文只是跟一下Activity
的启动流程,其中涉及到了很多细节都忽略了,例如最后Context
上下文的创建,这个留到其他文章具体点的分析。也就是从整体思路了解Activity
的启动流程。