AMS解析,Activity是如何被打开的
- 前言
- 总结
- 1. PMS保存App缩略信息
- 2. startActivity发送请求
- 3. AMS从PMS获取目标Activity的相关信息
- 3.1 AMS部分
- 3.2 PMS部分
- 4. AMS操作Activity返回栈,将目标Activity调用resume
- 5. AMS将目标页面信息发给ActivityThread
- 6. ActivityThread通过反射创建Activity
- 6.1 scheduleTransaction
- 6.2 ClientTransaction的内容
- 6.3 启动Activity:handleLaunchActivity
- 6.4 Activity切换前台:handleResumeActivity
- 参考资料
前言
源码只截取需要看的部分,其他部分会省略。
源码基于API 28也就是Android9.0,也就是源码还有ActivityStackSupervisor的这个版本
其他版本代码不太一样没有ActivityStackSupervisor,但是原理是相同的。
AOSP的源码在这个网站上看:http://aospxref.com/
总结
调用startActivty来启动一个新的activity,需要做多少事?
- 遍历data/app,遍历里面所有的App的文件夹,找到目标的包名。
- 把目标包的apk解压出来。
- 对AndroidManifest.xml进行dom解析(dom解析:把 XML 转换为 JavaScript 可存取的对象)
- 根据解析出来的标签用反射的方式构建MainActivity。
- 进入MainActivity的生命周期,展示页面。
如果每次调用startActivity都要将这五步从头到尾都走一遍,对于系统来说就非常耗时了。
而实际上Android系统是把启动的前三步交由PMS处理,在手机开机的时候就已经把data/app内所有的包都遍历过了,最后将每个app的缩略信息存在mPackages里面做了个缓存(用缓存空间来换启动时间)。
再将后两步交由AMS处理,在需要启动页面时:
- 应用进程通过IPC(进程间通信)的方式先将启动页面的请求发送给AMS。
- AMS接收到请求后,向PMS中请求对应Activity的的缩略信息。
- PMS将Activity信息封装到ResolveInfo后返回给AMS。
- AMS根据目前的堆栈情况,操作一下堆栈,原本栈顶的Activity给Pause,将目标Activity给Resume,注意此时目标Activity本体还未创建,这里操作的是Activity的缩略信息。
- AMS准备ClientTransaction,将启动Activity所需要的信息返回给ActivityThread。
- ActivityThread通过反射创建Activity,onCreate生命周期由Instrumentation调用。
- onResume生命周期由ActivityThread调用,流程结束。
1. PMS保存App缩略信息
见PMS篇
https://blog.csdn.net/qq_41872247/article/details/125010412
2. startActivity发送请求
从StartActivityForResult开始我们的逻辑
public class Activity extends ContextThemeWrapperimplements LayoutInflater.Factory2,Window.Callback, KeyEvent.Callback,OnCreateContextMenuListener, ComponentCallbacks2,Window.OnWindowDismissedCallback,ContentCaptureManager.ContentCaptureClient {public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,@Nullable Bundle options) {if (mParent == null) {// 一般我们都走这个地方,其他的部分就省略不看了 Instrumentation.ActivityResult ar =mInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), mToken, this,intent, requestCode, options);// ....省略代码} else {// ....省略代码}}
}public class Instrumentation {public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, String target,Intent intent, int requestCode, Bundle options) {try {// ActivityTaskManager.getService() 其实就是去取的AMS,看下面int result = ActivityTaskManager.getService().startActivity(whoThread,who.getOpPackageName(), who.getAttributionTag(), intent,intent.resolveTypeIfNeeded(who.getContentResolver()), token, target,requestCode, 0, null, options);} catch (RemoteException e) {throw new RuntimeException("Failure from system", e);}}
}public class ActivityTaskManager {public static IActivityTaskManager getService() {return IActivityTaskManagerSingleton.get();}private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =new Singleton<IActivityTaskManager>() {@Overrideprotected IActivityTaskManager create() {// 这一行就是跨进程通信去SystemServer进程取ActivityManagerServicefinal IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);return IActivityTaskManager.Stub.asInterface(b);}};
}
ActivityManager.getService本质返回一个Binder对象,就是IActivityManager,就是ActivityManagerProxy,最后交由AMS实现具体逻辑。
3. AMS从PMS获取目标Activity的相关信息
3.1 AMS部分
这里面很多跳转,我们就看跳转之后最后干了什么
public class ActivityManagerService extends IActivityManager.Stubimplements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {public final int startActivityAsUser(IApplicationThread caller, String callingPackage,Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,boolean validateIncomingUser) {// 我们这里不用去管mActivityStartController是做什么的,// 只需要知道他最后去拿了一个ActivityStarter的对象,最后执行了execute就行return mActivityStartController.obtainStarter(intent, "startActivityAsUser").setCaller(caller).setCallingPackage(callingPackage).setResolvedType(resolvedType).setResultTo(resultTo).setResultWho(resultWho).setRequestCode(requestCode).setStartFlags(startFlags).setProfilerInfo(profilerInfo).setActivityOptions(bOptions).setMayWait(userId) //调用完这一行后,mayWait这个字段会被设为true.execute();}
}class ActivityStarter {int execute() {try {// 这里代码会走上面if (mRequest.mayWait) {return startActivityMayWait(mRequest.caller, mRequest.callingUid,mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,mRequest.intent, mRequest.resolvedType,mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,mRequest.inTask, mRequest.reason,mRequest.allowPendingRemoteAnimationRegistryLookup);} else {return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,mRequest.ignoreTargetSecurity, mRequest.componentSpecified,mRequest.outActivity, mRequest.inTask, mRequest.reason,mRequest.allowPendingRemoteAnimationRegistryLookup);}} finally {onExecutionComplete();}}private int startActivityMayWait(IApplicationThread caller, int callingUid,String callingPackage, int requestRealCallingPid, int requestRealCallingUid,Intent intent, String resolvedType,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,IBinder resultTo, String resultWho, int requestCode, int startFlags,ProfilerInfo profilerInfo, WaitResult outResult,Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,int userId, TaskRecord inTask, String reason,boolean allowPendingRemoteAnimationRegistryLookup) {//...省略代码ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,0 /* matchFlags */,computeResolveFilterUid(callingUid, realCallingUid, mRequest.filterCallingUid));// 下面是启动activity的代码int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,allowPendingRemoteAnimationRegistryLookup);// 省略代码...return res;}
}public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener,RecentTasks.Callbacks {final ActivityManagerService mService;ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags,int filterCallingUid) {//有省略代码synchronized (mService) {try {return mService.getPackageManagerInternalLocked().resolveIntent(intent, resolvedType, modifiedFlags, userId, true, filterCallingUid);}}}
}
从AMS -> ActivityStarter -> ActivityStackSupervisor,这三个类的流程下来之后,最后是先去mService.getPackageManagerInternalLocked()就是去拿PMS的内部类。
3.2 PMS部分
PMS和AMS之间做接口解耦的方式是这样,PMS设置了一个内部类Internal,通过内部类可以持有外部类引用的这个特性,让其他对象只需要获得他这个内部类,就可以通过内部类实际上设置的接口方法来调用PMS的实际功能组。
这样PMS类自己的方法就可以全部private,只将需要开放方法的交由Internal类来对外开放。
public class PackageManagerService extends IPackageManager.Stubimplements PackageSender {private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,int flags, int userId, boolean resolveForStart, int filterCallingUid) {//实际的逻辑处理,代码这里省略,下次会贴}private class PackageManagerInternalImpl extends PackageManagerInternal {@Overridepublic ResolveInfo resolveIntent(Intent intent, String resolvedType,int flags, int userId, boolean resolveForStart, int filterCallingUid) {// 不处理任何逻辑,只是调用一下外部类的实际处理方法。return resolveIntentInternal(intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);}}
}
接下来看看他resolveIntent实际做了啥
public class PackageManagerService extends IPackageManager.Stubimplements PackageSender {private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,int flags, int userId, boolean resolveForStart, int filterCallingUid) {//实际的逻辑处理,代码这里省略,下次会贴final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);final ResolveInfo bestChoice =chooseBestActivity(intent, resolvedType, flags, query, userId);return bestChoice; }}/***ResolveInfo就是把四大组件都做了一个封装的信息类,为了不把他分成三四个方法写一大堆重名方法所以封装了一下*/
public class ResolveInfo implements Parcelable {public ActivityInfo activityInfo;public ServiceInfo serviceInfo;public ProviderInfo providerInfo;
}
我们从方法名就可以看得出来,
上面那个queryIntentActivitiesInternal就是通过我们传的Intent信息,去找到所有适合的Activity,然后把他装进ResolveInfo里面
下面那个chooseBestActivity就是将初步筛选出来的Activity,选一个最合适的,最后return出去。
PackageServiceManagerInternal.resolveIntent -> PMS.resolveIntent -> 遍历mPackages找到对应的Package和里面的ActivityInfo -> 用ResolveInfo装起来返回给AMS
4. AMS操作Activity返回栈,将目标Activity调用resume
我们取到resolveIntent之后,回到ActivityStarter的逻辑,继续往下走
class ActivityStarter {private int startActivityMayWait(IApplicationThread caller, int callingUid,String callingPackage, int requestRealCallingPid, int requestRealCallingUid,Intent intent, String resolvedType,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,IBinder resultTo, String resultWho, int requestCode, int startFlags,ProfilerInfo profilerInfo, WaitResult outResult,Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,int userId, TaskRecord inTask, String reason,boolean allowPendingRemoteAnimationRegistryLookup) {//...省略代码ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,0 /* matchFlags */,computeResolveFilterUid(callingUid, realCallingUid, mRequest.filterCallingUid));// 下面是启动activity的代码int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,allowPendingRemoteAnimationRegistryLookup);// 省略代码...return res;}private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,String callingPackage, int realCallingPid, int realCallingUid, int startFlags,SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,ActivityRecord[] outActivity, TaskRecord inTask, String reason,boolean allowPendingRemoteAnimationRegistryLookup) {// 又调了另外一个重载方法mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,inTask, allowPendingRemoteAnimationRegistryLookup);return getExternalResult(mLastStartActivityResult);}private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,String callingPackage, int realCallingPid, int realCallingUid, int startFlags,SafeActivityOptions options,boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {// ...省略代码// 又调了一个重载方法return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,true /* doResume */, checkedOptions, inTask, outActivity);}private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,ActivityRecord[] outActivity) {//省略代码try {result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,startFlags, doResume, options, inTask, outActivity);}return result;}
}
由于代码贴的太多了而且还没啥我们需要关注的重点看着有点累,所以在这里中断一下,总之我们就是经历了各种各样的重名方法调用,最终走到了startActivityUnchecked这个方法,在这里我们就正式开始启动Activity了。
class ActivityStarter {private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,ActivityRecord[] outActivity) {computeLaunchingTaskFlags(); //去拿启动flagmIntent.setFlags(mLaunchFlags);// ...省略一大堆和启动flag相关的逻辑,SingleTask SingleTop那些的计算堆栈相关的,我们这里就看正常的启动final boolean dontStart = top != null && mStartActivity.resultTo == null&& top.realActivity.equals(mStartActivity.realActivity)&& top.userId == mStartActivity.userId&& top.app != null && top.app.thread != null&& ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0|| isLaunchModeOneOf(LAUNCH_SINGLE_TOP, LAUNCH_SINGLE_TASK));if (dontStart) {if (mDoResume) {// 代码走这里mSupervisor.resumeFocusedStackTopActivityLocked();}return START_DELIVERED_TO_TOP;}}
}public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener,RecentTasks.Callbacks {ActivityStack mFocusedStack;boolean resumeFocusedStackTopActivityLocked() {return resumeFocusedStackTopActivityLocked(null, null, null);}boolean resumeFocusedStackTopActivityLocked(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {if (!readyToResume()) {return false;}if (targetStack != null && isFocusedStack(targetStack)) {return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);}final ActivityRecord r = mFocusedStack.topRunningActivityLocked();if (r == null || !r.isState(RESUMED)) {// 代码走这里 mFocusedStack.resumeTopActivityUncheckedLocked(null, null);} else if (r.isState(RESUMED)) {mFocusedStack.executeAppTransition(targetOptions);}return false;}
}class {boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {result = resumeTopActivityInnerLocked(prev, options);return result;}private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {// 这里面代码特别多,就是resumeActivity时所需要进行的各种各样的操作if (next.app != null && next.app.thread != null) {} else {mStackSupervisor.startSpecificActivityLocked(next, true, true);}}
}
这一段跳转了好几个类,主要的功能是对于Activity的堆栈进行各种各样的计算,然后将目前栈顶的Activity给暂停了,然后将目标Activity给Resume。
要注意一点的是,这里只是在ActivityStack中将其Resume了,这里所说的是Activity的一个封装的信息记录ActivityRecord,而不是真实的Activity,我们真实的Activity此时还没有创建出来。
5. AMS将目标页面信息发给ActivityThread
public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener,RecentTasks.Callbacks {void startSpecificActivityLocked(ActivityRecord r,boolean andResume, boolean checkConfig) {try {realStartActivityLocked(r, app, andResume, checkConfig);}}final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,boolean andResume, boolean checkConfig) throws RemoteException {try {// 准备启动Activity的事务final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,r.appToken);// 这里准备了一个LaunchActivityItem作为Callback,记住他,后面会用到clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),System.identityHashCode(r), r.info,mergedConfiguration.getGlobalConfiguration(),mergedConfiguration.getOverrideConfiguration(), r.compat,r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,r.persistentState, results, newIntents, mService.isNextTransitionForward(),profilerInfo));final ActivityLifecycleItem lifecycleItem;if (andResume) {// 这里我们是启动Activity,所以走resumelifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());} else {lifecycleItem = PauseActivityItem.obtain();}// 这里准备了一个ResumeActivityItem作为LifecycleState,记住他,后面会用到clientTransaction.setLifecycleStateRequest(lifecycleItem);// 发送这个事务mService.getLifecycleManager().scheduleTransaction(clientTransaction);}}
}class ClientLifecycleManager {void scheduleTransaction(ClientTransaction transaction) throws RemoteException {//这个东西其实就是把ActivityThread的内部类ApplicationThread取出来final IApplicationThread client = transaction.getClient(); transaction.schedule();if (!(client instanceof Binder)) {transaction.recycle();}}
这里准备了一个ClientTransaction,这个东西很关键,他就是应用进程里面的事务,然后他往里面塞了一个LaunchActivityItem一个ResumeActivityItem就扔给ActivityThread处理了。
6. ActivityThread通过反射创建Activity
6.1 scheduleTransaction
回到ActivityThread,调用scheduleTransaction,其实是调用的父类ClientTransactionHandler 的scheduleTransaction。
// 父类
public abstract class ClientTransactionHandler {void scheduleTransaction(ClientTransaction transaction) {transaction.preExecute(this);sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); //接下面的handleMessage代码}
}public final class ActivityThread extends ClientTransactionHandlerimplements ActivityThreadInternal {private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);class H extends Handler {public static final int EXECUTE_TRANSACTION = 159;public void handleMessage(Message msg) {case EXECUTE_TRANSACTION:final ClientTransaction transaction = (ClientTransaction) msg.obj;// 其实就是用线程池来执行这个ClientTransaction mTransactionExecutor.execute(transaction);if (isSystem()) {transaction.recycle();}break;}}
}public class TransactionExecutor {public void execute(ClientTransaction transaction) {executeCallbacks(transaction);executeLifecycleState(transaction);}public void executeCallbacks(ClientTransaction transaction) {final List<ClientTransactionItem> callbacks = transaction.getCallbacks();final IBinder token = transaction.getActivityToken();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);lifecycleItem.execute(mTransactionHandler, token, mPendingActions);lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);}
}
注意看,这段代码到最后,其实执行的是ClientTransaction里面的ClientTransactionItem和ActivityLifecycleItem里面的代码,那这个时候,我们就必须要回过头去,看看AMS当时在准备ClientTransaction的时候,到底往里面塞了什么东西。
6.2 ClientTransaction的内容
再次回到当时AMS准备ClientTransaction的时候,会议一下当时AMS到底塞了什么东西进去.
ClientTransaction
里面的Callbacks就是LaunchActivityItem,
里面的LifecycleStateRequest就是ResumeActivityItem
public class ClientTransaction implements Parcelable, ObjectPoolItem {private List<ClientTransactionItem> mActivityCallbacks;private ActivityLifecycleItem mLifecycleStateRequest;public List<ClientTransactionItem> getCallbacks() {return mActivityCallbacks;}public ActivityLifecycleItem getLifecycleStateRequest() {return mLifecycleStateRequest;}}// 继承ClientTransactionItem
public class LaunchActivityItem extends ClientTransactionItem {@Overridepublic void execute(ClientTransactionHandler client, IBinder token,PendingTransactionActions pendingActions) {ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,mOverrideConfig, mReferrer, mVoiceInteractor, mState, mPersistentState,mPendingResults, mPendingNewIntents, mActivityOptions, mIsForward, mProfilerInfo,client, mAssistToken, mShareableActivityToken, mLaunchedFromBubble,mTaskFragmentToken);// 这个client其实就是ActivityThread,准备了一个ActivityRecored,然后启动Activityclient.handleLaunchActivity(r, pendingActions, mDeviceId, null /* customIntent */);}
}// 继承ActivityLifecycleItem
public class ResumeActivityItem extends ActivityLifecycleItem {public void execute(ClientTransactionHandler client, ActivityClientRecord r,PendingTransactionActions pendingActions) {// 这个client其实就是ActivityThreadclient.handleResumeActivity(r, true /* finalStateRequest */, mIsForward,mShouldSendCompatFakeFocus, "RESUME_ACTIVITY");}
}
6.3 启动Activity:handleLaunchActivity
也就是走handleLaunchActivity -> performLaunchActivity的路线,Instrumentation先通过反射创建Activity对象,再用Instrumentation调用onCreate生命周期。
public final class ActivityThread extends ClientTransactionHandlerimplements ActivityThreadInternal {public Activity handleLaunchActivity(ActivityClientRecord r,PendingTransactionActions pendingActions, int deviceId, Intent customIntent) {、final Activity a = performLaunchActivity(r, customIntent);return a;}private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {try {java.lang.ClassLoader cl = appContext.getClassLoader();activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);}if (activity != null) {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.activityConfigCallback,r.assistToken, r.shareableActivityToken);r.activity = activity;if (r.isPersistable()) {mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);} else {mInstrumentation.callActivityOnCreate(activity, r.state);}}return activity ;}
}
public class Instrumentation {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 void callActivityOnCreate(Activity activity, Bundle icicle,PersistableBundle persistentState) {prePerformCreate(activity);activity.performCreate(icicle, persistentState); // 可以直接视作调用onCreatepostPerformCreate(activity);}
}public class AppComponentFactory {public @NonNull Activity instantiateActivity(@NonNull ClassLoader cl, @NonNull String className,@Nullable Intent intent)throws InstantiationException, IllegalAccessException, ClassNotFoundException {// 本质是反射return (Activity) cl.loadClass(className).newInstance();}
}
6.4 Activity切换前台:handleResumeActivity
最后一步,将Activity拖到前台,Activity启动流程结束。
public final class ActivityThread extends ClientTransactionHandlerimplements ActivityThreadInternal {public void handleResumeActivity(ActivityClientRecord r, boolean finalStateRequest,boolean isForward, boolean shouldSendCompatFakeFocus, String reason) {if (!performResumeActivity(r, finalStateRequest, reason)) {return;}//......其他逻辑......}public boolean performResumeActivity(ActivityClientRecord r, boolean finalStateRequest,String reason) {try {r.activity.performResume(r.startsNotResumed, reason); // ActivityThread调的r.state = null;r.persistentState = null;r.setState(ON_RESUME);}}
}
参考资料
码牛学院VIP课程VIP09-2021.11.26-AMS详解-David
AOSP的源码网站:http://aospxref.com/