当前位置:   article > 正文

Activity启动流程(Android 10源码分析)_android activity启动过程一:从intent到activity创建

android activity启动过程一:从intent到activity创建

目录

一、启动进程start目标Activity

二、进入AMS进程启动目标Activity

三、进入APP进程创建Activity

四、创建新的目标进程

五、进入新创建的目标APP进程

六、进入AMS进程执行Application初始化和启动Activity

七、回到目标APP进程初始化Application

八、从AMS进程启动Activity

九、总结


流程图:

下面的源码分析,将按照上图的流程图一步一步分析

一、启动进程start目标Activity

启动Activity先从startActivity开始,点进startActivity进入ContextWrapper类中,↓

  1. @Override
  2. public void startActivity(Intent intent) {
  3. mBase.startActivity(intent);
  4. }

上图中mBase对象是Context,Context的实现类为ContextImpl,进入ContextImpl的startActivity方法看下,↓

  1. @Override
  2. public void startActivity(Intent intent, Bundle options) {
  3. final int targetSdkVersion = getApplicationInfo().targetSdkVersion;
  4. //mMainThread为ActivityThread,获取的getInstrumentation()为Instrumentation
  5. mMainThread.getInstrumentation().execStartActivity(
  6. getOuterContext(), mMainThread.getApplicationThread(), null,
  7. (Activity) null, intent, -1, options);
  8. }

上图中代码最后一句为重点,已经加了说明,就是调用了 Instrumentation 的 execStartActivity() 方法,Instrumentation为仪表盘,管理着Activity和Application的生命周期,一个进程对应着一个Instrumentation。接着进入Instrumentation类看下,↓

  1. public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target,
  2. Intent intent, int requestCode, Bundle options) {
  3. IApplicationThread whoThread = (IApplicationThread) contextThread;
  4. //......部分代码省略
  5. try {
  6. intent.migrateExtraStreamToClipData();
  7. intent.prepareToLeaveProcess(who);
  8. //重点:这里获取了ATMS代理对象IActivityTaskManager,拿到ATMS代理对象就可以跨进程调用AMS的startActivity
  9. int result = ActivityTaskManager.getService()
  10. .startActivity(whoThread, who.getBasePackageName(), intent,
  11. intent.resolveTypeIfNeeded(who.getContentResolver()),
  12. token, target != null ? target.mEmbeddedID : null,
  13. requestCode, 0, null, options);
  14. checkStartActivityResult(result, intent);
  15. }
  16. return null;
  17. }

上图中加了注释处通过ActivityTaskManager.getService()获取了ATMS代理对象IActivityTaskManager,该IActivityTaskManager代理对象是一个接口,实现类为ActivityTaskManagerService,获取后即可调用ActivityTaskManagerService(ATMS)的startActivity方法,这里就是跨进程操作AMS的入口(第一次跨进程)。

注意:该ActivityTaskManagerService(ATMS)和ActivityManagerService(AMS)同属一个进程,他们之间的通信交互使用的是handler,该类是在10.0开始新加的一个类,这一处代码和10.0之前的有所不同。接下来就进入AMS进程中ATMS类的startActivity方法继续分析。↓

二、进入AMS进程启动目标Activity

  1. int startActivityAsUser(IApplicationThread caller, String callingPackage,
  2. Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
  3. int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
  4. boolean validateIncomingUser) {
  5. userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
  6. Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
  7. //看这里
  8. return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
  9. .setCaller(caller)
  10. .setCallingPackage(callingPackage)
  11. .setResolvedType(resolvedType)
  12. .setResultTo(resultTo)
  13. .setResultWho(resultWho)
  14. .setRequestCode(requestCode)
  15. .setStartFlags(startFlags)
  16. .setProfilerInfo(profilerInfo)
  17. .setActivityOptions(bOptions)
  18. .setMayWait(userId)
  19. .execute();
  20. }

分析上图代码,在ATMS类中,经过了多个方法调用,最终走到startActivityAsUser方法里,在这个方法return中getActivityStartController().obtainStarter方法返回的是一个ActivityStarter对象,然后调用了该对象的execute()方法,接着进入ActivityStarter类中继续分析。↓

  1. int execute() {
  2. try {
  3. if (mRequest.mayWait) {
  4. return startActivityMayWait(mRequest.caller, mRequest.callingUid,
  5. mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
  6. mRequest.intent, mRequest.resolvedType,
  7. mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
  8. mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
  9. mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
  10. mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
  11. mRequest.inTask, mRequest.reason,
  12. mRequest.allowPendingRemoteAnimationRegistryLookup,
  13. mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
  14. }
  15. } finally {
  16. onExecutionComplete();
  17. }
  18. }

上图中,ActivityStarter的execute()方法中,mRequest.mayWait返回为true,设置为true的地方在上上图中的setMayWait(userId)处,因此这里会走startActivityMayWait()方法,继续分析startActivityMayWait()方法。↓

  1. private int startActivityMayWait(IApplicationThread caller, int callingUid,
  2. String callingPackage, int requestRealCallingPid, int requestRealCallingUid,......) {
  3. //.......省略部分代码
  4. final ActivityRecord[] outRecord = new ActivityRecord[1];
  5. int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
  6. voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
  7. callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
  8. ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
  9. allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
  10. allowBackgroundActivityStart);
  11. Binder.restoreCallingIdentity(origId);
  12. //.......省略部分代码
  13. }

