Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

深入剖析 Android 應用的啟動全流程

編輯:關於 Android 程式設計

前言

在正式開始之前,建議您最好先具備兩個前提條件:

     1、手邊有一份已成功編譯的 Android 源碼(親自動手實踐,理解才會更透徹)

     2、對 Binder 機制有基本的認識

本文的啟動流程分析以 Android 5.1 源碼為基礎。為什麼選 5.1?純粹是因為手邊編譯好的代碼剛好只有這個版本。其實用哪個版本並不重要,整體流程本質上並無差別,只是實現細節略有調整,挑一個你熟悉的版本即可。

一、啟動時序圖

作為一個略帶強迫症的人,我整理了一張時序圖,相信諸位按圖索驥,一定能把整個啟動流程摸清楚:

說明:為了讓大家更直觀地理解整個過程,我把時序圖劃分成三個部分——Launcher 進程、System 進程與App 進程。其中涉及共用的類,用 L / A 加以區分,標明它與哪個進程相關,便於理解。

二、關鍵類說明

整個啟動流程會涉及多次 Binder 通信,這裡先簡要交代幾個類的職責,方便大家理清交互脈絡:

      1、ActivityManagerService:AMS 是 Android 最核心的服務之一,主要負責系統四大組件的啟動、切換、調度,以及應用進程的管理與調度,其職責與操作系統中的進程管理模塊頗為相似,地位舉足輕重。它本身也是一個 Binder 的實現類。

      2、Instrumentation:顧名思義,它用來監控應用程序與系統之間的交互。

      3、ActivityThread:應用的入口類,系統通過調用 main 函數開啟消息循環隊列。ActivityThread 所在的線程被稱為應用的主線程(UI 線程)。

      4、ApplicationThread:提供 Binder 通訊接口,AMS 通過代理調用它來執行 App 進程的本地方法。

      5、ActivityManagerProxy:AMS 服務在當前進程的代理類,負責與 AMS 通信。

      6、ApplicationThreadProxy:ApplicationThread 在 AMS 服務中的代理類,負責與 ApplicationThread 通信。

三、流程分析

先交代本次分析的場景:用戶點擊 Launcher 上的應用圖標,直到該應用的主界面展示在用戶眼前。

整個過程涉及跨進程通信,因此我們將其劃分為時序圖中呈現的三個進程:Launcher 進程、System 進程與App 進程。為了既不貼過長的代碼、又能把進程間的交互說清楚,這裡重點講解幾個關鍵交互節點。

從時序圖不難看出,調用鏈相當長,對應的代碼量也不小,而且時序圖僅分析了這一個場景。道阻且長,行則將至!

3.1 Launcher 響應用戶點擊,通知 AMS

