AMS(ActivityManagerService)源码解析,Activity是如何被打开的

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,需要做多少事?

  1. 遍历data/app,遍历里面所有的App的文件夹,找到目标的包名。
  2. 把目标包的apk解压出来。
  3. 对AndroidManifest.xml进行dom解析(dom解析:把 XML 转换为 JavaScript 可存取的对象)
  4. 根据解析出来的标签用反射的方式构建MainActivity。
  5. 进入MainActivity的生命周期,展示页面。

如果每次调用startActivity都要将这五步从头到尾都走一遍,对于系统来说就非常耗时了。

而实际上Android系统是把启动的前三步交由PMS处理,在手机开机的时候就已经把data/app内所有的包都遍历过了,最后将每个app的缩略信息存在mPackages里面做了个缓存(用缓存空间来换启动时间)。

再将后两步交由AMS处理,在需要启动页面时:

  1. 应用进程通过IPC(进程间通信)的方式先将启动页面的请求发送给AMS。
  2. AMS接收到请求后,向PMS中请求对应Activity的的缩略信息。
  3. PMS将Activity信息封装到ResolveInfo后返回给AMS。
  4. AMS根据目前的堆栈情况,操作一下堆栈,原本栈顶的Activity给Pause,将目标Activity给Resume,注意此时目标Activity本体还未创建,这里操作的是Activity的缩略信息。
  5. AMS准备ClientTransaction,将启动Activity所需要的信息返回给ActivityThread。
  6. ActivityThread通过反射创建Activity,onCreate生命周期由Instrumentation调用。
  7. 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/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/26612.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

STM32学习笔记(二)--GPIO通用输入输出口详解

&#xff08;1&#xff09;配置步骤1.使用RCC开启GPIO时钟2.使用GPIO_Init函数初始化GPIO3.使用输入或输出的函数等来控制GPIO 其中涉及外设有RCC、GPIO &#xff08;2&#xff09;代码示例 案例1&#xff08;设置PA0为推挽输出&#xff09; RCC_APB2PeriphClockCmd(RCC_APB2…

使用Spring Cloud设计电商系统架构

在当今互联网高速发展的时代&#xff0c;电子商务系统成为了商家与用户互动的主要方式之一。为了能够更好地应对高并发、可扩展性、灵活性等需求&#xff0c;微服务架构逐渐成为设计电商系统的首选方案。Spring Cloud作为一个成熟的微服务框架&#xff0c;为开发人员提供了一整…

后端开发面试题4(附答案)

前言 在下首语言是golang,所以会用他作为示例。 原文参见 @arialdomartini的: Back-End Developer Interview Questions 语言相关问题 1. 告诉我你的首选语言的三个最坏的缺陷。 Golang虽然在很多方面表现出色,但它并非完美无缺,根据已有的讨论和批评,以下是Go语言被广泛…

深入浅出:面向对象软件设计原则(OOD)

目录 前言 1.单一责任原则&#xff08;SRP&#xff09; 2.开发封闭原则&#xff08;OCP&#xff09; 3.里氏替换原则&#xff08;LSP&#xff09; 4.依赖倒置原则&#xff08;DIP&#xff09; 5.接口分离原则&#xff08;ISP) 6.共同封闭原则&#xff08;CCP&#xff09…

Android替换默认的按键音

替换audio_assets.xml文件 此文件在AudioService.java被调用 <!--文件位置 /frameworks/base/core/res/res/xml/--> <audio_assets version"1.0"><group name"touch_sounds"><asset id"FX_KEY_CLICK" file"Effect…

用idea将java文件打成jar包

一、用idea将java文件打成jar包 1、在idea上选择file—Project Structure 2、Artifacts —点–JAR—From modules with dependencies 3、选择要打包的java文件 4、Build — Build Artifacts 5、找到刚才添加的Artifacts直接Build 6、生成jar包文件

【总结】项目中用过的设计模式

1.单例模式&#xff08;饿汉式 、懒汉式&#xff09; 应用场景&#xff1a;当频繁使用同一个对象&#xff0c;如配置信息、数据库连接池、线程池等时&#xff0c;使用单例模式可以避免重复创建对象&#xff0c;节省资源 线程池 2.工厂模式 应用场景&#xff1a;当需要创建的…

关于 UEditorPlus 和 TinyMCE 编辑器上线 HKCMS 插件市场的通知

亲爱的各位用户&#xff1a; 我们非常高兴地向大家宣布一个重要的消息&#xff01;UEditorPlus 和 TinyMCE 编辑器现已成功上线 HKCMS 插件市场&#xff01; UEditorPlus 以其强大的功能和便捷的操作&#xff0c;为用户提供了卓越的编辑体验。而 TinyMCE 编辑器也一直以其稳定…

C语言 | Leetcode C语言题解之第140题单词拆分II

