#Task.java private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options, boolean deferPause) { if (!mAtmService.isBooting() && !mAtmService.isBooted()) { // Not ready yet! return false; } // 在当前 Task 栈中找到最上层正在运行的 Activity // 如果这个 Activity 没有获取焦点,那这个 Activity 将会被重新启动 ActivityRecord next = topRunningActivity(true /* focusableOnly */); if (next.attachedToProcess()) { ...... } else { ...... //调用 ActivityTaskSupervisor.startSpecificActivity mTaskSupervisor.startSpecificActivity(next, true, true); } return true; }
#ActivityTaskSupervisor.java void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) { // 获取目标进程 final WindowProcessController wpc = mService.getProcessController(r.processName, r.info.applicationInfo.uid); boolean knownToBeDead = false; if (wpc != null && wpc.hasThread()) { try { //如果进程存在,启动 Activity 并返回 realStartActivityLocked(r, wpc, andResume, checkConfig); return; } catch (RemoteException e) { } knownToBeDead = true; } r.notifyUnknownVisibilityLaunchedForKeyguardTransition(); final boolean isTop = andResume && r.isTopRunningActivity(); // 进程不存在,则创建进程,并启动 Activity mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity"); }
如果进程不存在,则会创建进程,如果进程存在,则执行此方法
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) throws RemoteException { // 创建启动 Activity 的事务 // proc.getThread() 获取的是一个 IApplicationThread 对象 final ClientTransaction clientTransaction = ClientTransaction.obtain( proc.getThread(), r.appToken); final boolean isTransitionForward = r.isTransitionForward(); // 为事务设置 Callback LaunchActivityItem,在客户端时会被调用 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, r.takeOptions(), isTransitionForward, proc.createProfilerInfoIfNeeded(), r.assistToken, activityClientController, r.createFixedRotationAdjustmentsIfNeeded(), r.shareableActivityToken, r.getLaunchedFromBubble())); // 生命周期对象 final ActivityLifecycleItem lifecycleItem; if (andResume) { lifecycleItem = ResumeActivityItem.obtain(isTransitionForward); } else { lifecycleItem = PauseActivityItem.obtain(); } // 设置生命周期请求 clientTransaction.setLifecycleStateRequest(lifecycleItem); // 执行事务 mService.getLifecycleManager().scheduleTransaction(clientTransaction); return true; }
上面代码的核心就是创建事务实例,然后来启动 Activity 。
ClientTransaction 是一个容器,里面包含了一些列的消息,这些消息会被发送到客户端,这些消息包括了一系列的回调和一个最终的生命周期状态。
ActivityLifecycleItem 用来请求 Activity 应该到达那个生命周期。
ClientLifecycleManager 用来执行事务
接着上面的代码往下走,就到了 scheduleTransaction():
void scheduleTransaction(ClientTransaction transaction) throws RemoteException { // AIDL 接口,在客户端被实现,也就是 app 中 final IApplicationThread client = transaction.getClient(); //执行事务 transaction.schedule(); if (!(client instanceof Binder)) { transaction.recycle(); } }
public void schedule() throws RemoteException { mClient.scheduleTransaction(this); }
mClient 就是 IApplicationThread 的实例,这里是一个 IPC 调用,会直接调用到 App 进程中,并传入了 this,也就是 ClientTransaction 对象。
IApplicationThread 是 ApplicationThread 所实现的,他是 ActivityThread 的内部类:
private class ApplicationThread extends IApplicationThread.Stub { @Override public void scheduleTransaction(ClientTransaction transaction) throws RemoteException { ActivityThread.this.scheduleTransaction(transaction); } }
在上面代码中检查 intent 以及各种权限,并且会获取启动模式,设置启动 Activity 的Task,最后判断 Activity 所在的进程是否存活,如果不存在则创建,如果存在则会通过 IPC 回调到 ApplicationThread 中去。
三、ActivityThread
通过上面,我们知道了启动 Activity 最终有回调到 ApplicationThread,而它又是 ActivityThread 的子类。所以 上面代码最终调用到了 ActivityThread 的父类 ClientTransactionHandler 中:
void scheduleTransaction(ClientTransaction transaction) { transaction.preExecute(this);//处理 //发送消息 sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); }
//创建的时候传入了 ActivityThread 实例 private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this); #ActivityThread$H case EXECUTE_TRANSACTION: final ClientTransaction transaction = (ClientTransaction) msg.obj; mTransactionExecutor.execute(transaction); if (isSystem()) { transaction.recycle(); } break;
上面代码中通过 TransactionExecutor 来执行事务:
public void execute(ClientTransaction transaction) { //执行回调 executeCallbacks(transaction); //处理生命周期状态 executeLifecycleState(transaction); mPendingActions.clear(); if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction"); } //处理生命周期状态 private void executeLifecycleState(ClientTransaction transaction) { final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); if (lifecycleItem == null) { // No lifecycle request, return early. return; } final IBinder token = transaction.getActivityToken(); final ActivityClientRecord r = mTransactionHandler.getActivityClient(token); if (DEBUG_RESOLVER) { Slog.d(TAG, tId(transaction) + "Resolving lifecycle state: " + lifecycleItem + " for activity: " + getShortActivityName(token, mTransactionHandler)); } if (r == null) { // Ignore requests for non-existent client records for now. return; } // 切换到对应的生命周期 cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction); // Execute the final transition with proper parameters. lifecycleItem.execute(mTransactionHandler, token, mPendingActions); lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions); } private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState, ClientTransaction transaction) { final int start = r.getLifecycleState(); final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState); performLifecycleSequence(r, path, transaction); } //执行生命周期状态 private void performLifecycleSequence(ActivityClientRecord r, IntArray path, ClientTransaction transaction) { final int size = path.size(); for (int i = 0, state; i < size; i++) { state = path.get(i); switch (state) { case ON_CREATE: mTransactionHandler.handleLaunchActivity(r, mPendingActions, null /* customIntent */); break; case ON_START: mTransactionHandler.handleStartActivity(r, mPendingActions, null /* activityOptions */); break; case ON_RESUME: mTransactionHandler.handleResumeActivity(r, false /* finalStateRequest */, r.isForward, "LIFECYCLER_RESUME_ACTIVITY"); break; case ON_PAUSE: mTransactionHandler.handlePauseActivity(r, false /* finished */, false /* userLeaving */, 0 /* configChanges */, mPendingActions, "LIFECYCLER_PAUSE_ACTIVITY"); break; case ON_STOP: mTransactionHandler.handleStopActivity(r, 0 /* configChanges */, mPendingActions, false /* finalStateRequest */, "LIFECYCLER_STOP_ACTIVITY"); break; case ON_DESTROY: mTransactionHandler.handleDestroyActivity(r, false /* finishing */, 0 /* configChanges */, false /* getNonConfigInstance */, "performLifecycleSequence. cycling to:" + path.get(size - 1)); break; case ON_RESTART: mTransactionHandler.performRestartActivity(r, false /* start */); break; default: throw new IllegalArgumentException("Unexpected lifecycle state: " + state); } } }
由于是新启动的 Activity,所以最开始执行的是 ON_CREATE 状态,也就是 handleLaunchActivity 方法, 而 mTransactionHandler 则是从构造方法中传入的,所以这里调用你的就是 ActivityThread 中的方法。
#ActivityThread.java public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) { //获取 Activity 的实例 final Activity a = performLaunchActivity(r, customIntent); return a; }
#ActivityThread.java private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { ActivityInfo aInfo = r.activityInfo; ContextImpl appContext = createBaseContextForActivity(r); Activity activity = null; try { //反射创建 Activity java.lang.ClassLoader cl = appContext.getClassLoader(); activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent); ...... } catch (Exception e) { if (!mInstrumentation.onException(activity, e)) { throw new RuntimeException( "Unable to instantiate activity " + component + ": " + e.toString(), e); } } try { //如果没有 Application ,则进行创建 Application app = r.packageInfo.makeApplication(false, mInstrumentation); ...... if (activity != null) { Window window = null; if (r.mPendingRemoveWindow != null && r.mPreserveWindow) { window = r.mPendingRemoveWindow; r.mPendingRemoveWindow = null; r.mPendingRemoveWindowManager = null; } .... // 加载资源 appContext.getResources().addLoaders( app.getResources().getLoaders().toArray(new ResourcesLoader[0])); // 调用 attach 方法 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, r.shareableActivityToken); //回调 onCreate 方法 if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); } } //设置当前状态 r.setState(ON_CREATE); ...... } return activity; }
回调到 ActivityThread 后,会发送一个 EXECUTE_TRANSACTION 消息,处理 system_server 传过来的 ClientTransaction。
具体的处理是在 TransactionExecutor 的 execute 方法中完成的,在里面会先执行各种回调,然后处理并切换到对应的生命周期。在根据对应的什么周期执行对应的方法。由于这里是新建的 aCTIVITY ,所以状态是 ON_CREATE,就会执行 handleLaunchActivity 方法。
接着就会调用 performLaunchActivity 创建 Activity 的实例,调用 attach 初始化 activity,最后回调 activity 中的 onCreate 方法。
总结一下流程
调用 Activity 的 startActivity 方法来启动目标 Activity
接着就会调用到 Instrunmentation 的 execStartActivity 方法,通过获取 ATMS 的 binder 代理对象,然后调用到 ATMS 的 startActivity 中去
调用到 ATMS 中后,会执行到ActivityStarter 的 execute 方法,内部最终执行到了 executeRequest ,接着就会进行一些校验和判断权限,包括进程检查,intent检查,权限检查等,后面就会创建 ActivityRecord ,用来保存 Activity 的相关信息,
然后就会根据启动模式计算 flag ,设置启动 Activity 的 Task 栈。
在 ActivityTaskSupervisor 中检查要启动的 Activity 进程是否存在,存在则向客户端进程 ApplicationThread 回调启动 Activity,否则就创建进程。
会调到 ActivityThread 后在 TransactionExecute 中开始执行system_server回调回来的事务,处理各种回调,切换到对应的生命周期
最后又回调到 ActivityThread 的 handleLaunchActivity 来启动 Activity。在其中调用了 performLaunchActivity 方法。
在 performLaunchActivity 中通过反射创建 Activity 实例,如果没有 Application 则先进行创建,然后再调用Activity 的 attach 方法进行初始化,最后回调 activity 的 onCreate 方法。