APP 启动流程涉及到进程的创建、进程间通信、Socket 通信、Handler 线程通信,作为系统工程师了解 APP 的启动流程很有必要,本文从 startActivity() 开始分析 APP 的启动流程,代码基于 android-12.1.0_r4;
1. 相关代码路径
Layer
Path
framework
frameworks/base/core/java/android/app/Activity.java
frameworks/base/core/java/android/app/Instrumentation.java
frameworks/base/core/java/android/app/ActivityTaskManager.java
frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java
frameworks/base/services/core/java/com/android/server/wm/Task.java
frameworks/base/services/core/java/com/android/server/wm/TaskFragment.java
frameworks/base/services/core/java/com/android/server/wm/ActivityTaskSupervisor.java
frameworks/base/services/core/java/com/android/server/wm/ClientLifecycleManager.java
frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
frameworks/base/core/java/android/app/ActivityThread.java
frameworks/base/core/java/android/app/ClientTransactionHandler.java
frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java
frameworks/base/core/java/android/app/AppComponentFactory.java
frameworks/base/services/core/java/com/android/server/am/ProcessList.java
frameworks/base/core/java/android/os/Process.java
frameworks/base/core/java/android/os/ZygoteProcess.java
frameworks/base/core/java/com/android/internal/os/ZygoteServer.java
frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java
frameworks/base/core/java/com/android/internal/os/Zygote.java
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java
frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
2. Launcher 向 system_server 发起请求(Binder) 2.1 Activity Launcher 中点击 icon 后最终会执行到 Activity.startActivity(),以此为入口分析 startActivity() 流程;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 @Override public void startActivity (Intent intent) { this .startActivity(intent, null ); } @Override public void startActivity (Intent intent, @Nullable Bundle options) { if (mIntent != null && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN) && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY)) { ... } if (options != null ) { startActivityForResult(intent, -1 , options); } else { startActivityForResult(intent, -1 ); } } public void startActivityForResult (@RequiresPermission Intent intent, int requestCode) { startActivityForResult(intent, requestCode, null ); } public void startActivityForResult (@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) { ... Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(this , mMainThread.getApplicationThread(), mToken, this , intent, requestCode, options); if (ar != null ) { mMainThread.sendActivityResult(mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData()); ... }
有多种启动 activity 的方法,但是最终都是调用 mInstrumentation.execStartActivity(),Instrumentation 主要用来监控应用程序和系统的交互。
2.2 Instrumentation 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public ActivityResult execStartActivity ( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { ... try { intent.migrateExtraStreamToClipData(who); intent.prepareToLeaveProcess(who); int result = ActivityTaskManager.getService().startActivity(whoThread, who.getOpPackageName(), who.getAttributionTag(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null , requestCode, 0 , null , options); ... }
获取 ATMS,并执行其中的 startActivity()
2.3 ActivityTaskManager 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public static IActivityTaskManager getService () { return IActivityTaskManagerSingleton.get(); } @UnsupportedAppUsage(trackingBug = 129726065) private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton = new Singleton <IActivityTaskManager>() { @Override protected IActivityTaskManager create () { final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE); return IActivityTaskManager.Stub.asInterface(b); } };
getService() 返回的是 IActivityTaskManager.Stub.asInterface(b);
,这是一个远程调用模式,是 AIDL 生成的 IActivityTaskManager.java 中的 stub 类中的 asInterface() 方法,先通过 ACTIVITY_TASK_SERVICE 获取 ATMS 的 IBinder 对象 b,再通过 asInterface(b) 获取 ATMS 的代理对象,接下来进入 ATMS 中;
3. system_server 进程请求 Zygote 创建新进程(Socket) 3.1 ActivityTaskManagerService 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 public final int startActivity (IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) { return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, UserHandle.getCallingUserId()); } public int startActivityAsUser (IApplicationThread caller, String callingPackage, String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) { return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId, true ); } private int startActivityAsUser (IApplicationThread caller, String callingPackage, @Nullable String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) { ... return getActivityStartController().obtainStarter(intent, "startActivityAsUser" ) .setCaller(caller) .setCallingPackage(callingPackage) .setCallingFeatureId(callingFeatureId) .setResolvedType(resolvedType) .setResultTo(resultTo) .setResultWho(resultWho) .setRequestCode(requestCode) .setStartFlags(startFlags) .setProfilerInfo(profilerInfo) .setActivityOptions(bOptions) .setUserId(userId) .execute(); }
通过 obtailStarter() 获取 ActivityStarter 对象并设置一些参数,最终调用到 ActivityStarter.execute()
3.2 ActivityStarter 1 2 3 4 5 6 7 8 9 10 int execute () { try { ... res = resolveToHeavyWeightSwitcherIfNeeded(); if (res != START_SUCCESS) { return res; } res = executeRequest(mRequest); ...
根据前面提供的请求参数解析必要的信息,
1 2 3 4 5 6 7 8 9 10 11 private int executeRequest (Request request) { ... final ActivityRecord r = new ActivityRecord .Builder(mService) ... mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession, request.voiceInteractor, startFlags, true , checkedOptions, inTask, inTaskFragment, restrictedBgActivity, intentGrants); ... return mLastStartActivityResult; }
1 2 3 4 5 6 7 8 9 10 11 12 13 private int startActivityUnchecked (final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, Task inTask, TaskFragment inTaskFragment, boolean restrictedBgActivity, NeededUriGrants intentGrants) { ... result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor, startFlags, doResume, options, inTask, inTaskFragment, restrictedBgActivity, intentGrants); ... return result; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 int startActivityInner (final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, Task inTask, TaskFragment inTaskFragment, boolean restrictedBgActivity, NeededUriGrants intentGrants) { ... mTargetRootTask.startActivityLocked(mStartActivity, topRootTask != null ? topRootTask.getTopNonFinishingActivity() : null , newTask, isTaskSwitch, mOptions, sourceRecord); ... mRootWindowContainer.resumeFocusedTasksTopActivities( mTargetRootTask, mStartActivity, mOptions, mTransientLaunch); } } ... return START_SUCCESS; }
startActivityLocked():判断当前 activity 是否可见以及是否需要为其新建 Task,根据不同情况将 ActivityRecord 加入到对应的 Task 栈顶中;
resumeFocusedTasksTopActivities():将所有聚焦的 Task 的所有 Activity 恢复运行,因为有些刚加入的 Activity 是处于暂停状态的,判断传入的 targetRootTask 是否等于当前栈顶的 Task,不管是否相等,后续都是调用栈顶 Task 的 resumeTopActivityUncheckedLocked() 方法;
1 2 3 4 5 6 7 8 9 10 11 12 boolean resumeFocusedTasksTopActivities ( Task targetRootTask, ActivityRecord target, ActivityOptions targetOptions, boolean deferPause) { ... final Task focusedRoot = display.getFocusedRootTask(); if (focusedRoot != null ) { result |= focusedRoot.resumeTopActivityUncheckedLocked(target, targetOptions); } else if (targetRootTask == null ) { ... return result; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 boolean resumeTopActivityUncheckedLocked (ActivityRecord prev, ActivityOptions options) { return resumeTopActivityUncheckedLocked(prev, options, false ); } boolean resumeTopActivityUncheckedLocked (ActivityRecord prev, ActivityOptions options, boolean deferPause) { ... boolean someActivityResumed = false ; try { mInResumeTopActivity = true ; if (isLeafTask()) { if (isFocusableAndVisible()) { someActivityResumed = resumeTopActivityInnerLocked(prev, options, deferPause); } ... return someActivityResumed; }
1 2 3 4 5 6 7 8 9 private boolean resumeTopActivityInnerLocked (ActivityRecord prev, ActivityOptions options, boolean deferPause) { ... final boolean [] resumed = new boolean [1 ]; final TaskFragment topFragment = topActivity.getTaskFragment(); resumed[0 ] = topFragment.resumeTopActivity(prev, options, deferPause); ... }
1 2 3 4 5 6 7 8 9 10 11 12 13 final boolean resumeTopActivity (ActivityRecord prev, ActivityOptions options, boolean deferPause) { ... boolean pausing = !deferPause && taskDisplayArea.pauseBackTasks(next); ... if (next.attachedToProcess()) { ... } else { ... mTaskSupervisor.startSpecificActivity(next, true , true ); }
判断当前(栈顶) Activity 是否与已有的进程关联,如果已经关联,就在该进程中恢复页面,否则就需要在 startSpecificActivity() 重新启动目标 Activity,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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 { realStartActivityLocked(r, wpc, andResume, checkConfig); return ; ... final boolean isTop = andResume && r.isTopRunningActivity(); mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity" ); }
首先判断待启动的 activity 所在的 application 是否在运行,如果已经运行就直接启动,否则启动新进程
4. App 进程已存在 4.1 ATS.realStartActivityLocked() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 boolean realStartActivityLocked (ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) throws RemoteException { ... final ClientTransaction clientTransaction = ClientTransaction.obtain( proc.getThread(), r.appToken); clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent (r.intent),...); final ActivityLifecycleItem lifecycleItem; if (andResume) { lifecycleItem = ResumeActivityItem.obtain(isTransitionForward); } else { lifecycleItem = PauseActivityItem.obtain(); } clientTransaction.setLifecycleStateRequest(lifecycleItem); mService.getLifecycleManager().scheduleTransaction(clientTransaction); ... return true ; }
CLientTransaction 类是一种容器,用于保存可发送给客户端的消息序列,包括一个回调列表和一个最终生命周期状态;
消息分为 5 种,包括 LaunchActivityItem / ResumeActivityItem / PauseActivityItem / StopActivityItem / DestroyActivityItem;
上述代码主要就是添加 LaunchActivityItem 到回调列表中以及通过 setLifecycleStateRequest()
设置最终的生命周期状态,最后调用 ClientTransaction.schedule()
;
4.2 CLM.scheduleTransaction() 1 2 3 4 5 6 void scheduleTransaction (ClientTransaction transaction) throws RemoteException { final IApplicationThread client = transaction.getClient(); transaction.schedule(); ... }
最终 ClientLifecycleManager 把创建 activity 事务提交给了客户端的 ApplicationThread 类。
4.3 ClientTransaction.schedule()[Binder] 1 2 3 4 5 private IApplicationThread mClient; public void schedule () throws RemoteException { mClient.scheduleTransaction(this ); }
mCLient 是 IApplicationThread 对象,IApplicationThread 是一个 AIDL 接口,ApplicationThread 是ActivityThread 的内部类,继承 IApplicationThread.Stub,所以会调用到服务端 ApplicationThread 的 scheduleTransaction() 中,此时我们是在 system_server 进程,所以对应的服务端就是 app 进程, 实现在 ActivityThread.ApplicationThread 中:
4.4 APP Binder 线程向主线程发送 EXECUTE_TRANSACTION[Handler] 1 2 3 4 public void scheduleTransaction (ClientTransaction transaction) throws RemoteException { ActivityThread.this .scheduleTransaction(transaction); }
ActivityThread 继承 ClientTransactionHandler,最后对应的实现在 ClientTransactionHandler 中;
1 2 3 4 5 6 void scheduleTransaction (ClientTransaction transaction) { transaction.preExecute(this ); sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); } abstract void sendMessage (int what, Object obj) ;
通过 handler 发送 EXECUTE_TRANSACTION 消息给 ActivityThread;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 final H mH = new H (); void sendMessage (int what, Object obj) { sendMessage(what, obj, 0 , 0 , false ); } private void sendMessage (int what, Object obj, int arg1, int arg2, boolean async) { if (DEBUG_MESSAGES) { Slog.v(TAG, "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj); } Message msg = Message.obtain(); msg.what = what; msg.obj = obj; msg.arg1 = arg1; msg.arg2 = arg2; if (async) { msg.setAsynchronous(true ); } mH.sendMessage(msg); }
mH 是 H 类,调用 ActivityThread.handleMessage() 处理;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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()) { transaction.recycle(); } break ;
4.5 TransactionExecutor 1 2 3 4 5 6 7 8 9 10 11 12 13 public void execute (ClientTransaction transaction) { if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Start resolving transaction" ); final IBinder token = transaction.getActivityToken(); ... executeCallbacks(transaction); executeLifecycleState(transaction); mPendingActions.clear(); if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction" ); }
TransactionExecutor 类的功能就是以正确顺序管理事务执行,即前面 **[4.1 小节]**添加的消息在这个类里会按照一定的顺序去执行;
4.5.1 executeCallbacks() 1 2 3 4 5 6 7 8 9 10 11 12 13 public void executeCallbacks (ClientTransaction transaction) { final List<ClientTransactionItem> callbacks = transaction.getCallbacks(); ... 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); ... } }
在服务端提交事务的时候,通过 clientTransaction.addCallback
方式将 LaunchActivityItem 添加到 mActivityCallbacks 里面,所以通过遍历 transaction#callbacks 获取到 LaunchActivityItem,然后调用 execute 方法:
1 2 3 4 5 6 7 8 public void execute (ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) { Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart" ); ActivityClientRecord r = client.getLaunchingActivity(token); client.handleLaunchActivity(r, pendingActions, null ); Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER); }
调用到 ClientTransactionHandler.handleLaunchActivity()
,ActivityClientRecord 是 ActivityThread 的内部类,ActivityThread 继承了 ClientTransactionHandler,实现了抽象方法 getLaunchingActivity()
和handleLaunchActivity()
,进入到 ActivityThread;
4.5.2 executeLifecycleState() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 private void executeLifecycleState (ClientTransaction transaction) { final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); ... final IBinder token = transaction.getActivityToken(); final ActivityClientRecord r = mTransactionHandler.getActivityClient(token); ... cycleToPath(r, lifecycleItem.getTargetState(), true , transaction); lifecycleItem.execute(mTransactionHandler, token, mPendingActions); lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions); }
这里通过 getLifecycleStateRequest()
获取事务的最终生命周期状态,即在 **[4.1 小节]**中通过 setLifecycleStateRequest()
添加的 ResumeActivityItem,所以此处的 lifecycleItem 就是 ResumeActivityItem,先来看一下 cycleToPath()
:
1 2 3 4 5 6 7 8 9 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); }
循环到最终请求状态之前的状态,拿到 lifeCyclePath 后就交给了 performLifecycleSequence()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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(...); break ; case ON_START: mTransactionHandler.handleStartActivity(...); case ON_RESUME: mTransactionHandler.handleResumeActivity(...); case ON_PAUSE: mTransactionHandler.handlePauseActivity(...); case ON_STOP: mTransactionHandler.handleStopActivity(...); case ON_DESTROY: mTransactionHandler.handleDestroyActivity(...); case ON_RESTART: mTransactionHandler.performRestartActivity(...);
按照状态执行对应的操作,然后继续看 cycleToPath()
后面的代码 lifecycleItem.execute()
,即 ResumeActivityItem.execute()
:
1 2 3 4 5 6 7 public void execute (ClientTransactionHandler client, ActivityClientRecord r, PendingTransactionActions pendingActions) { Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume" ); client.handleResumeActivity(r, true , mIsForward, "RESUME_ACTIVITY" ); Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER); }
和 LaunchActivityItem.execute()
一样,调用到 ActivityThread.handleResumeActivity()
;
4.6 handleLaunchActivity() 1 2 3 4 5 public Activity handleLaunchActivity (ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) { ... final Activity a = performLaunchActivity(r, customIntent);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 private Activity performLaunchActivity (ActivityClientRecord r, Intent customIntent) { ContextImpl appContext = createBaseContextForActivity(r); Activity activity = null ; try { java.lang.ClassLoader cl = appContext.getClassLoader(); activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent); ...... r.activity = activity; if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); } 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 @NonNull Activity instantiateActivity (@NonNull ClassLoader cl, @NonNull String className, @Nullable Intent intent) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return (Activity) cl.loadClass(className).newInstance(); }
performLaunchActivity() 的作用就是在 Instrumentation.newActivity()
函数中根据 Activity 的类名通过通过反射机制创建对应的 Activity,然后调用 Activity 的 onCreate() 函数;
4.6.2 callActivityOnCreate - 执行 Activity.onCreate 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public void callActivityOnCreate (Activity activity, Bundle icicle) { prePerformCreate(activity); activity.performCreate(icicle); postPerformCreate(activity); } final void performCreate (Bundle icicle) { performCreate(icicle, null ); } final void performCreate (Bundle icicle, PersistableBundle persistentState) { ... if (persistentState != null ) { onCreate(icicle, persistentState); } else { onCreate(icicle); } protected void onCreate (@Nullable Bundle savedInstanceState) { ...
最终调用到 Activity.onCreate() 方法,开始执行 APP 的代码,app 进程已启动的情况流程完结,startActivity() 成功;
handleResumeActivity()
的流程也和上面一样,handleResumeActivity() -> performResumeActivity() -> Activity.performResume() -> Instrumentation.callActivityOnResume() -> Activity.onResume()
,不再展开,接下来看 app 进程未启动的情况。
5. App 进程不存在,请求 Zygote 创建新进程(Socket) 5.1 startProcessAsync() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 void startProcessAsync (ActivityRecord activity, boolean knownToBeDead, boolean isTop, String hostingType) { try { if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) { Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:" + activity.processName); } final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess, mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead, isTop, hostingType, activity.intent.getComponent()); mH.sendMessage(m); } finally { Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER); } }
5.2 AMS.startProcess() 进入 ActivityManagerInternal::startProcess()
1 2 3 4 public abstract class ActivityManagerInternal { public abstract void startProcess (String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName) ;
是个抽象类,AMS.LocalService 继承了它,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public final class LocalService extends ActivityManagerInternal implements ActivityManagerLocal { ... public void startProcess (String processName, ApplicationInfo info, boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName) { ... synchronized (ActivityManagerService.this ) { startProcessLocked(processName, info, knownToBeDead, 0 , new HostingRecord (hostingType, hostingName, isTop), ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false , false ); ...
5.3 startProcessLocked() 1 2 3 4 5 6 7 8 9 10 final ProcessRecord startProcessLocked (String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated) { return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 , null , null , null , null ); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 ProcessRecord startProcessLocked (String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated, int isolatedUid, String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) { long startTime = SystemClock.uptimeMillis(); ProcessRecord app; ... final boolean success = startProcessLocked(app, hostingRecord, zygotePolicyFlags, abiOverride); checkSlow(startTime, "startProcess: done starting proc!" ); return success ? app : null ; } boolean startProcessLocked (ProcessRecord app, HostingRecord hostingRecord, int zygotePolicyFlags, String abiOverride) { return startProcessLocked(app, hostingRecord, zygotePolicyFlags, false , false , abiOverride); } boolean startProcessLocked (ProcessRecord app, HostingRecord hostingRecord, int zygotePolicyFlags, boolean disableHiddenApiChecks, boolean disableTestApiChecks, String abiOverride) { ... long startTime = SystemClock.uptimeMillis(); ... final String entryPoint = "android.app.ActivityThread" ; return startProcessLocked(hostingRecord, entryPoint, app, uid, gids, runtimeFlags, zygotePolicyFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith, startTime); ... } boolean startProcessLocked (HostingRecord hostingRecord, String entryPoint, ProcessRecord app, int uid, int [] gids, int runtimeFlags, int zygotePolicyFlags, int mountExternal, String seInfo, String requiredAbi, String instructionSet, String invokeWith, long startTime) { ... try { final Process.ProcessStartResult startResult = startProcess(...); handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper, startSeq, false ); ...
记住 ProcessList.java:2043 行的 entryPoint,在后面 zygote 创建完子进程后需要用到;
5.4 ProcessList.startProcess() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 private Process.ProcessStartResult startProcess (HostingRecord hostingRecord, String entryPoint, ProcessRecord app, int uid, int [] gids, int runtimeFlags, int zygotePolicyFlags, int mountExternal, String seInfo, String requiredAbi, String instructionSet, String invokeWith, long startTime) { try { startResult = startWebView(...); } else if (hostingRecord.usesAppZygote()) { final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app); startResult = appZygote.getProcess().start(...); } else { regularZygote = true ; startResult = Process.start(...); } ...
有三种不同类型的 zygote,
webview zygote:辅助 zygote 进程,用于创建 isolated_app 进程来渲染不可信的 web 内容,具有最为严格的安全限制;
app zygote:应用 zygote 进程,与常规 zygote 创建的应用相比受到更多限制;
regular zygote:常规的 zygote32/zygote64 进程,是所有 Android Java 应用的父进程;
关注常规 zygote 即可,最终都是调用到 Process.start() 方法;
5.5 Process.start() 1 2 3 4 5 6 7 8 9 10 public static final ZygoteProcess ZYGOTE_PROCESS = new ZygoteProcess (); public static ProcessStartResult start (...) { return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids, runtimeFlags, mountExternal, targetSdkVersion, seInfo, abi, instructionSet, appDataDir, invokeWith, packageName, zygotePolicyFlags, isTopApp, disabledCompatChanges, pkgDataInfoMap, whitelistedDataInfoMap, bindMountAppsData, bindMountAppStorageDirs, zygoteArgs); }
调用 ZYGOTE_PROCESS.start(),ZYGOTE_PROCESS 就是一个 ZygoteProcess 对象,其在构造函数中初始化了用于和 zygote 通信的 mZygoteSocketAddress,
1 2 3 4 5 6 7 8 9 10 public final Process.ProcessStartResult start (...) { ... return startViaZygote(processClass, niceName, uid, gid, gids, runtimeFlags, mountExternal, targetSdkVersion, seInfo, abi, instructionSet, appDataDir, invokeWith, false , packageName, zygotePolicyFlags, isTopApp, disabledCompatChanges, pkgDataInfoMap, allowlistedDataInfoList, bindMountAppsData, bindMountAppStorageDirs, zygoteArgs); ...
5.6 Process.ProcessStartResult 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 private Process.ProcessStartResult startViaZygote (...) ... argsForZygote.add("--runtime-args" ); argsForZygote.add("--setuid=" + uid); argsForZygote.add("--setgid=" + gid); argsForZygote.add("--runtime-flags=" + runtimeFlags); argsForZygote.add("--target-sdk-version=" + targetSdkVersion); ... argsForZygote.add("--nice-name=" + niceName); argsForZygote.add("--package-name=" + packageName); synchronized (mLock) { return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), zygotePolicyFlags, argsForZygote); } }
该过程主要工作是生成argsForZygote
数组,该数组保存了进程的 uid、gid、groups、target-sdk、nice-name、package-name 等一系列的参数;
openZygoteSocketIfNeeded() 是根据当前的 abi 来选择与 zygote 还是 zygote64 进程建立连接,获取和 Zygote 通信的 Socket,最终返回了一个已连接 Zygote、包含对应套接字的 ZygoteState 对象,便于后面通信使用;
1 2 3 4 5 6 7 8 9 private Process.ProcessStartResult zygoteSendArgsAndGetResult ( ZygoteState zygoteState, int zygotePolicyFlags, @NonNull ArrayList<String> args) throws ZygoteStartFailedEx { ... String msgStr = args.size() + "\n" + String.join("\n" , args) + "\n" ; ... return attemptZygoteSendArgsAndGetResult(zygoteState, msgStr); }
ZygoteState 是用于与 Zygote 通信的状态,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 private Process.ProcessStartResult attemptZygoteSendArgsAndGetResult ( ZygoteState zygoteState, String msgStr) throws ZygoteStartFailedEx { try { final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter; final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream; zygoteWriter.write(msgStr); zygoteWriter.flush(); Process.ProcessStartResult result = new Process .ProcessStartResult(); result.pid = zygoteInputStream.readInt(); result.usingWrapper = zygoteInputStream.readBoolean(); if (result.pid < 0 ) { throw new ZygoteStartFailedEx ("fork() failed" ); } return result; ...
主要功能是通过 socket 通道向 Zygote 进程发送一个参数列表,然后进入阻塞等待状态,直到远端的socket服务端发送回来新创建的进程 pid 才返回。
system_server 向 zygote 进程发送消息后就唤醒了 zygote 进程,来响应 socket 客户端的请求,接下来 zygote 开始创建进程。
6. Zygote fork 新进程 6.1 Zygote fork 流程 6.1.1 runSelectLoop() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 Runnable runSelectLoop (String abiList) { ArrayList<FileDescriptor> socketFDs = new ArrayList <>(); ArrayList<ZygoteConnection> peers = new ArrayList <>(); socketFDs.add(mZygoteSocket.getFileDescriptor()); peers.add(null ); while (true ) { ... try { pollReturnValue = Os.poll(pollFDs, pollTimeoutMs); ... while (--pollIndex >= 0 ) { if ((pollFDs[pollIndex].revents & POLLIN) == 0 ) { continue ; } if (pollIndex == 0 ) { ZygoteConnection newPeer = acceptCommandPeer(abiList); peers.add(newPeer); socketFDs.add(newPeer.getFileDescriptor()); } else if (pollIndex < usapPoolEventFDIndex) { try { ZygoteConnection connection = peers.get(pollIndex); boolean multipleForksOK = !isUsapPoolEnabled() && ZygoteHooks.isIndefiniteThreadSuspensionSafe(); final Runnable command = connection.processCommand(this , multipleForksOK);
Zygote 服务端收到客户端请求,创建 ZygoteConnection 对象,调用其 processCommand()
处理收到的数据;
6.1.2 processCommand() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 Runnable processCommand (ZygoteServer zygoteServer, boolean multipleOK) { pid = Zygote.forkAndSpecialize(...); if (pid == 0 ) { zygoteServer.setForkChild(); zygoteServer.closeServerSocket(); IoUtils.closeQuietly(serverPipeFd); serverPipeFd = null ; return handleChildProc(parsedArgs, childPipeFd, parsedArgs.mStartChildZygote); } else { IoUtils.closeQuietly(childPipeFd); childPipeFd = null ; handleParentProc(pid, serverPipeFd); return null ; }
调用 forkAndSpecialize() fork 出子进程,函数返回两次;
6.1.3 forkAndSpecialize() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 static int forkAndSpecialize (int uid, int gid, int [] gids, int runtimeFlags, int [][] rlimits, int mountExternal, String seInfo, String niceName, int [] fdsToClose, int [] fdsToIgnore, boolean startChildZygote, String instructionSet, String appDataDir, boolean isTopApp, String[] pkgDataInfoList, String[] allowlistedDataInfoList, boolean bindMountAppDataDirs, boolean bindMountAppStorageDirs) { ZygoteHooks.preFork(); int pid = nativeForkAndSpecialize( uid, gid, gids, runtimeFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose, fdsToIgnore, startChildZygote, instructionSet, appDataDir, isTopApp, pkgDataInfoList, allowlistedDataInfoList, bindMountAppDataDirs, bindMountAppStorageDirs); ... }
fork 出一个新的进程,通过 JNI 调用 nativeForAndSpecialize() 函数,对应的是 com_android_internal_os_Zygote_nativeForkAndSpecialize()
。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 static jint com_android_internal_os_Zygote_nativeForkAndSpecialize ( JNIEnv* env, jclass, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray managed_fds_to_close, jintArray managed_fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app, jobjectArray pkg_data_info_list, jobjectArray allowlisted_data_info_list, jboolean mount_data_dirs, jboolean mount_storage_dirs) { ... pid_t pid = zygote::ForkCommon (env, false , fds_to_close, fds_to_ignore, true ); if (pid == 0 ) { SpecializeCommon (env, uid, gid, gids, runtime_flags, rlimits, capabilities, capabilities, mount_external, se_info, nice_name, false , is_child_zygote == JNI_TRUE, instruction_set, app_data_dir, is_top_app == JNI_TRUE, pkg_data_info_list, allowlisted_data_info_list, mount_data_dirs == JNI_TRUE, mount_storage_dirs == JNI_TRUE); } return pid; }
6.1.5 ForkCommon 1 2 3 4 5 6 7 8 pid_t zygote::ForkCommon (JNIEnv* env, bool is_system_server, const std::vector<int >& fds_to_close, const std::vector<int >& fds_to_ignore, bool is_priority_fork, bool purge) { ... pid_t pid = fork();
fork() 采用写时拷贝(copy on write),即如果 fork 完什么也不做,其实内存中并没有为子进程分配物理内存,父子进程共用同一份物理内存,只有当父子进程任一方修改内存数据时(on write 时机),才会分配新的物理内存,fork() 函数调用一次,返回两次,返回值有 3 种类型:
子进程:fork() 返回 0;
父进程:fork() 返回子进程 pid;
< 0:fork() 失败(当进程数超过上限或者系统内存不足时会 fork 失败);
fork() 的主要工作是寻找空闲的进程号 pid,然后从父进程拷贝进程信息,例如数据段和代码段、fork() 后子进程要执行的代码等;
到这里 app 进程已经创建,fork() 返回 pid 后根据 pid 的值分别进入子进程和父进程执行 handleChildProc()
和 handleParentProc()
;
6.2 fork 后父进程工作 handleParentProc() 1 2 3 4 5 6 private void handleParentProc (int pid, FileDescriptor pipeFd) { ... try { mSocketOutStream.writeInt(pid); mSocketOutStream.writeBoolean(usingWrapper);
fork 成功后 zygote 进程通过 socket 返回数据;
6.3 fork 后子进程工作 1 2 3 4 5 6 7 8 9 10 11 12 13 14 pid = Zygote.forkAndSpecialize(...); try { if (pid == 0 ) { zygoteServer.setForkChild(); zygoteServer.closeServerSocket(); IoUtils.closeQuietly(serverPipeFd); serverPipeFd = null ; return handleChildProc(parsedArgs, childPipeFd, parsedArgs.mStartChildZygote); }
6.3.1 handleChildProc 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 private Runnable handleChildProc (ZygoteArguments parsedArgs, FileDescriptor pipeFd, boolean isZygote) { closeSocket(); Zygote.setAppProcessName(parsedArgs, TAG); if (parsedArgs.mInvokeWith != null ) { ... } else { if (!isZygote) { return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion, parsedArgs.mDisabledCompatChanges, parsedArgs.mRemainingArgs, null ); } else { return ZygoteInit.childZygoteInit( parsedArgs.mRemainingArgs ); } } }
6.3.2 zygoteInit 1 2 3 4 5 6 7 8 9 10 public static Runnable zygoteInit (int targetSdkVersion, long [] disabledCompatChanges, String[] argv, ClassLoader classLoader) { ... RuntimeInit.commonInit(); ZygoteInit.nativeZygoteInit(); return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv, classLoader); }
6.3.3 nativeZygoteInit() 在 forkSystemServer() 流程 中已经分析,就是调用 open() 打开 /dev/binder 驱动设备,再使用 mmap() 映射内核地址空间,将 Binder 驱动的 fd 赋值给 ProcessState 对象中的变量 mDriveFD,创建一个新的 binder 线程池,通过 talkWithDriver() 与驱动通信;
6.3.4 applicationInit 1 2 3 4 5 6 7 8 9 protected static Runnable applicationInit (int targetSdkVersion, long [] disabledCompatChanges, String[] argv, ClassLoader classLoader) { ... final Arguments args = new Arguments (argv); ... return findStaticMain(args.startClass, args.startArgs, classLoader); }
回忆一下前面 ProcessList.java:2043 行的 entryPoint 的值,这里的 startClass 是 entryPoint(android.app.ActivityThread),接下来的操作也在 forkSystemServer() 流程 中已经分析,最终就是通过反射获取到 startClass 的 main() 函数,返回一个 Runnable,然后在 ZygoteInit.main() 中调用 caller.run();
启动 ActivityThread.main();
7. APP 进程向 system_server 发起 attachApplication[Binder] attach() -> attachApplication() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public static void main (String[] args) { Environment.initForCurrentUser(); Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread (); thread.attach(false , startSeq); if (sMainThreadHandler == null ) { sMainThreadHandler = thread.getHandler(); } Looper.loop(); } final ApplicationThread mAppThread = new ApplicationThread (); private void attach (boolean system, long startSeq) { RuntimeInit.setApplicationObject(mAppThread.asBinder()); final IActivityManager mgr = ActivityManager.getService(); try { mgr.attachApplication(mAppThread, startSeq);
通过 Binder 调用 AMS.attachApplication(),并传入 app 的 Binder 对象 mAppThread。
8. system_server 请求 APP bindeApplication[Binder] system_server 收到请求后向 app binder线程(ApplicationThread) 请求 bindeApplication[Binder 通信];
8.1 attachApplication() 1 2 3 4 5 6 7 8 9 10 11 12 13 public final void attachApplication (IApplicationThread thread, long startSeq) { if (thread == null ) { throw new SecurityException ("Invalid application interface" ); } synchronized (this ) { int callingPid = Binder.getCallingPid(); final int callingUid = Binder.getCallingUid(); final long origId = Binder.clearCallingIdentity(); attachApplicationLocked(thread, callingPid, callingUid, startSeq); Binder.restoreCallingIdentity(origId); } }
在 binder 远程调用的时候,服务端在执行 binder_thread_read() 过程中会把客户端线程的 pid 和 uid 保存到 binder_transaction_data 对象中传递到用户空间,然后在处理 BR_TRANSACTION 的时候把内核传递过来的客户端的 pid 和 uid 赋值给到服务端的 IPCThreadState 的 mCallingPid 和 mCallingUid,所以此处
Binder.getCallingPid() / Binder.getCallingUid():返回 binder 调用端的 pid 和 uid;
Binder.clearCallingIdentity():把 binder 调用端的 pid 和 uid 保存到一个 token(origId) 并返回,然后用当前线程(服务端)的 pid 和 uid 赋值给服务端 IPCThreadState 的 mCallingPid 和 mCallingUid 变量;
restoreCallingIdentity():把 origId 中保存的调用端的 pid 和 uid 恢复到服务端 IPCThreadState 的 mCallingPid 和 mCallingUid 变量;
8.2 attachApplicationLocked 1 2 3 4 5 6 7 8 9 10 11 12 13 private boolean attachApplicationLocked (@NonNull IApplicationThread thread, int pid, int callingUid, long startSeq) { thread.bindApplication(...); ... if (normalMode) { try { didSomething = mAtmInternal.attachApplication(app.getWindowProcessController()); } catch (Exception e) { Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); badApp = true ; } }
thread 是 app 进程传过来的 binder 对象,attachApplicationLocked 做了两件重要的事:
thread.bindApplication:创建 Application 并启动其 onCreate() 方法;
mAtmInternal.attachApplication:创建 Activity,并启动其 onCreate()/onResume() 等方法;
9. 创建 Application/Activity 9.1 初始化 Application 进程并启动 onCreate() 1 2 3 4 5 public final void bindApplication (...) { ... sendMessage(H.BIND_APPLICATION, data); }
通过 Handler 发送 BIND_APPLICATION 消息,app 进程的 looper 从 MessageQueue 取出消息,在 handleMessage() 中处理:
1 2 3 4 5 6 7 8 9 10 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 = (AppBindData)msg.obj; handleBindApplication(data); Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); break ;
调用 handleBindApplication()
1 2 3 4 5 6 7 8 9 10 11 private void handleBindApplication (AppBindData data) { ... Process.setArgV0(data.processName); android.ddm.DdmHandleAppName.setAppName(data.processName, data.appInfo.packageName, UserHandle.myUserId()); VMRuntime.setProcessPackageName(data.appInfo.packageName); final ContextImpl appContext = ContextImpl.createAppContext(this , data.info); Application app; app = data.info.makeApplication(data.restrictedBackupMode, null ); mInstrumentation.callApplicationOnCreate(app);
创建 Application,然后通过 callApplicationOnCreate()
启动 Application.onCreate()
方法;
1 2 3 4 public void callApplicationOnCreate (Application app) { app.onCreate(); }
到这里应用程序的 Application 中的 onCreate() 方法就执行了;
9.2 创建 Activity 1 2 3 4 5 6 public ActivityTaskManagerInternal mAtmInternal; private boolean attachApplicationLocked (...) { ... didSomething = mAtmInternal.attachApplication(app.getWindowProcessController()); }
调用 ActivityTaskManagerInternal.attachApplication() 方法;
1 2 3 4 5 6 public boolean attachApplication (WindowProcessController wpc) throws RemoteException { synchronized (mGlobalLockWithoutBoost) { ... return mRootWindowContainer.attachApplication(wpc); ...
调用 RootWindowContainer.attachApplication() 方法;
1 2 3 4 5 6 7 8 9 boolean attachApplication (WindowProcessController app) throws RemoteException { boolean didSomething = false ; ... final PooledFunction c = PooledLambda.obtainFunction( RootWindowContainer::startActivityForAttachedApplicationIfNeeded, this , PooledLambda.__(ActivityRecord.class), app, rootTask.topRunningActivity()); ...
调用 RootWindowContainer.startActivityForAttachedApplicationIfNeeded() 方法;
1 2 3 4 5 6 7 8 9 ActivityTaskSupervisor mTaskSupervisor; private boolean startActivityForAttachedApplicationIfNeeded (ActivityRecord r, WindowProcessController app, ActivityRecord top) { ... if (mTaskSupervisor.realStartActivityLocked(r, app, top == r && r.isFocusable() , true )) { mTmpBoolean = true ; ...
最终又调用到了 realStartActivityLocked()
,流程和前面 [第 4 小节](# 4. App 进程已存在) 一样,app 的 looper 处理 EXECUTE_TRANSACTION
命令,启动 Activity。
10. 总结 点击 Launcher 中的 icon 可以启动 APP,APP 启动流程分为如下阶段:
Launcher 通过 Binder 向 system_server 进程发起 startActivity 请求;
system_server 通过 socket 向 zygote 发起创建进程请求;
zygote 进程 fork 出 app 子进程,通过 socket 返回 pid 给 system_server 进程;
app 子进程通过 Binder 向 system_server 进程发起 attachApplication 请求;
system_server 进程通过 Binder 向 app 进程发送 binderApplication 请求;
app 进程的 binder 线程(ApplicationThread)收到请求后通过 Handler 向 app 主线程发送 BIND_APPLICATION 消息,ActivityThread 通过 handleBindApplication() 创建 Application 并执行其 onCreate() 方法;
system_server 进程通过 Binder 向 app 进程发送 scheduleTransaction 请求;
app 进程的 binder 线程(ApplicationThread)收到请求后通过 Handler 向 app 主线程发送 EXECUTE_TRANSACTION 消息;
app 主线程收到 Message 后通过反射机制 创建目标 Activity ;
app 正式启动,进入 Activity 生命周期,执行 onCreate/onStart/onResume,UI 渲染结束进入 app 主界面;
APP 启动涉及了多个进程之间的交互,使用了 Binder/Socket 进程间通信机制,Handler 线程间通信机制。