题目&#xff1a; 题解&#xff1a; struct Trie {int ch[26];bool flag; } trie[10001];int size;void insert(char* s, int sSize) {int add 0;for (int i 0; i < sSize; i) {int x s[i] - a;if (trie[add].ch[x] 0) {trie[add].ch[x] size;memset(trie[size].ch, 0…

C语言 | Leetcode C语言题解之第139题单词拆分

题目&#xff1a; 题解&#xff1a; unsigned long long Hash(char* s, int l, int r) {unsigned long long value 0;for (int i l; i < r; i) {value value * 2333ull;value s[i] - a 1;}return value; } bool query(unsigned long long* rec, int len_rec, unsigned…

【代码随想录】【算法训练营】【第30天 1】 [322]重新安排行程 [51]N皇后

前言 思路及算法思维&#xff0c;指路 代码随想录。 题目来自 LeetCode。 day 30&#xff0c;周四&#xff0c;好难&#xff0c;会不了一点~ 题目详情 [322] 重新安排行程 题目描述 322 重新安排行程 解题思路 前提&#xff1a;…… 思路&#xff1a;回溯。 重点&…

抖音a_bogus爬虫逆向补环境

抖音a_bogus爬虫逆向补环境 写在前面 https://github.com/ShilongLee/Crawler 这是我为了学习爬虫而搭建的爬虫服务器项目&#xff0c;目标是作为一个高性能的可靠爬虫服务器为广大爬虫爱好者和安全工程师提供平台进行学习爬虫&#xff0c;了解爬虫&#xff0c;应对爬虫。现已…

Github 2024-06-13开源项目日报Top10

根据Github Trendings的统计,今日(2024-06-13统计)共有10个项目上榜。根据开发语言中项目的数量,汇总情况如下: 开发语言项目数量Python项目3非开发语言项目2Shell项目1TypeScript项目1Swift项目1PHP项目1Blade项目1JavaScript项目1从零开始构建你喜爱的技术 创建周期:2156…

C#面:C#面向对象的思想主要包括什么?

C#面向对象的思想主要包括以下几个方面&#xff1a; 封装&#xff08;Encapsulation&#xff09;&#xff1a;封装是将数据和操作数据的方法封装在一起&#xff0c;形成一个类。通过封装&#xff0c;可以隐藏类的内部实现细节&#xff0c;只暴露必要的接口给外部使用。这样可以…

如何在浏览器书签栏设置2个书签实现一键到达网页顶部和底部

本次设置浏览器为&#xff1a;Chrome浏览器&#xff08;其他浏览器可自行测试&#xff09; 1&#xff0c;随便收藏一个网页到浏览器书签栏 2&#xff0c;右键这个书签 3&#xff0c;修改 4&#xff0c;修改名称 5&#xff0c;修改网址&#xff1a; javascript:(function(…

arm64电源管理之PSCI

PSCIPower State Coordination Interface功耗状态协同接口SCPISystem Control and Power Interface系统控制和电源接口SCMISystem Control and Management Interface系统控制和管理接口SMCCCSMC Calling ConventionSMC调用约定 scpi&#xff1b;通过mailbox核间通信&#xff0c…

借助Historian Connector + TDengine,打造工业创新底座

在工业自动化的领域中&#xff0c;数据的采集、存储和分析是实现高效决策和操作的基石。AVEVA Historian (原 Wonderware Historian) 作为领先的工业实时数据库&#xff0c;专注于收集和存储高保真度的历史工艺数据。与此同时&#xff0c;TDengine 作为一款专为时序数据打造的高…

FullCalendar日历组件集成实战(11)

背景 有一些应用系统或应用功能&#xff0c;如日程管理、任务管理需要使用到日历组件。虽然Element Plus也提供了日历组件&#xff0c;但功能比较简单&#xff0c;用来做数据展现勉强可用。但如果需要进行复杂的数据展示&#xff0c;以及互动操作如通过点击添加事件&#xff0…

怎么防止源代码泄露?9种方法教会你!

怎么防止源代码泄露&#xff1f;首先要了解员工可以通过哪些方式将源代码传输出去&#xff01; 物理方法&#xff1a; — 网线直连&#xff0c;即把网线从墙上插头拔下来&#xff0c;然后和一个非受控电脑直连; — winPE启动&#xff0c;通过光盘或U盘的winPE启动&#xff0c;甚…

Maven Dependency Tree:深入理解你的项目依赖

在Java开发领域&#xff0c;Apache Maven作为一款强大的构建和项目管理工具&#xff0c;广泛应用于自动化构建、依赖管理和项目报告生成等场景。当处理大型项目时&#xff0c;管理依赖关系变得尤为关键&#xff0c;因为不透明或冗余的依赖可能导致各种问题&#xff0c;从构建失…