上图中,在startActivityMayWait()方法调用了startActivity()方法,继续分析startActivity()方法。↓

  1. private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
  2. String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,......) {
  3. //.......省略部分代码
  4. mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
  5. aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
  6. callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
  7. options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
  8. inTask, allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
  9. allowBackgroundActivityStart);
  10. //.......省略部分代码
  11. return getExternalResult(mLastStartActivityResult);
  12. }

上图中,在startActivity()方法里调用了名称相同但参数个数不同的startActivity()方法,继续分析startActivity()方法。↓

  1. private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,String resolvedType,......) {
  2. //......省略部分代码
  3. final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
  4. true /* doResume */, checkedOptions, inTask, outActivity, restrictedBgActivity);
  5. mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outActivity[0]);
  6. return res;
  7. }
  8. }

上图中,这段代码很长,但只需要找到这个方法里最末处,在这里调用了一个startActivity(),又是一个名称相同但参数个数不同的startActivity()方法,继续进入分析。↓

  1. private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
  2. IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
  3. int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
  4. ActivityRecord[] outActivity, boolean restrictedBgActivity) {
  5. int result = START_CANCELED;
  6. final ActivityStack startedActivityStack;
  7. try {
  8. mService.mWindowManager.deferSurfaceLayout();
  9. result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
  10. startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
  11. }
  12. }

上图中,在startActivity()方法里调用了startActivityUnchecked(),进入startActivityUnchecked()方法继续分析。↓

  1. private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
  2. IVoiceInteractionSession voiceSession,......) {
  3. //计算启动 Activity 的 Flag 值
  4. computeLaunchingTaskFlags();
  5. //......省略部分代码
  6. //处理 Task 和 Activity 的进栈操作
  7. mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,mOptions);
  8. if (mDoResume) {
  9. final ActivityRecord topTaskActivity = mStartActivity.getTaskRecord().topRunningActivityLocked();
  10. if (!mTargetStack.isFocusable() || (topTaskActivity != null && topTaskActivity.mTaskOverlay
  11. && mStartActivity != topTaskActivity)) {
  12. mTargetStack.ensureActivitiesVisibleLocked(mStartActivity, 0, !PRESERVE_WINDOWS);
  13. mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
  14. } else {
  15. if (mTargetStack.isFocusable()
  16. && !mRootActivityContainer.isTopDisplayFocusedStack(mTargetStack)) {
  17. mTargetStack.moveToFront("startActivityUnchecked");
  18. }
  19. //启动栈中顶部的 Activity
  20. mRootActivityContainer.resumeFocusedStacksTopActivities(mTargetStack, mStartActivity, mOptions);
  21. }
  22. }
  23. //......省略部分代码
  24. }

上图中,关键代码加了注释,最后进入到RootActivityContainer类的resumeFocusedStacksTopActivities()方法中,继续分析。↓

  1. boolean resumeFocusedStacksTopActivities(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
  2. if (!mStackSupervisor.readyToResume()) {
  3. return false;
  4. }
  5. boolean result = false;
  6. if (targetStack != null && (targetStack.isTopStackOnDisplay()|| getTopDisplayFocusedStack() == targetStack)) {
  7. result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
  8. }
  9. //......省略部分代码
  10. return result;
  11. }

上图中,这里调用了ActivityStack类的resumeTopActivityUncheckedLocked()方法,该类是Activity在AMS的栈管理,用来记录已经启动的Activity的先后关系,状态信息等,通过ActivityStack决定是否需要启动新的进程。进入resumeTopActivityUncheckedLocked()方法继续分析。↓

  1. boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
  2. if (mInResumeTopActivity) {
  3. return false;
  4. }
  5. boolean result = false;
  6. try {
  7. mInResumeTopActivity = true;
  8. result = resumeTopActivityInnerLocked(prev, options);
  9. final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
  10. if (next == null || !next.canTurnScreenOn()) {
  11. checkReadyForSleep();
  12. }
  13. }
  14. return result;
  15. }

上图中,注意resumeTopActivityInnerLocked()方法,进入查看该方法。↓

  1. private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
  2. //......省略部分代码
  3. if (next.attachedToProcess()) {
  4. //......省略部分代码
  5. } else {
  6. if (!next.hasBeenLaunched) {
  7. next.hasBeenLaunched = true;
  8. } else {
  9. if (SHOW_APP_STARTING_PREVIEW) {
  10. next.showStartingWindow(null /* prev */, false /* newTask */,
  11. false /* taskSwich */);
  12. }
  13. }
  14. mStackSupervisor.startSpecificActivityLocked(next, true, true);
  15. }
  16. return true;
  17. }

上图中,在代码最末尾处调用了startSpecificActivityLocked()方法,点进去查看。↓

  1. void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
  2. // Is this activity's application already running?
  3. //根据进程名和进程id判断目标进程是否已经创建,如果没有则代表进程未创建
  4. final WindowProcessController wpc = mService.getProcessController(r.processName, r.info.applicationInfo.uid);
  5. boolean knownToBeDead = false;
  6. //如果进程已经创建,这里直接调用realStartActivityLocked去启动Activity
  7. if (wpc != null && wpc.hasThread()) {
  8. try {
  9. realStartActivityLocked(r, wpc, andResume, checkConfig);
  10. return;
  11. } catch (RemoteException e) {
  12. }
  13. knownToBeDead = true;
  14. }
  15. if (getKeyguardController().isKeyguardLocked()) {
  16. r.notifyUnknownVisibilityLaunched();
  17. }
  18. try {
  19. //走到这里说明目标进程未创建,这里使用handler发送消息给ActivityManagerService类,让AMS创建一个新的进程
  20. final Message msg = PooledLambda.obtainMessage(
  21. ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
  22. r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
  23. mService.mH.sendMessage(msg);
  24. }
  25. }

上图中,进入到ActivityStackSupervisor的startSpecificActivityLocked()方法中,ActivityStackSupervisor是ActivityStack的管理类,在startSpecificActivityLocked()方法中,先去判断目标进程是否已经创建,已经创建的话就去启动Activity,否则使用handler发送消息给ActivityManagerService,即AMS,让AMS去创建一个新的进程出来,到这里就有两条分支,一个是去启动Activity,另一个是去创建进程,先看启动Activity这条线,后面再分析创建进程。接下来进入realStartActivityLocked()方法。↓

  1. boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
  2. boolean andResume, boolean checkConfig) throws RemoteException {
  3. //......省略部分代码
  4. //创建一个Activity启动事务,同时传入proc.getThread(),该对象实际为ApplicationThread
  5. final ClientTransaction clientTransaction = ClientTransaction.obtain(proc.getThread(), r.appToken);
  6. final DisplayContent dc = r.getDisplay().mDisplayContent;
  7. //把LaunchActivityItem加入事务中,后面会调用到该类的handleLaunchActivity()方法
  8. clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
  9. System.identityHashCode(r), r.info,
  10. mergedConfiguration.getGlobalConfiguration(),
  11. mergedConfiguration.getOverrideConfiguration(), r.compat,
  12. r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
  13. r.icicle, r.persistentState, results, newIntents,
  14. dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
  15. r.assistToken));
  16. final ActivityLifecycleItem lifecycleItem;
  17. if (andResume) {
  18. lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
  19. } else {
  20. lifecycleItem = PauseActivityItem.obtain();
  21. }
  22. clientTransaction.setLifecycleStateRequest(lifecycleItem);
  23. //在这里启动事务
  24. Service.getLifecycleManager().scheduleTransaction(clientTransaction);
  25. //......省略部分代码
  26. }

上图中,重点代码做了注释,可以看到,在这段代码中,主要是创建事务,同时传入ApplicationThread,而ApplicationThread继承于Binder,这里传入目的主要后面用来跟目标APP进程通信。然后就是启动事务,mService.getLifecycleManager()方法返回的是ClientLifecycleManager对象,接下来继续分析ClientLifecycleManager的scheduleTransaction()方法,↓

  1. void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
  2. final IApplicationThread client = transaction.getClient();
  3. transaction.schedule();
  4. if (!(client instanceof Binder)) {
  5. transaction.recycle();
  6. }
  7. }

上图中,在ClientLifecycleManager类的scheduleTransaction()方法中可以明确看到,这里实际调用了ClientTransaction对象的schedule()方法,进入到ClientTransaction的schedule()方法继续分析。↓

  1. private IApplicationThread mClient;
  2. public void schedule() throws RemoteException {
  3. mClient.scheduleTransaction(this);
  4. }

上图中,在ClientTransaction类的schedule()方法里,又调用了mClient的scheduleTransaction()方法,而这个mClient实际就是在上上上图中创建Activity启动事务时传入的ApplicationThread对象,也就是说,这里开始从AMS进程跨进程调用ApplicationThread 的scheduleTransaction()方法(第二次跨进程),接下来进入到 ApplicationThread 的 scheduleTransaction() 方法中分析。

三、进入APP进程创建Activity

  1. private class ApplicationThread extends IApplicationThread.Stub {
  2. @Override
  3. public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
  4. ActivityThread.this.scheduleTransaction(transaction);
  5. }
  6. }

上图中,先介绍下ApplicationThread,它是ActivityThread的内部类,继承于IApplicationThread.Stub,而IApplicationThread.Stub又继承于Binder,所以本质还是一个Binder,用来在ActivityThread和AMS之间通信。继续分析scheduleTransaction()方法,这里又调用了ActivityThread的scheduleTransaction()方法,点进去分析。↓

  1. void scheduleTransaction(ClientTransaction transaction) {
  2. transaction.preExecute(this);
  3. sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
  4. }

上图中,走到了ActivityThread的父类ClientTransactionHandler中的scheduleTransaction()方法,在这个方法里发送handler消息H.EXECUTE_TRANSACTION,并且 Message 中的 obj 就是启动 Activity 的事务对象。而这个 Handler 的具体实现是 ActivityThread 中的 H 对象,接着找到接收handle消息的地方继续分析。↓

  1. class H extends Handler {
  2. public static final int EXECUTE_TRANSACTION = 159;
  3. public void handleMessage(Message msg) {
  4. switch (msg.what) {
  5. case EXECUTE_TRANSACTION:
  6. final ClientTransaction transaction = (ClientTransaction) msg.obj;
  7. mTransactionExecutor.execute(transaction);
  8. if (isSystem()) {
  9. transaction.recycle();
  10. }
  11. break;
  12. }
  13. }
  14. }

上图中,接收handler消息的地方定义在ActivityThread类中,在这里,又调用了TransactionExecutor的execute()方法,点进去继续分析。↓

  1. public void execute(ClientTransaction transaction) {
  2. //......省略部分代码
  3. executeCallbacks(transaction);
  4. executeLifecycleState(transaction);
  5. mPendingActions.clear();
  6. if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
  7. }

上图中,点进去executeCallbacks(transaction)方法继续分析。↓

  1. public void executeCallbacks(ClientTransaction transaction) {
  2. final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
  3. //......省略部分代码
  4. final int size = callbacks.size();
  5. for (int i = 0; i < size; ++i) {
  6. final ClientTransactionItem item = callbacks.get(i);
  7. if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Resolving callback: " + item);
  8. final int postExecutionState = item.getPostExecutionState();
  9. final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
  10. item.getPostExecutionState());
  11. if (closestPreExecutionState != UNDEFINED) {
  12. cycleToPath(r, closestPreExecutionState, transaction);
  13. }
  14. //item的类型其实就是LaunchActivityItem
  15. item.execute(mTransactionHandler, token, mPendingActions);
  16. item.postExecute(mTransactionHandler, token, mPendingActions);
  17. //......省略部分代码
  18. }
  19. }

上图中,在 executeCallback()方法中,会遍历事务中的 callback 并执行 execute 方法,这些 callbacks 是在前面创建Activity启动事务时添加的。↓

  1. boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
  2. boolean andResume, boolean checkConfig) throws RemoteException {
  3. //......省略部分代码
  4. //创建一个Activity启动事务,同时传入proc.getThread(),该对象实际为ApplicationThread
  5. final ClientTransaction clientTransaction = ClientTransaction.obtain(
  6. proc.getThread(), r.appToken);
  7. final DisplayContent dc = r.getDisplay().mDisplayContent;
  8. //把LaunchActivityItem加入事务中,后面会调用到该类的handleLaunchActivity()方法
  9. clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
  10. System.identityHashCode(r), r.info,
  11. mergedConfiguration.getGlobalConfiguration(),
  12. mergedConfiguration.getOverrideConfiguration(), r.compat,
  13. r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
  14. r.icicle, r.persistentState, results, newIntents,
  15. dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
  16. r.assistToken));
  17. //......省略部分代码
  18. }

上图中,添加的callback对象其实就是LaunchActivityItem类型的对象,所以在上上图中,item.execute(mTransactionHandler, token, mPendingActions),就是调用了LaunchActivityItem类的execute()方法,进入LaunchActivityItem类的execute()方法继续分析。↓

  1. @Override
  2. public void execute(ClientTransactionHandler client, IBinder token,
  3. PendingTransactionActions pendingActions) {
  4. ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
  5. mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,mPendingResults, mPendingNewIntents, mIsForward,mProfilerInfo, client, mAssistToken);
  6. //注意这里
  7. client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
  8. }

上图中,在LaunchActivityItem类的execute()方法里,调用了client.handleLaunchActivity()方法,这里的client为ClientTransactionHandler类型,而ClientTransactionHandler的实现类是ActivityThread,所以这里又回到了ActivityThread类,并调用了handleLaunchActivity()方法,接着进入handleLaunchActivity()方法继续分析。↓

  1. public Activity handleLaunchActivity(ActivityClientRecord r,
  2. PendingTransactionActions pendingActions, Intent customIntent) {
  3. //......省略部分代码
  4. //初始化 Activity 的 WindowManager,每一个 Activity 都会对应一个“窗口”
  5. WindowManagerGlobal.initialize();
  6. //重点
  7. final Activity a = performLaunchActivity(r, customIntent);
  8. //......省略部分代码
  9. return a;
  10. }

上图中,通过调用performLaunchActivity()方法创建并显示一个Activity,进入performLaunchActivity()方法继续分析。↓

  1. private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
  2. //......省略部分代码
  3. ContextImpl appContext = createBaseContextForActivity(r);
  4. Activity activity = null;
  5. try {
  6. //通过反射创建目标 Activity 对象
  7. java.lang.ClassLoader cl = appContext.getClassLoader();
  8. activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
  9. StrictMode.incrementExpectedActivityCount(activity.getClass());
  10. }
  11. try {
  12. Application app = r.packageInfo.makeApplication(false, mInstrumentation);
  13. if (activity != null) {
  14. //创建window
  15. Window window = null;
  16. if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
  17. window = r.mPendingRemoveWindow;
  18. r.mPendingRemoveWindow = null;
  19. r.mPendingRemoveWindowManager = null;
  20. }
  21. //调用 attach 方法建立 Activity 与 Context 之间的联系,创建 PhoneWindow 对象,并与 Activity 进行关联操作
  22. activity.attach(appContext, this, getInstrumentation(), r.token,
  23. r.ident, app, r.intent, r.activityInfo, title, r.parent,
  24. r.embeddedID, r.lastNonConfigurationInstances, config,
  25. r.referrer, r.voiceInteractor, window, r.configCallback,
  26. r.assistToken);
  27. int theme = r.activityInfo.getThemeResource();
  28. if (theme != 0) {
  29. //设置主题
  30. activity.setTheme(theme);
  31. }
  32. activity.mCalled = false;
  33. //通过 Instrumentation 最终调用 Activity 的 onCreate 方法
  34. if (r.isPersistable()) {
  35. mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
  36. } else {
  37. mInstrumentation.callActivityOnCreate(activity, r.state);
  38. }
  39. r.activity = activity;
  40. }
  41. }
  42. return activity;
  43. }

上图中,主要代码已经加了注释,主要做了以下这些事情,

  1. 使用反射创建目标 Activity 对象;
  2. 创建PhoneWindow 对象,
  3. 调用attach方法绑定Activity;
  4. 调用 Activity 的 onCreate 方法

步骤4中,是通过Instrumentation来调用的Activity的onCreate()方法,点进去看下callActivityOnCreate()方法。↓

  1. public void callActivityOnCreate(Activity activity, Bundle icicle) {
  2. prePerformCreate(activity);
  3. activity.performCreate(icicle);
  4. postPerformCreate(activity);
  5. }

上图中,可以看到调用了Activity的performCreate()方法,进入performCreate()方法查看。↓

  1. final void performCreate(Bundle icicle, PersistableBundle persistentState) {
  2. //在这里调用了Activity的生命周期onCreate方法
  3. if (persistentState != null) {
  4. onCreate(icicle, persistentState);
  5. } else {
  6. onCreate(icicle);
  7. }
  8. //......省略部分代码
  9. }
  10. protected void onCreate(@Nullable Bundle savedInstanceState) {
  11. //......省略部分代码
  12. }

至此,目标Activity已经被成功创建,并开始了生命周期的回调;

四、创建新的目标进程

在文章当中分析startSpecificActivityLocked()方法的时候,说到该方法里会先判断目标进程是否已经创建,如果已经创建就走启动Activity流程,如果没有,就去创建进程,接下来就分析创建进程,并在创建进程后启动Activity这个过程,重新回到startSpecificActivityLocked()方法。↓

  1. void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
  2. //根据进程名和进程id判断目标进程是否已经创建,如果没有则代表进程未创建
  3. final WindowProcessController wpc =mService.getProcessController(r.processName, r.info.applicationInfo.uid);
  4. boolean knownToBeDead = false;
  5. //如果进程已经创建,这里直接调用realStartActivityLocked去启动Activity
  6. if (wpc != null && wpc.hasThread()) {
  7. try {
  8. realStartActivityLocked(r, wpc, andResume, checkConfig);
  9. return;
  10. }
  11. }
  12. //......省略部分代码
  13. try {
  14. //走到这里说明目标进程未创建,这里使用handler发送消息给ActivityManagerService类,让AMS创建一个新的进程
  15. final Message msg = PooledLambda.obtainMessage(
  16. ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
  17. r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
  18. mService.mH.sendMessage(msg);
  19. }
  20. }

上图中,startSpecificActivityLocked()方法定义在ActivityStackSupervisor类中。

1、在obtainMessage()方法中,可以看到调用了ActivityManagerInternal类的startProcess()方法,ActivityManagerInternal是一个抽象类,它的实现类在AMS中,即LocalService类。

2、通过mService.mH.sendMessage(msg)发送handle消息告诉AMS类去执行startProcess()方法,这里mService为ATMS对象,mH是定义在ATMS类中的一个handler。

接着进入AMS中,找到startProcess()方法继续分析。↓

  1. public void startProcess(String processName, ApplicationInfo info,boolean
  2. knownToBeDead, String hostingType, ComponentName hostingName) {
  3. try {
  4. synchronized (ActivityManagerService.this) {
  5. startProcessLocked(processName, info, knownToBeDead, 0 ,new HostingRecord(hostingType, hostingName),false , false ,true);
  6. }
  7. }
  8. }

上图中,只做了一件事,使用同步锁调用了startProcessLocked()方法,进入该方法继续分析。↓

  1. final ProcessRecord startProcessLocked(String processName,ApplicationInfo info, boolean knownToBeDead,
  2. int intentFlags,HostingRecord hostingRecord, ......) {
  3. return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
  4. hostingRecord, allowWhileBooting, isolated, 0, keepIfLarge,
  5. null, null, null,null);
  6. }

上图中,点击startProcessLocked()方法继续分析。↓

  1. final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
  2. boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord,......) {
  3. //......省略部分代码
  4. final boolean success = startProcessLocked(app, hostingRecord, abiOverride);
  5. checkSlow(startTime, "startProcess: done starting proc!");
  6. return success ? app : null;
  7. }

上图中,调用了相同名称参数个数不同的startProcessLocked()方法,进入继续分析。↓

  1. final boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
  2. String abiOverride) {
  3. return startProcessLocked(app, hostingRecord,
  4. false /* disableHiddenApiChecks */, false /* mountExtStorageFull */, abiOverride);
  5. }

上图中,又调用了相同名称参数个数不同的startProcessLocked()方法,进入继续分析。↓

  1. boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
  2. boolean disableHiddenApiChecks, boolean mountExtStorageFull,String abiOverride) {
  3. //......省略部分代码
  4. try {
  5. //......省略部分代码
  6. //创建好新的进程后会立即启动ActivityThread,进入main入口,这里传入ActivityThread路径
  7. final String entryPoint = "android.app.ActivityThread";
  8. return startProcessLocked(hostingRecord, entryPoint, app, uid, gids,
  9. runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
  10. startTime);
  11. } catch (RuntimeException e) {
  12. //......省略部分代码
  13. return false;
  14. }
  15. }

上图中,又调用了相同名称参数个数不同的startProcessLocked()方法,同时传入了ActivityThread的路径,因为在新的进程创建完成后,会立即启动ActivityThread的main入口,进入startProcessLocked()方法继续分析。↓

  1. boolean startProcessLocked(HostingRecord hostingRecord,String entryPoint,ProcessRecord app, int uid, int[] gids,......) {
  2. //......省略部分代码
  3. //是否异步开启进程,默认为true
  4. if (mService.mConstants.FLAG_PROCESS_START_ASYNC) {
  5. mService.mProcStartHandler.post(() -> {
  6. try {
  7. //注意这里
  8. final Process.ProcessStartResult startResult = startProcess(app.hostingRecord,
  9. entryPoint, app, app.startUid, gids, runtimeFlags, mountExternal,
  10. app.seInfo, requiredAbi, instructionSet, invokeWith, app.startTime);
  11. synchronized (mService) {
  12. handleProcessStartedLocked(app, startResult, startSeq);
  13. }
  14. } catch (RuntimeException e) {
  15. //......省略部分代码
  16. }
  17. });
  18. return true;
  19. }
  20. }

上图中,使用异步方式调用了startProcess()方法,进去该方法分析。↓

  1. private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
  2. ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
  3. String seInfo, String requiredAbi, String instructionSet, String invokeWith,
  4. long startTime) {
  5. try {
  6. final Process.ProcessStartResult startResult;
  7. if (hostingRecord.usesWebviewZygote()) {
  8. //......省略部分代码
  9. } else if (hostingRecord.usesAppZygote()) {
  10. //......省略部分代码
  11. } else {
  12. startResult = Process.start(entryPoint,
  13. app.processName, uid, uid, gids, runtimeFlags, mountExternal,
  14. app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
  15. app.info.dataDir, invokeWith, app.info.packageName,
  16. new String[] {PROC_START_SEQ_IDENT + app.startSeq});
  17. }
  18. checkSlow(startTime, "startProcess: returned from zygote!");
  19. return startResult;
  20. }
  21. }

上图中,走到了else里面的代码,为什么是else,在ATMS发送handler消息告诉AMS创建进程时,调用了AMS的内部类LocalService中的startProcess()方法,在该方法里new了一个HostingRecord两个参数的构造参数的对象,所以默认进程类型是“REGULAR_ZYGOTE”。在看Process.start()方法,这里开始调用了Process的创建,点进去Process的start()方法继续分析。↓

  1. public static ProcessStartResult start(@NonNull final String processClass,
  2. @Nullable final String niceName,
  3. int uid, int gid, @Nullable int[] gids,
  4. int runtimeFlags,
  5. int mountExternal,
  6. int targetSdkVersion,
  7. @Nullable String seInfo,
  8. @NonNull String abi,
  9. @Nullable String instructionSet,
  10. @Nullable String appDataDir,
  11. @Nullable String invokeWith,
  12. @Nullable String packageName,
  13. @Nullable String[] zygoteArgs) {
  14. return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
  15. runtimeFlags, mountExternal, targetSdkVersion, seInfo,
  16. abi, instructionSet, appDataDir, invokeWith, packageName,
  17. /*useUsapPool=*/ true, zygoteArgs);
  18. }

上图中,这里又调用了ZYGOTE_PROCESS.start()方法,ZYGOTE_PROCESS就是系统中的Zygote进程,Android中所有的App进程都是由Zygote进程fork生成的,包括SystemServer进程,Zygote是所有Java进程的父进程,到这里就开始了目标APP进程的创建了,目标APP进程创建成功,会立即启动ActivityThread线程,并进入它的main方法。接下来进入ActivityThread的main入口进行分析。↓

五、进入新创建的目标APP进程

  1. public static void main(String[] args) {
  2. //......省略部分代码
  3. Looper.prepareMainLooper();
  4. //......省略部分代码
  5. ActivityThread thread = new ActivityThread();
  6. thread.attach(false, startSeq);
  7. Looper.loop();
  8. }

上图中,又回到了目标APP进程中,这里又完成了一次跨进程,在目标APP进程的ActivityThread的Main入口,主要做了两件事,一是创建MainLooper,并loop起来。二是调用ActivityThread的attach()方法,这个方法很重要,点进去分析。↓

  1. private void attach(boolean system, long startSeq) {
  2. if (!system) {
  3. //获取AMS代理,然后调用AMS的attachApplication方法
  4. final IActivityManager mgr = ActivityManager.getService();
  5. try {
  6. mgr.attachApplication(mAppThread, startSeq);
  7. } catch (RemoteException ex) {
  8. throw ex.rethrowFromSystemServer();
  9. }
  10. //......省略部分代码
  11. } else {
  12. //......省略部分代码
  13. }
  14. }

上图中,在attach()方法中,获取了AMS的代理,然后跨进程调用了AMS的attachApplication()方法,同时传入了ApplicationThread对象,这里又是一次跨进程,进入AMS的attachApplication()方法继续分析。↓

六、进入AMS进程执行Application初始化和启动Activity

  1. private final boolean attachApplicationLocked(IApplicationThread thread,int pid, int callingUid, long startSeq) {
  2. //......省略部分代码
  3. try {
  4. if (app.isolatedEntryPoint != null) {
  5. //......省略部分代码
  6. } else if (instr2 != null) {
  7. //调用ApplicationThread的bindApplication去初始化Application
  8. thread.bindApplication(processName, appInfo, providers,
  9. instr2.mClass,
  10. profilerInfo, instr2.mArguments,
  11. instr2.mWatcher,
  12. instr2.mUiAutomationConnection, testMode,
  13. mBinderTransactionTrackingEnabled, enableTrackAllocation,
  14. isRestrictedBackupMode || !normalMode, app.isPersistent(),
  15. new Configuration(app.getWindowProcessController().getConfiguration()),
  16. app.compat, getCommonServicesLocked(app.isolated),
  17. mCoreSettingsObserver.getCoreSettingsLocked(),
  18. buildSerial, autofillOptions, contentCaptureOptions);
  19. }
  20. } catch (Exception e) {
  21. //......省略部分代码
  22. return false;
  23. }
  24. //......省略部分代码
  25. if (normalMode) {
  26. try {
  27. //去启动Activity
  28. didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
  29. } catch (Exception e) {
  30. Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
  31. badApp = true;
  32. }
  33. }
  34. }

上图中,主要做了两件事:

1、调用了ApplicationThread的bindApplication()方法去初始化Application,又是一次跨进程调用。

2、通过ATMS去启动目标Activity。

先来分析ApplicationThread的bindApplication()方法。↓

七、回到目标APP进程初始化Application

  1. public final void bindApplication(String processName, ApplicationInfo appInfo,...) {
  2. //......省略部分代码
  3. AppBindData data = new AppBindData();
  4. //......省略部分代码
  5. sendMessage(H.BIND_APPLICATION, data);
  6. }