Launcher 作為應用的入口,有必要交代一下。我們來看看 Launcher 的代碼片段,它使用的是 packages/apps/Launcher3 的源碼。

 public class Launcher extends Activity implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks, View.OnTouchListener, PageSwitchListener, LauncherProviderChangeListener { ... /** * Launches the intent referred by the clicked shortcut. * * @param v The view representing the clicked shortcut. */ public void onClick(View v) { // Make sure that rogue clicks don't get through while allapps is launching, or after the // view has detached (it's possible for this to happen if the view is removed mid touch). if (v.getWindowToken() == null) { return; } ... Object tag = v.getTag(); if (tag instanceof ShortcutInfo) { onClickAppShortcut(v); } else if (tag instanceof FolderInfo) { ... } else if (v == mAllAppsButton) { onClickAllAppsButton(v); } else if (tag instanceof AppInfo) { startAppShortcutOrInfoActivity(v); } else if (tag instanceof LauncherAppWidgetInfo) { ... } } private void startAppShortcutOrInfoActivity(View v) { ... boolean success = startActivitySafely(v, intent, tag); ... } boolean startActivitySafely(View v, Intent intent, Object tag) { ... try { success = startActivity(v, intent, tag); } catch (ActivityNotFoundException e) { ... } return success; } boolean startActivity(View v, Intent intent, Object tag) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { ... if (user == null || user.equals(UserHandleCompat.myUserHandle())) { // Could be launching some bookkeeping activity startActivity(intent, optsBundle); } else { ... } return true; } catch (SecurityException e) { ... } return false; } }

通過 startActivity 輾轉調用到 Activity:startActivityForResult,隨後又調用至 Instrumentation:execStartActivity,代碼片段如下:

 public class Instrumentation { ... public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { IApplicationThread whoThread = (IApplicationThread) contextThread; ... try { ... int result = ActivityManagerNative.getDefault() .startActivity(whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); ... } catch (RemoteException e) { } return null; } ... }

這裡的 ActivityManagerNative.getDefault 返回的是 ActivityManagerService 的遠程接口,也就是 ActivityManagerProxy 接口。有人可能會問:為什麼是 ActivityManagerProxy?這就牽涉到 Binder 通信了,此處不再展開。通過 Binder 驅動程序,ActivityManagerProxy 與 AMS 服務通信,從而實現跨進程抵達 System 進程。

3.2 AMS 響應 Launcher 進程請求

從上面的流程可知,此時 AMS 應當處理 Launcher 進程發來的請求。請對照時序圖與源碼,我們來看 ActivityStackSupervisor:startActivityUncheckedLocked 方法,目測這個方法已超過 600 行代碼,這裡摘取一些關鍵片段:

 public final class ActivityStackSupervisor implements DisplayListener { ... final int startActivityUncheckedLocked(ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, Bundle options, TaskRecord inTask) { final Intent intent = r.intent; final int callingUid = r.launchedFromUid; ... final boolean launchSingleTop = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP; final boolean launchSingleInstance = r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE; final boolean launchSingleTask = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK; int launchFlags = intent.getFlags(); ... // We'll invoke onUserLeaving before onPause only if the launching // activity did not explicitly state that this is an automated launch. mUserLeaving = (launchFlags & Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0; ... ActivityRecord notTop = (launchFlags & Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP) != 0 ? r : null; // If the onlyIfNeeded flag is set, then we can do this if the activity // being launched is the same as the one making the call... or, as // a special case, if we do not know the caller then we count the // current top activity as the caller. if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) { ... } ... // If the caller is not coming from another activity, but has given us an // explicit task into which they would like us to launch the new activity, // then let's see about doing that. if (sourceRecord == null && inTask != null && inTask.stack != null) { final Intent baseIntent = inTask.getBaseIntent(); final ActivityRecord root = inTask.getRootActivity(); ... // If this task is empty, then we are adding the first activity -- it // determines the root, and must be launching as a NEW_TASK. if (launchSingleInstance || launchSingleTask) { ... } ... } ... if (inTask == null) { if (sourceRecord == null) { // This activity is not being started from another... in this // case we -always- start a new task. if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) == 0 && inTask == null) { Slog.w(TAG, "startActivity called from non-Activity context; forcing " + "Intent.FLAG_ACTIVITY_NEW_TASK for: " + intent); launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK; } } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) { // The original activity who is starting us is running as a single // instance... this new activity it is starting must go on its // own task. launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK; } else if (launchSingleInstance || launchSingleTask) { // The activity being started is a single instance... it always // gets launched into its own task. launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK; } } ... // We may want to try to place the new activity in to an existing task. We always // do this if the target activity is singleTask or singleInstance; we will also do // this if NEW_TASK has been requested, and there is not an additional qualifier telling // us to still place it in a new task: multi task, always doc mode, or being asked to // launch this as a new task behind the current one. if (((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0 && (launchFlags & Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0) || launchSingleInstance || launchSingleTask) { // If bring to front is requested, and no result is requested and we have not // been given an explicit task to launch in to, and // we can find a task that was started with this same // component, then instead of launching bring that one to the front. if (inTask == null && r.resultTo == null) { // See if there is a task to bring to the front. If this is // a SINGLE_INSTANCE activity, there can be one and only one // instance of it in the history, and it is always in its own // unique task, so we do a special search. ActivityRecord intentActivity = !launchSingleInstance ? findTaskLocked(r) : findActivityLocked(intent, r.info); if (intentActivity != null) { ... } } } ... if (r.packageName != null) { // If the activity being launched is the same as the one currently // at the top, then we need to check if it should only be launched // once. ActivityStack topStack = getFocusedStack(); ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(notTop); if (top != null && r.resultTo == null) { if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) { ... } } } else{ ... } boolean newTask = false; boolean keepCurTransition = false; TaskRecord taskToAffiliate = launchTaskBehind && sourceRecord != null ? sourceRecord.task : null; // Should this be considered a new task? if (r.resultTo == null && inTask == null && !addingToTask && (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) { ... if (reuseTask == null) { r.setTask(targetStack.createTaskRecord(getNextTaskId(), newTaskInfo != null ? newTaskInfo : r.info, newTaskIntent != null ? newTaskIntent : intent, voiceSession, voiceInteractor, !launchTaskBehind /* toTop */), taskToAffiliate); ... } else { r.setTask(reuseTask, taskToAffiliate); } ... } else if (sourceRecord != null) { } else if (!addingToTask && (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) { } else if (inTask != null){ } else { } ... targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options); ... return ActivityManager.START_SUCCESS; } ... }

函數經過 intent 標志值的設置,通過 findTaskLocked 函數查找是否已存在這樣的 Task,這裡返回的結果是 null,即 intentActivity 為 null,因此需要創建一個新的 Task 來啟動這個 Activity。此時堆棧頂端的 Activity 是 Launcher,與我們即將啟動的 MainActivity 並非同一個,於是便在一個新建的 Task 中啟動這個 Activity。

經過棧頂檢測後,需要將 Launcher 推入 Paused 狀態,才能啟動新的 Activity。後續調用至 ActivityStack:startPausingLocked,我們來看看這個函數:

 final class ActivityStack { ... final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming, boolean dontWait) { if (mPausingActivity != null) { ... } ActivityRecord prev = mResumedActivity; if (prev == null) { ... } ... mResumedActivity = null; mPausingActivity = prev; mLastPausedActivity = prev; mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0 || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null; prev.state = ActivityState.PAUSING; ... if (prev.app != null && prev.app.thread != null) { try { ... prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing, userLeaving, prev.configChangeFlags, dontWait); } catch (Exception e) { ... } } else { ... } ... } ... }

這裡的 prev.app.thread 是一個 ApplicationThread 對象的遠程接口,通過調用這個遠程接口的 schedulePauseActivity,來通知 Launcher 進入 Paused 狀態。至此,AMS 對 Launcher 的請求已經響應完畢,我們發現又通過 Binder 通信回調至 Launcher 進程。

3.3 Launcher 進程掛起 Launcher,再次通知 AMS

這段流程相對簡單,我們來看 ActivityThread:

 public final class ActivityThread { ... private void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving, int configChanges, boolean dontReport) { ActivityClientRecord r = mActivities.get(token); if (r != null) { ... performPauseActivity(token, finished, r.isPreHoneycomb()); // Make sure any pending writes are now committed. if (r.isPreHoneycomb()) { QueuedWork.waitToFinish(); } // Tell the activity manager we have paused. if (!dontReport) { try { ActivityManagerNative.getDefault().activityPaused(token); } catch (RemoteException ex) { } } ... } } ... }

這部分由 Launcher 的 ActivityThread 處理頁面 Paused,並再次通過 ActivityManagerProxy 通知 AMS。

3.4 AMS 創建新的進程

創建新進程時,AMS 會保存一份 ProcessRecord 信息。如果應用的 AndroidManifest.xml 中沒有為 Application 標簽指定 process 屬性,系統便默認使用 package 名稱。每個應用程序都有自己的 uid,因此這裡 uid + process 的組合,就能為每個應用程序創建一個 ProcessRecord。

 public final class ActivityManagerService extends ActivityManagerNative implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback { ... private final void startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) { ... try { ... // Start the process. It will either succeed and return a result containing // the PID of the new process, or else throw a RuntimeException. boolean isActivityProcess = (entryPoint == null); if (entryPoint == null) entryPoint = "android.app.ActivityThread"; 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); ... } catch () { ... } } ... }

這裡主要是調用 Process:start 接口來創建一個新進程。新進程會導入 android.app.ActivityThread 類並執行它的 main 函數,這正是每個應用程序都有一個 ActivityThread 實例相互對應的原因。

3.5 應用進程初始化

我們來看 Activity 的 main 函數,它在這裡綁定了主線程的 Looper 並進入消息循環。大家應該知道,整個 Android 系統是消息驅動的,這也正是主線程默認綁定 Looper 的原因:

 public final class ActivityThread { ... public static void main(String[] args) { ... Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false); ... Looper.loop(); ... } private void attach(boolean system) { ... if (!system) { ... final IActivityManager mgr = ActivityManagerNative.getDefault(); try { mgr.attachApplication(mAppThread); } catch (RemoteException ex) { // Ignore } } else { ... } ... } ... }

attach 函數最終調用了 ActivityManagerService 遠程接口 ActivityManagerProxy 的 attachApplication 函數,傳入的參數 mAppThread 是一個 ApplicationThread 類型的 Binder 對象,作用是在 AMS 與應用進程之間進行跨進程通信。

3.6 在 AMS 中注冊應用進程,啟動棧頂頁面

前面提到,AMS 負責系統四大組件的啟動、切換、調度以及應用進程的管理與調度。通過上一段流程可知,應用進程創建後會通過 Binder 驅動與 AMS 交互,此時 AMS 便對應用進程創建後的信息進行了一次注冊。如果拿 Windows 系統中程序注冊到注冊表來類比,這個過程或許會更形象一些。

mMainStack.topRunningActivityLocked(null) 從堆棧頂端取出要啟動的 Activity,並在 realStartActivityLocked 函數中通過 ApplicationThreadProxy 調回 App 進程去啟動頁面。

 public final class ActivityStackSupervisor implements DisplayListener { ... final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, boolean andResume, boolean checkConfig) throws RemoteException { ... r.app = app; ... try { ... app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken, System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration), r.compat, r.launchedFromPackage, r.task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results, newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo); ... } catch (RemoteException e) { ... } ... } ... }

此時在 App 進程中,經過一系列調用鏈,最終調用至 MainActivity:onCreate 函數,隨後調用 onResume,再通知 AMS 該 MainActivity 已進入 resume 狀態。至此,整個啟動流程告一段落。

四、總結

通過上述流程,相信大家可以建立起一個基本的認知。這裡我們忽略細節、簡化流程,單純從進程角度來看下圖:

圖中所畫之處不再贅述。Activity 啟動後進入 Resume 狀態,此時即可交互。以上就是關於 Android 應用啟動流程分析的全部內容,如有疑問,歡迎指正交流。

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