Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

深入解析 Android 7.0 應用冷啟動的完整流程

編輯:Android 資訊

近期為自己的 Moto G 定製 ROM,順便把 Android 7.0 的相關源碼重新梳理了一遍,於是整理成這篇筆記,記錄下應用啟動的來龍去脈。

正式進入主題之前,有必要先釐清「冷啟動」與「熱啟動」這兩個概念。所謂冷啟動,指的是啟動某個應用時,系統後台並不存在該應用的進程,此時系統需要為它創建一個全新進程——AMS 透過 Socket 與 Zygote 溝通,Zygote 再呼叫 forkAndSpecialize() 向 Linux 內核申請新進程,隨後創建並初始化 Application,最後透過反射執行 ActivityThread 中的 main 方法。而熱啟動則不同:當應用啟動時,後台已存在對應進程(例如按下 Home 鍵回到桌面後再次打開該應用),系統會直接複用已有進程來拉起應用,這條路徑不會重新走一遍 Application 的初始化流程。

本文聚焦於應用冷啟動的完整過程。在梳理源碼的過程中我發現,從 Android 2.3 到 Android 7.0,啟動流程的整體骨架變化並不大,因此下文的分析對大多數版本都具有一定的通用性。另外,為了讓更多讀者能順暢閱讀,文中刻意略去了 Binder 相關的細節。

從點擊 Launcher 圖標說起

Launcher 就是我們日常所說的桌面,它本質上也是一個 apk。當我們點擊桌面上的圖標時,會呼叫 Activity 的 startActivity(),最終落到 startActivityForResult():

