android 8.0源码分析activity启动流程

当我们点击桌面图标的时候,会通过Launch应用,启动另外一个进程来启动当前应用的activity。那么这个activity的启动流程是怎样的呢?当然这一部分分为两个关键点:

  • application启动
  • activity启动
一、application启动
首先进入ActivityThread.java类。找到main()方法
1、ActivityThread.java----->main()方法,伪代码如下:
public static void main(String[] args) { ...Looper.prepareMainLooper(); ... ActivityThread thread = new ActivityThread(); thread.attach(false, startSeq); if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); }if (false) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); }// End of event ActivityThreadMain. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }

使用了Handler,looper消息机制,并且初始化了ActivityThread对象,调用了attach方法。
2、ActivityThread.java----->attach()方法,伪代码如下:
@UnsupportedAppUsage private void attach(boolean system, long startSeq) { ...final IActivityManager mgr = ActivityManager.getService(); try { mgr.attachApplication(mAppThread, startSeq); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } ... }

【android 8.0源码分析activity启动流程】使用了Binder机制,得到了ActivityManagerService的服务端代理类,调用attachApplication()方法,就会跨进程调动服务端的该方法。进入ActivityManagerService.java类。
3、ActivityManagerService.java----->attachApplication()方法,伪代码如下:
@Override public final void attachApplication(IApplicationThread thread, long startSeq) { synchronized (this) { ... attachApplicationLocked(thread, callingPid, callingUid, startSeq); ... } }

间接调用attachApplicationLocked()方法。
4、ActivityManagerService.java----->attachApplicationLocked()方法,伪代码如下:
@GuardedBy("this") private final boolean attachApplicationLocked(IApplicationThread thread, int pid, int callingUid, long startSeq) {...final ActiveInstrumentation instr2 = app.getActiveInstrumentation(); //1、第一步thread.bindApplication(processName, appInfo, providers, instr2.mClass, profilerInfo, instr2.mArguments, instr2.mWatcher, instr2.mUiAutomationConnection, testMode, mBinderTransactionTrackingEnabled, enableTrackAllocation, isRestrictedBackupMode || !normalMode, app.isPersistent(), new Configuration(app.getWindowProcessController().getConfiguration()), app.compat, getCommonServicesLocked(app.isolated), mCoreSettingsObserver.getCoreSettingsLocked(), buildSerial, autofillOptions, contentCaptureOptions); ...if (normalMode) { try { //2、第二步 didSomething = mAtmInternal.attachApplication(app.getWindowProcessController()); } catch (Exception e) { Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); badApp = true; } }... }

这部分代码,需要注意两部分,首先看第一步。这里的thread就是IApplicationThread ,我们知道它的实现类就是ApplicationThread,是ActivityThread的内部类。
5、ActivityThread.java $ ApplicaitonThread----->bindApplication()方法,伪代码如下:
public final void bindApplication(...) { ...//发送消息 sendMessage(H.BIND_APPLICATION, data); }

找到消息接收回调方法handleMessage()方法。
6、ActivityThread.java----->handleMessage()方法,伪代码如下:
public void handleMessage(Message msg) { if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what)); switch (msg.what) { case BIND_APPLICATION: Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication"); AppBindData data = https://www.it610.com/article/(AppBindData)msg.obj; handleBindApplication(data); Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); break; ... }

然后接收到消息后会调用handleBindApplication()方法。
7、ActivityThread.java----->handleBindApplication()方法,伪代码如下:
@UnsupportedAppUsage private void handleBindApplication(AppBindData data) { ...mInstrumentation.callApplicationOnCreate(app); ... }

8、Instrumentation.java----->callApplicationOnCreate()方法,伪代码如下:
public void callApplicationOnCreate(Application app) { app.onCreate(); }

这里的app就是Applicaiton,然后自然而然就会调用它的onCreate()方法。
9、Applicaiton.java----->onCreate()方法,伪代码如下:
public void onCreate() { }

这个方法需要开发者重写的。
ok,以上就完成了Application的启动过程,applicaiton启动以后,自然而然就会启动activity,之前在第4步的时候,我们只分析了一半、其实另一半就是activity的启动流程。
二、activity启动
1、ActivityManagerService.java----->attachApplicationLocked()方法,伪代码如下:
@GuardedBy("this") private final boolean attachApplicationLocked(IApplicationThread thread, int pid, int callingUid, long startSeq) {...final ActiveInstrumentation instr2 = app.getActiveInstrumentation(); //1、第一步thread.bindApplication(processName, appInfo, providers, instr2.mClass, profilerInfo, instr2.mArguments, instr2.mWatcher, instr2.mUiAutomationConnection, testMode, mBinderTransactionTrackingEnabled, enableTrackAllocation, isRestrictedBackupMode || !normalMode, app.isPersistent(), new Configuration(app.getWindowProcessController().getConfiguration()), app.compat, getCommonServicesLocked(app.isolated), mCoreSettingsObserver.getCoreSettingsLocked(), buildSerial, autofillOptions, contentCaptureOptions); ...if (normalMode) { try { //2、第二步 didSomething = mAtmInternal.attachApplication(app.getWindowProcessController()); } catch (Exception e) { Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); badApp = true; } }... }

我们分析第2步,这里的mAtmInternal是什么鬼呢?源码中是ActivityTaskManagerInternal.java类,但是我们发现他是一个抽象类,其实这个类的设计也是用到了Binder机制,并且真正的服务端就是ActivityTaskManagerService.java类。好了,进去看看吧
2、ActivityTaskManagerService.java----->attachApplication()方法,伪代码如下:
@Override public boolean attachApplication(WindowProcessController wpc) throws RemoteException { synchronized (mGlobalLockWithoutBoost) { return mRootActivityContainer.attachApplication(wpc); } }

3、RootActivityContainer.java----->attachApplication()方法,伪代码如下:
boolean attachApplication(WindowProcessController app) throws RemoteException { final String processName = app.mName; boolean didSomething = false; for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) { ... try { if (mStackSupervisor.realStartActivityLocked(activity, app, top == activity /* andResume */, true /* checkConfig */)) { didSomething = true; } } catch (RemoteException e) { ... } ... } ... return didSomething; }

关键代码就是realStartActivityLocked()。
4、ActivityStackSupervisor.java----->realStartActivityLocked()方法,伪代码如下:
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) throws RemoteException {...// Create activity launch transaction. final ClientTransaction clientTransaction = ClientTransaction.obtain( proc.getThread(), r.appToken); //1、第一步、添加了LaunchActivityItem final DisplayContent dc = r.getDisplay().mDisplayContent; clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent), System.identityHashCode(r), r.info, // TODO: Have this take the merged configuration instead of separate global // and override configs. mergedConfiguration.getGlobalConfiguration(), mergedConfiguration.getOverrideConfiguration(), r.compat, r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(), r.icicle, r.persistentState, results, newIntents, dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(), r.assistToken)); // Set desired final state.//2、第二步、设置了ActivityLifecycleItem final ActivityLifecycleItem lifecycleItem; if (andResume) { lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward()); } else { lifecycleItem = PauseActivityItem.obtain(); } clientTransaction.setLifecycleStateRequest(lifecycleItem); // Schedule transaction. //3 、第三步、开始执行事务 mService.getLifecycleManager().scheduleTransaction(clientTransaction); ... return true; }

前两步,添加了LaunchActivityItem、和ActivityLifecycleItem 到clientTransaction。然后执行第三步
5、ClientLifecycleManager.java----->scheduleTransaction()方法,伪代码如下:
void scheduleTransaction(ClientTransaction transaction) throws RemoteException { ... transaction.schedule(); ... }

6、ClientTransaction .java----->schedule()方法,伪代码如下:
public void schedule() throws RemoteException { mClient.scheduleTransaction(this); }

注意这里的mClient就是ApplicaitonThread对象,所以这边又回到了ActivityThread的内部类中
7、ActivityThread.java $ ApplicaitonThread.java----->scheduleTransaction()方法,伪代码如下:
@Override public void scheduleTransaction(ClientTransaction transaction) throws RemoteException { ActivityThread.this.scheduleTransaction(transaction); }

这里会调用ActivityThread父类ClientTransactionHandler的方法
8、ClientTransactionHandler.java ----->scheduleTransaction()方法,伪代码如下:
void scheduleTransaction(ClientTransaction transaction) { transaction.preExecute(this); sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); }

找到消息接收回调方法handleMessage()方法。
9、ActivityThread.java ----->handleMessage()方法,伪代码如下:
public void handleMessage(Message msg) { if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what)); switch (msg.what) { ... case EXECUTE_TRANSACTION: final ClientTransaction transaction = (ClientTransaction) msg.obj; mTransactionExecutor.execute(transaction); if (isSystem()) { // Client transactions inside system process are recycled on the client side // instead of ClientLifecycleManager to avoid being cleared before this // message is handled. transaction.recycle(); } // TODO(lifecycler): Recycle locally scheduled transactions. break; ... } ... }

10、TransactionExecutor.java ----->execute()方法,伪代码如下:
public void execute(ClientTransaction transaction) { ...//1、第一步 executeCallbacks(transaction); //2、第二步 executeLifecycleState(transaction); ... }

这边关键的两个步骤,其实这两个步骤就是activity的OnCreate()和onResume()方法的调用过程。先看第一步
10–1、TransactionExecutor.java ----->executeCallbacks()方法,伪代码如下:
@VisibleForTesting public void executeCallbacks(ClientTransaction transaction) { ...final int size = callbacks.size(); for (int i = 0; i < size; ++i) {//这里拿到的是LaunchActivityItem final ClientTransactionItem item = callbacks.get(i); ...item.execute(mTransactionHandler, token, mPendingActions); ... } }

10–2、LaunchActivityItem.java ----->execute()方法,伪代码如下:
@Override public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) { Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart"); ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo, mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState, mPendingResults, mPendingNewIntents, mIsForward, mProfilerInfo, client, mAssistToken); client.handleLaunchActivity(r, pendingActions, null /* customIntent */); Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER); }

这里的client是ClientTransactionHandler ,我们知道他的子类就是ActivityThread,所以再次回到ActivityThread。
10–3、ActivityThread.java ----->handleLaunchActivity()方法,伪代码如下:
@Override public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) { // If we are getting ready to gc after going to the background, well // we are back active so skip it. ...final Activity a = performLaunchActivity(r, customIntent); ...return a; }

10–4、ActivityThread.java ----->performLaunchActivity()方法,伪代码如下:
/**Core implementation of activity launch. */ private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { ... if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); } ... return activity; }

10–5、Instrumentation.java ----->callActivityOnCreate()方法,伪代码如下:
public void callActivityOnCreate(Activity activity, Bundle icicle) { prePerformCreate(activity); activity.performCreate(icicle); postPerformCreate(activity); }

10–6、Activity .java ----->performCreate()方法,伪代码如下:
final void performCreate(Bundle icicle) { performCreate(icicle, null); }@UnsupportedAppUsage final void performCreate(Bundle icicle, PersistableBundle persistentState) { ... if (persistentState != null) { onCreate(icicle, persistentState); } else { onCreate(icicle); } ... }

ok,以上就完成了Activity的onCreate()启动过程。回到第10步的另外一部分
10–7、TransactionExecutor.java ----->executeLifecycleState()方法,伪代码如下:
private void executeLifecycleState(ClientTransaction transaction) { final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); ...// Execute the final transition with proper parameters. lifecycleItem.execute(mTransactionHandler, token, mPendingActions); lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions); }

这里的ActiivtyLifecycleItem是一个抽象类,发现并没有execute()方法,那么肯定是它的子类拥有,子类就是ResumeActivityItem。
10–8、ResumeActivityItem.java ----->execute()方法,伪代码如下:
@Override public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) { Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume"); client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward, "RESUME_ACTIVITY"); Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER); }

同上,这里的client就是ActiviytThread。于是回到了起点。剩下的和onCreate的分析大致相同了,这里不做描述。
其实由于源码在不同版本,都会有或大或小的变化,但是,归根结底都会使用hanlder的消息机制以及Binder机制。

    推荐阅读