上图中,在ApplicationThread中的bindApplication()方法里最终发送了一个H.BIND_APPLICATION消息,接着查看handler接收消息的地方。↓

  1. class H extends Handler {
  2. public static final int BIND_APPLICATION = 110;
  3. //......省略部分代码
  4. public void handleMessage(Message msg) {
  5. switch (msg.what) {
  6. case BIND_APPLICATION:
  7. AppBindData data = (AppBindData)msg.obj;
  8. handleBindApplication(data);
  9. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  10. break;
  11. }
  12. }

上图中,又调用了handleBindApplication(data)方法,继续进入分析。↓

  1. private void handleBindApplication(AppBindData data) {
  2. //......省略部分代码
  3. if (ii != null) {
  4. final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo, appContext.getClassLoader(), false, true, false);
  5. final ContextImpl instrContext = ContextImpl.createAppContext(this, pi, appContext.getOpPackageName());
  6. try {
  7. final ClassLoader cl = instrContext.getClassLoader();
  8. //创建仪表盘
  9. mInstrumentation = (Instrumentation) cl.loadClass(data.instrumentationName.getClassName()).newInstance();
  10. }
  11. //初始化仪表盘
  12. mInstrumentation.init(this, instrContext, appContext, component, data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
  13. }
  14. //......省略部分代码
  15. Application app;
  16. try {
  17. //创建Application
  18. app = data.info.makeApplication(data.restrictedBackupMode, null);
  19. //......省略部分代码
  20. try {
  21. mInstrumentation.onCreate(data.instrumentationArgs);
  22. }
  23. try {
  24. //调用Application的onCreate方法
  25. mInstrumentation.callApplicationOnCreate(app);
  26. }
  27. }
  28. }

上图中,主要做了三件事:

1、创建仪表盘。

2、使用LoadedApk创建一个Application,不过最终还是使用的仪表盘利用反射创建的Application类。

3、使用仪表盘初始化Application,点击去可以查看下mInstrumentation.callApplicationOnCreate()方法。↓

  1. public void callApplicationOnCreate(Application app) {
  2. app.onCreate();
  3. }

到此,Application即初始化完成。

八、从AMS进程启动Activity

在步骤六中,有两步,第一步初始化Application,这里已经完成,还有一步去ATMS启动Activity,先看下之前的代码。↓

  1. private final boolean attachApplicationLocked(IApplicationThread thread,int pid, int callingUid, long startSeq) {
  2. //......省略部分代码
  3. if (normalMode) {
  4. try {
  5. //去启动Activity
  6. didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
  7. } catch (Exception e) {
  8. Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
  9. badApp = true;
  10. }
  11. }
  12. }

上图中,是在AMS的attachApplicationLocked()方法里,mAtmInternal是一个ActivityTaskManagerInternal对象,它是一个抽象类,由LocalService以AMS内部类形式实现,进入attachApplication()方法继续查看。↓

  1. final class LocalService extends ActivityTaskManagerInternal {
  2. public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
  3. synchronized (mGlobalLockWithoutBoost) {
  4. return mRootActivityContainer.attachApplication(wpc);
  5. }
  6. }
  7. }

上图中,这个方法只做了一件事,调用RootActivityContainer的attachApplication()方法,下面进入RootActivityContainer类找到

attachApplication()方法。↓

  1. boolean attachApplication(WindowProcessController app) throws RemoteException {
  2. for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
  3. if (stack != null) {
  4. stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
  5. final ActivityRecord top = stack.topRunningActivityLocked();
  6. final int size = mTmpActivityList.size();
  7. for (int i = 0; i < size; i++) {
  8. final ActivityRecord activity = mTmpActivityList.get(i);
  9. if (activity.app == null && app.mUid == activity.info.applicationInfo.uid && processName.equals(activity.processName)) {
  10. try {
  11. if (mStackSupervisor.realStartActivityLocked(activity, app,top == activity, true)) {
  12. didSomething = true;
  13. }
  14. } catch (RemoteException e) {
  15. }
  16. }
  17. }
  18. }
  19. }
  20. return didSomething;
  21. }

上图中,可以看到这里调用了 ActivityStackSupervisor 的 realStartActivityLocked() 方法,到这里就和前面启动Activity的流程完全一致了,可以在流程图中找到。↓

九、总结

至此,Activity的创建过程已经梳理完了,总结一下,主要分两个支线,一个是:

1、启动进程start目标Activity,并进入AMS。

2、AMS判断目标Activity所属进程是否存在,存在就去通知ApplicationThread启动目标Activity。

3、目标ActivityThread收到通知,执行Activity的创建、初始化操作

另一个是:

1、启动进程start目标Activity,并进入AMS。

2、AMS判断目标Activity所属进程是否存在,不存在就去通知Zygote进程创建一个新的进程。

3、新的进程进入ActivityThread的main入口,初始化Looper,并通知AMS进程创建和初始化Application

4、同时AMS又跨进程通知ActivityThread去创建Activity。

5、目标ActivityThread收到通知,执行Activity的创建、初始化操作。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/654426
推荐阅读
相关标签
  

闽ICP备14008679号