public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) { if (mParent == null) { Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options); // 省略多行代碼 } else { // 省略多行代碼 } }

接著,startActivityForResult 會把創建任務委託給 Instrumentation 的 execStartActivity():

public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { //重點關注IApplicationThread IApplicationThread whoThread = (IApplicationThread) contextThread; Uri referrer = target != null ? target.onProvideReferrer() : null; if (referrer != null) { intent.putExtra(Intent.EXTRA_REFERRER, referrer); } if (mActivityMonitors != null) { synchronized (mSync) { final int N = mActivityMonitors.size(); for (int i=0; i<N; i++) { final ActivityMonitor am = mActivityMonitors.get(i); if (am.match(who, null, intent)) { am.mHits++; if (am.isBlocking()) { return requestCode >= 0 ? am.getResult() : null; } break; } } } } try { intent.migrateExtraStreamToClipData(); intent.prepareToLeaveProcess(); // 重點關注ActivityManagerNative int result = ActivityManagerNative.getDefault() .startActivity(whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); checkStartActivityResult(result, intent); } catch (RemoteException e) { throw new RuntimeException("Failure from system", e); } return null; }

仔細看方法簽名,第二個參數 contextThread 是 IBinder 類型,再往下追會發現它其實是 IApplicationThread 的實現類。下面簡要看一下 IApplicationThread 的定義:

public interface IApplicationThread extends IInterface { void schedulePauseActivity(IBinder token, boolean finished, boolean userLeaving, int configChanges, boolean dontReport) throws RemoteException; void scheduleStopActivity(IBinder token, boolean showWindow, int configChanges) throws RemoteException; void scheduleWindowVisibility(IBinder token, boolean showWindow) throws RemoteException; void scheduleSleeping(IBinder token, boolean sleeping) throws RemoteException; void scheduleResumeActivity(IBinder token, int procState, boolean isForward, Bundle resumeArgs) throws RemoteException; void scheduleSendResult(IBinder token, List<ResultInfo> results) throws RemoteException; void scheduleLaunchActivity(Intent intent, IBinder token, int ident, ActivityInfo info, Configuration curConfig, Configuration overrideConfig, CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state, PersistableBundle persistentState, List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents, boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) throws RemoteException; void scheduleRelaunchActivity(IBinder token, List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents, int configChanges, boolean notResumed, Configuration config, Configuration overrideConfig) throws RemoteException; void scheduleNewIntent(List<ReferrerIntent> intent, IBinder token) throws RemoteException; void scheduleDestroyActivity(IBinder token, boolean finished, int configChanges) throws RemoteException; void scheduleReceiver(Intent intent, ActivityInfo info, CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras, boolean sync, int sendingUser, int processState) throws RemoteException; // 省略多個方法 void scheduleBindService(IBinder token, Intent intent, boolean rebind, int processState) throws RemoteException; void scheduleUnbindService(IBinder token, Intent intent) throws RemoteException; //省略多個方法 void scheduleStopService(IBinder token) throws RemoteException; //省略多個方法 void bindApplication(String packageName, ApplicationInfo info, List<ProviderInfo> providers, ComponentName testName, ProfilerInfo profilerInfo, Bundle testArguments, IInstrumentationWatcher testWatcher, IUiAutomationConnection uiAutomationConnection, int debugMode, boolean openGlTrace, boolean restrictedBackupMode, boolean persistent, Configuration config, CompatibilityInfo compatInfo, Map<String, IBinder> services, Bundle coreSettings) throws RemoteException; void scheduleExit() throws RemoteException; // 省略多行代碼 void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent, int resultCode, String data, Bundle extras, boolean ordered, boolean sticky, int sendingUser, int processState) throws RemoteException; void scheduleLowMemory() throws RemoteException; void scheduleActivityConfigurationChanged(IBinder token, Configuration overrideConfig) throws RemoteException; //省略多個方法 void scheduleTrimMemory(int level) throws RemoteException; //省略多個方法 }

通讀 IApplicationThread 的代碼後,不少方法名都給人一種似曾相識的感覺:schedulePauseActivity 顯然負責 Activity 的 Pause(),scheduleLaunchActivity() 負責 Activity 的創建,scheduleBindService() 則負責 Service 的綁定。由此不難推斷,IApplicationThread 的真正實現類 ApplicationThread(位於 ActivityThread.java 中)才是負責 Activity、Service 等創建與各項操作的關鍵角色。先來看一下它的類關係圖:

回到 Instrumentation 的 execStartActivity() 方法,我們繼續往下看:

int result = ActivityManagerNative.getDefault() .startActivity(whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);

此時,啟動 Activity 這一動作被交到了 ActivityManagerNative.getDefault() 的 startActivity() 方法手裡。ActivityManagerNative 是一個抽象類,它繼承了 Binder,同時又實現了 IActivityManager 接口,其具體實現類正是 ActivityManagerService(AMS)。

ActivityManagerNative.getDefault() 返回的是一個 IActivityManager 類型的對象,其實現類為 ActivityManagerProxy,而它的構造函數接收一個 IBinder 類型參數,本質上就是 ActivityManagerService 對象。至此,ActivityManagerNative、IActivityManager 與 ActivityManagerProxy 三者之間的關係便清晰起來:

從上圖可以看出,這三者構成了典型的代理模式:ActivityManagerProxy 是 ActivityManagerService 的遠端代理,而 ActivityManagerNative 的作用也就不言自明——返回 AMS 的遠端代理對象,從而使 Launcher 應用得以與 AMS 服務進行通信。

我們用一張流程圖來概括上述過程:

走進 ActivityManagerService

現在讓我們跳進 AMS 的 startActivity() 方法,繼續追蹤:

@Override public int startActivity(IBinder whoThread, String callingPackage, Intent intent, String resolvedType, Bundle options) { checkCaller(); int callingUser = UserHandle.getCallingUserId(); TaskRecord tr; IApplicationThread appThread; synchronized (ActivityManagerService.this) { tr = mStackSupervisor.anyTaskForIdLocked(mTaskId); if (tr == null) { throw new IllegalArgumentException("Unable to find task ID " + mTaskId); } appThread = ApplicationThreadNative.asInterface(whoThread); if (appThread == null) { throw new IllegalArgumentException("Bad app thread " + appThread); } } //交給mStackSupervisor繼續 return mStackSupervisor.startActivityMayWait(appThread, -1, callingPackage, intent, resolvedType, null, null, null, null, 0, 0, null, null, null, options, false, callingUser, null, tr); }

首先要注意到,該方法的第一個參數是 IBinder 類型,其本質正是前面提到的 ApplicationThread 實例,也就是 ActivityThread 中的 mAppThread 對象。隨後,流程被交給 ActivityStackSupervisor 實例的 startActivityMayWait() 繼續處理:

final int startActivityMayWait(IApplicationThread caller, int callingUid, String callingPackage, Intent intent, String resolvedType, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, WaitResult outResult, Configuration config, Bundle options, boolean ignoreTargetSecurity, int userId, IActivityContainer iContainer, TaskRecord inTask) { // Refuse possible leaked file descriptors if (intent != null && intent.hasFileDescriptors()) { throw new IllegalArgumentException("File descriptors passed in Intent"); } boolean componentSpecified = intent.getComponent() != null; // Don't modify the client's object! intent = new Intent(intent); // Collect information about the target of the Intent. ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags, profilerInfo, userId); ActivityContainer container = (ActivityContainer)iContainer; synchronized (mService) { //省略多行代碼 int res = startActivityLocked(caller, intent, resolvedType, aInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options, ignoreTargetSecurity, componentSpecified, null, container, inTask); // 省略多行代碼 return res; } }

這個方法乍看起來頗為複雜,但主線其實相當清晰:先透過 resolveActivity() 取得 ActivityInfo,接著做一系列其他處理(在不影響主流程的前提下省略部分代碼),然後繼續呼叫 startActivityLocked():

final int startActivityLocked(IApplicationThread caller, Intent intent, String resolvedType, ActivityInfo aInfo, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid, String callingPackage, int realCallingPid, int realCallingUid, int startFlags, Bundle options, boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity, ActivityContainer container, TaskRecord inTask) { int err = ActivityManager.START_SUCCESS; //省略多行代碼 err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true, options, inTask); return err; }

在這個方法裡,又接著呼叫了 startActivityUncheckedLocked()。撇開細節不談,可以發現它內部再繼續呼叫 ActivityStack 的 resumeTopActivityLocked() 來推進啟動流程:

 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) { if (mStackSupervisor.inResumeTopActivity) { // Don't even start recursing. return false; } boolean result = false; try { // Protect against recursion. mStackSupervisor.inResumeTopActivity = true; if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) { mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN; mService.updateSleepIfNeededLocked(); } //繼續啟動 result = resumeTopActivityInnerLocked(prev, options); } finally { mStackSupervisor.inResumeTopActivity = false; } return result; }

從上面的代碼不難看出,resumeTopActivitiesLocked() 方法又呼叫了 resumeTopActivityInnerLocked(),而該方法內部反過來又呼叫了 ActivityStackSupervisor 的 resumeTopActivitiesLocked():

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) { //省略多行代碼 mStackSupervisor.startSpecificActivityLocked(next, true, false); if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); return true; }

由於應用是首次啟動,這裡跳過了一些判斷邏輯,最終又呼叫 ActivityStackSupervisor 的 startSpecificActivityLocked() 來繼續推進:

void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) { // Is this activity's application already running? ProcessRecord app = mService.getProcessRecordLocked(r.processName, r.info.applicationInfo.uid, true); r.task.stack.setLaunchTime(r); //該應用的進程已經存在 if (app != null && app.thread != null) { try { if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0 || !"android".equals(r.info.packageName)) { app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode, mService.mProcessStats); } realStartActivityLocked(r, app, andResume, checkConfig); return; } catch (RemoteException e) { Slog.w(TAG, "Exception when starting activity " + r.intent.getComponent().flattenToShortString(), e); } } //該應用的進程尚未創建,調用AMS的startProcessLocked() mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0, "activity", r.intent.getComponent(), false, false, true); }

因為應用是首次啟動,此時系統尚未為它創建進程,所以會呼叫 AMS 的 startProcessLocked() 方法;如果應用進程已存在,則改走 realStartActivityLocked()。既然這裡是首次啟動,我們就沿著 startProcessLocked() 繼續往下看:

final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName, boolean allowWhileBooting, boolean isolated, boolean keepIfLarge) { return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,hostingName, allowWhileBooting, isolated, 0 , keepIfLarge,null , null , null,null); }

該方法直接呼叫了對應的重載版本,並在重載方法中繼續往下呼叫:

 private final void startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) { long startTime = SystemClock.elapsedRealtime(); //省略多行代碼 boolean isActivityProcess = (entryPoint == null); //默認情況下,entryPoint為null,此時虛擬機啟動後默認從ActivityThread的main()方法執行 if (entryPoint == null) entryPoint = "android.app.ActivityThread"; Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " + app.processName); //要求Zygote進程為其創建進程 checkTime(startTime, "startProcess: asking zygote to start proc"); Process.ProcessStartResult startResult = Process.start(entryPoint, app.processName, uid, uid, gids, debugFlags, mountExternal, app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet, app.info.dataDir, entryPointArgs); checkTime(startTime, "startProcess: returned from zygote!"); Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); //省略多行代碼 } catch (RuntimeException e) { //省略 } }

同樣地,我們用一張圖來描繪這一階段:

走進 Zygote

這裡透過 Process 的 start() 方法,向 Zygote 進程發出創建新進程的請求;而在 start() 內部又直接呼叫了 startViaZygote():

//processClass是調用者傳的android.app.ActivityThread private static ProcessStartResult startViaZygote(final String processClass, final String niceName, final int uid, final int gid, final int[] gids, int debugFlags, int mountExternal, int targetSdkVersion, String seInfo, String abi, String instructionSet, String appDataDir, String[] extraArgs) throws ZygoteStartFailedEx { synchronized(Process.class) { ArrayList<String> argsForZygote = new ArrayList<String>(); // --runtime-args, --setuid=, --setgid=, // and --setgroups= must go first //--runtime-agrs決定了新建進程執行方式, argsForZygote.add("--runtime-args"); argsForZygote.add("--setuid=" + uid); argsForZygote.add("--setgid=" + gid); if ((debugFlags & Zygote.DEBUG_ENABLE_JNI_LOGGING) != 0) { argsForZygote.add("--enable-jni-logging"); } if ((debugFlags & Zygote.DEBUG_ENABLE_SAFEMODE) != 0) { argsForZygote.add("--enable-safemode"); } if ((debugFlags & Zygote.DEBUG_ENABLE_DEBUGGER) != 0) { argsForZygote.add("--enable-debugger"); } if ((debugFlags & Zygote.DEBUG_ENABLE_CHECKJNI) != 0) { argsForZygote.add("--enable-checkjni"); } if ((debugFlags & Zygote.DEBUG_ENABLE_JIT) != 0) { argsForZygote.add("--enable-jit"); } if ((debugFlags & Zygote.DEBUG_GENERATE_DEBUG_INFO) != 0) { argsForZygote.add("--generate-debug-info"); } if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) { argsForZygote.add("--enable-assert"); } if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) { argsForZygote.add("--mount-external-default"); } else if (mountExternal == Zygote.MOUNT_EXTERNAL_READ) { argsForZygote.add("--mount-external-read"); } else if (mountExternal == Zygote.MOUNT_EXTERNAL_WRITE) { argsForZygote.add("--mount-external-write"); } argsForZygote.add("--target-sdk-version=" + targetSdkVersion); //TODO optionally enable debuger //argsForZygote.add("--enable-debugger"); // --setgroups is a comma-separated list if (gids != null && gids.length > 0) { StringBuilder sb = new StringBuilder(); sb.append("--setgroups="); int sz = gids.length; for (int i = 0; i < sz; i++) { if (i != 0) { sb.append(','); } sb.append(gids[i]); } argsForZygote.add(sb.toString()); } if (niceName != null) { argsForZygote.add("--nice-name=" + niceName); } if (seInfo != null) { argsForZygote.add("--seinfo=" + seInfo); } if (instructionSet != null) { argsForZygote.add("--instruction-set=" + instructionSet); } if (appDataDir != null) { argsForZygote.add("--app-data-dir=" + appDataDir); } argsForZygote.add(processClass); if (extraArgs != null) { for (String arg : extraArgs) { argsForZygote.add(arg); } } return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote); } }

這個方法本身並不複雜:把一堆參數組織好之後,再呼叫 zygoteSendArgsAndGetResult() 向 Zygote 發出創建進程的請求,該方法內部正是透過 Socket 與 Zygote 進行通信。Zygote 收到請求後,會將其封裝為 ZygoteConnection 對象,相關代碼位於 ZygoteInit.java 中,具體可參考 runSelectLoop():

private static void runSelectLoop(String abiList) throws MethodAndArgsCaller { ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>(); ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>(); fds.add(sServerSocket.getFileDescriptor()); peers.add(null); while (true) { StructPollfd[] pollFds = new StructPollfd[fds.size()]; for (int i = 0; i < pollFds.length; ++i) { pollFds[i] = new StructPollfd(); pollFds[i].fd = fds.get(i); pollFds[i].events = (short) POLLIN; } try { Os.poll(pollFds, -1); } catch (ErrnoException ex) { throw new RuntimeException("poll failed", ex); } for (int i = pollFds.length - 1; i >= 0; --i) { if ((pollFds[i].revents & POLLIN) == 0) { continue; } if (i == 0) { //接受來自AMS的請求 ZygoteConnection newPeer = acceptCommandPeer(abiList); peers.add(newPeer); fds.add(newPeer.getFileDesciptor()); } else { boolean done = peers.get(i).runOnce(); if (done) { peers.remove(i); fds.remove(i); } } } } }

此時,Zygote 作為服務端不斷監聽來自 AMS 的請求,透過 acceptCommandPeer() 把請求封裝成 ZygoteConnection 對象,將 Socket 文件標識存入 fds,請求則放入 peers;而 runOnce() 會在下一輪循環中真正處理這些請求,具體代碼如下:

boolean runOnce() throws ZygoteInit.MethodAndArgsCaller { String args[]; Arguments parsedArgs = null; FileDescriptor[] descriptors; try { //讀取請求中的參數 args = readArgumentList(); descriptors = mSocket.getAncillaryFileDescriptors(); } catch (IOException ex) { Log.w(TAG, "IOException on command socket " + ex.getMessage()); closeSocket(); return true; } //省略多行代碼 /** the stderr of the most recent request, if avail */ PrintStream newStderr = null; if (descriptors != null && descriptors.length >= 3) { newStderr = new PrintStream( new FileOutputStream(descriptors[2])); } int pid = -1; FileDescriptor childPipeFd = null; FileDescriptor serverPipeFd = null; try { //將請求參數封裝成Arguments對象 parsedArgs = new Arguments(args); //省略多行代碼 //創建新進程或者說創建VM實例 pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo, parsedArgs.niceName, fdsToClose, parsedArgs.instructionSet,parsedArgs.appDataDir); } catch (ErrnoException ex) { //省略多行代碼 } try { if (pid == 0) {//pid=0表示剛才fork出的子進程 IoUtils.closeQuietly(serverPipeFd); serverPipeFd = null; handleChildProc(parsedArgs, descriptors, childPipeFd, newStderr); // should never get here, the child is expected to either // throw ZygoteInit.MethodAndArgsCaller or exec(). return true; } else { // in parent...pid of < 0 means failure IoUtils.closeQuietly(childPipeFd); childPipeFd = null; return handleParentProc(pid, descriptors, serverPipeFd, parsedArgs); } } finally { IoUtils.closeQuietly(childPipeFd); IoUtils.closeQuietly(serverPipeFd); } }

這段代碼相對簡單,核心就是讀取請求參數並將其封裝為 Arguments 對象。Arguments 中包含以下這些參數:

--setuid= --setgid= --target-sdk-version= --enable-debugger --enable-safemode --enable-checkjni --enable-jit --generate-debug-info --enable-jni-logging --enable-assert --runtime-args --seinfo= --capabilities= --rlimit= --setgroups= --invoke-with --nice-name= --mount-external-default --mount-external-read --mount-external-write --query-abi-list --instruction-set= --app-data-dir=

接著透過 Zygote 的 forkAndSpecialize() 生成新進程,成功後子進程中 pid 的值為 0。這裡我們只關注創建成功的情形:此後新進程會關閉從 Zygote 繼承而來的 Socket,然後透過 handleChildProc() 繼續後續操作。

private void handleChildProc(Arguments parsedArgs, FileDescriptor[] descriptors, FileDescriptor pipeFd, PrintStream newStderr) throws ZygoteInit.MethodAndArgsCaller { //關閉AMS和Zygote之間的Socket連接 closeSocket(); ZygoteInit.closeServerSocket(); if (descriptors != null) { try { Os.dup2(descriptors[0], STDIN_FILENO); Os.dup2(descriptors[1], STDOUT_FILENO); Os.dup2(descriptors[2], STDERR_FILENO); for (FileDescriptor fd: descriptors) { IoUtils.closeQuietly(fd); } newStderr = System.err; } catch (ErrnoException ex) { Log.e(TAG, "Error reopening stdio", ex); } } if (parsedArgs.niceName != null) { Process.setArgV0(parsedArgs.niceName); } // End of the postFork event. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); if (parsedArgs.invokeWith != null) { //通過系統調用執行進程 WrapperInit.execApplication(parsedArgs.invokeWith, parsedArgs.niceName, parsedArgs.targetSdkVersion, VMRuntime.getCurrentInstructionSet(), pipeFd, parsedArgs.remainingArgs); } else { //尋找相應目標類的main()方法並執行 RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, null /* classLoader */); } }

這裡會根據 invokeWith 參數決定採用哪種執行方式:invokeWith 不為空時透過 WrapperInit 執行,否則透過 RuntimeInit 執行。對於這兩者這裡不做過多展開,只需記住——由於 --runtime-args 決定了新進程都以 RuntimeInit 方式啟動,目前只要知道 SystemServer 和 apk 都是走 RuntimeInit 這條路即可。

走進 RuntimeInit

接著來看 RuntimeInit 的 zygoteInit() 方法:

public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) throws ZygoteInit.MethodAndArgsCaller { if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from zygote"); Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "RuntimeInit"); redirectLogStreams(); commonInit(); nativeZygoteInit(); applicationInit(targetSdkVersion, argv, classLoader); }

commonInit() 為虛擬機設置了默認的線程異常處理器,隨後呼叫本地方法 nativeZygoteInit(),其具體實現在 AndroidRuntime.cpp 中,位於 frameworks/base/core/jni/AndroidRuntime.cpp:

static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz) { gCurRuntime->onZygoteInit(); }

該方法內部又呼叫了其子類 AppRuntime 的 onZygoteInit(),AppRuntime 位於 frameworks/base/cmds/app_process/app_main.cpp:

virtual void onZygoteInit() { sp<ProcessState> proc = ProcessState::self(); ALOGV("App process: starting thread pool.\n"); proc->startThreadPool(); }

為了不打斷後文的脈絡,我們先回到 RuntimeInit 的 applicationInit():

private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) throws ZygoteInit.MethodAndArgsCaller { nativeSetExitWithoutCleanup(true); //VM設置 VMRuntime.getRuntime().setTargetHeapUtilization(0.75f); VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion); final Arguments args; try { args = new Arguments(argv); } catch (IllegalArgumentException ex) { Slog.e(TAG, ex.getMessage()); // let the process exit return; } Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); //反射執行ActivityThread的main函數 invokeStaticMain(args.startClass, args.startArgs, classLoader); }

其中最关键的就是 invokeStaticMain() 方法:

private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader) throws ZygoteInit.MethodAndArgsCaller { Class<?> cl; try { cl = Class.forName(className, true, classLoader); } catch (ClassNotFoundException ex) { throw new RuntimeException( "Missing class when invoking static main " + className, ex); } Method m; try { m = cl.getMethod("main", new Class[] { String[].class }); } catch (NoSuchMethodException ex) { throw new RuntimeException( "Missing static main on " + className, ex); } catch (SecurityException ex) { throw new RuntimeException( "Problem getting static main on " + className, ex); } int modifiers = m.getModifiers(); if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) { throw new RuntimeException( "Main method is not public and static on " + className); } //該異常會在ZygoteInit.main()中被捕獲,然後在異常處理中調用MethodAndArgsCaller的run() //方法,這樣就清除了進程中所有的棧幀 throw new ZygoteInit.MethodAndArgsCaller(m, argv); }

可以看到,最終的執行是透過拋出 MethodAndArgsCaller 這種方式來完成的。一起來看看 MethodAndArgsCaller 類的定義:

public static class MethodAndArgsCaller extends Exception implements Runnable { /** method to call */ private final Method mMethod; /** argument array */ private final String[] mArgs; public MethodAndArgsCaller(Method method, String[] args) { mMethod = method; mArgs = args; } public void run() { try { mMethod.invoke(null, new Object[] { mArgs }); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { Throwable cause = ex.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof Error) { throw (Error) cause; } throw new RuntimeException(ex); } } }

MethodAndArgsCaller 繼承了 Exception 類並實現了 Runnable 接口。無論如何,此時終於迎來了 ActivityThread 的入口函數 main() 的執行:

public static void main(String[] args) { Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain"); SamplingProfilerIntegration.start(); CloseGuard.setEnabled(false); Environment.initForCurrentUser(); EventLogger.setReporter(new EventLoggingReporter()); AndroidKeyStoreProvider.install(); final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId()); TrustedCertificateStore.setDefaultUserDirectory(configDir); Process.setArgV0("<pre-initialized>"); Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false); 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"); }

當 main() 開始運行,主線程也就正式啟動了,這正是我們所說的 UI 線程。同樣,我們用一張簡圖來描述這一階段:

總結

至此,我們已經完整走完了應用的冷啟動流程。上面的過程乍看繁瑣,但結合時序圖一起看,其實脈絡相當清晰。若拋開種種細節,整個流程可以用下圖概括:

最後,為了便於大家從整体上理解整個流程,再附上一張相對完整的時序圖:

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved