2018-09-06

本文重點(diǎn)介紹應(yīng)用程序的啟動(dòng)過程系奉,應(yīng)用程序的啟動(dòng)過程實(shí)際上就是應(yīng)用程序中的默認(rèn)Activity的啟動(dòng)過程,本文將詳細(xì)分析應(yīng)用程序框架層的源代碼攘蔽,了解Android應(yīng)用程序的啟動(dòng)過程句狼。

    下面詳細(xì)分析每一步是如何實(shí)現(xiàn)的。

    Step 1\. Launcher.startActivitySafely

    在Android系統(tǒng)中十偶,應(yīng)用程序是由Launcher啟動(dòng)起來的肛冶,其實(shí),Launcher本身也是一個(gè)應(yīng)用程序扯键,其它的應(yīng)用程序安裝后,就會(huì)Launcher的界面上出現(xiàn)一個(gè)相應(yīng)的圖標(biāo)珊肃,點(diǎn)擊這個(gè)圖標(biāo)時(shí)荣刑,Launcher就會(huì)對應(yīng)的應(yīng)用程序啟動(dòng)起來。

    Launcher的源代碼工程在packages/apps/Launcher2目錄下伦乔,負(fù)責(zé)啟動(dòng)其它應(yīng)用程序的源代碼實(shí)現(xiàn)在src/com/android/launcher2/Launcher.java文件中:
  1. /**

    • Default launcher application.
  2. */

  3. public final class Launcher extends Activity

  4. implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks, AllAppsView.Watcher {

  5. ......

  6. /**

    • Launches the intent referred by the clicked shortcut.
    • @param v The view representing the clicked shortcut.
  7. */

  8. public void onClick(View v) {

  9. Object tag = v.getTag();

  10. if (tag instanceof ShortcutInfo) {

  11. // Open shortcut

  12. final Intent intent = ((ShortcutInfo) tag).intent;

  13. int[] pos = new int[2];

  14. v.getLocationOnScreen(pos);

  15. intent.setSourceBounds(new Rect(pos[0], pos[1],

  16. pos[0] + v.getWidth(), pos[1] + v.getHeight()));

  17. startActivitySafely(intent, tag);

  18. } else if (tag instanceof FolderInfo) {

  19. ......

  20. } else if (v == mHandleView) {

  21. ......

  22. }

  23. }

  24. void startActivitySafely(Intent intent, Object tag) {

  25. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

  26. try {

  27. startActivity(intent);

  28. } catch (ActivityNotFoundException e) {

  29. ......

  30. } catch (SecurityException e) {

  31. ......

  32. }

  33. }

  34. ......

  35. }

    回憶一下前面一篇文章Android應(yīng)用程序的Activity啟動(dòng)過程簡要介紹和學(xué)習(xí)計(jì)劃說到的應(yīng)用程序Activity厉亏,它的默認(rèn)Activity是MainActivity,這里是AndroidManifest.xml文件中配置的:

  36. <activity android:name=".MainActivity"

  37. android:label="@string/app_name">

  38. <intent-filter>

  39. <action android:name="android.intent.action.MAIN" />

  40. <category android:name="android.intent.category.LAUNCHER" />

  41. </intent-filter>

  42. </activity>

    因此烈和,這里的intent包含的信息為:action = "android.intent.action.Main"爱只,category="android.intent.category.LAUNCHER", cmp="shy.luo.activity/.MainActivity",表示它要啟動(dòng)的Activity為shy.luo.activity.MainActivity招刹。Intent.FLAG_ACTIVITY_NEW_TASK表示要在一個(gè)新的Task中啟動(dòng)這個(gè)Activity恬试,注意,Task是Android系統(tǒng)中的概念疯暑,它不同于進(jìn)程Process的概念训柴。簡單地說,一個(gè)Task是一系列Activity的集合妇拯,這個(gè)集合是以堆棧的形式來組織的幻馁,遵循后進(jìn)先出的原則。事實(shí)上越锈,Task是一個(gè)非常復(fù)雜的概念仗嗦,有興趣的讀者可以到官網(wǎng)[http://developer.android.com/guide/topics/manifest/activity-element.html](http://developer.android.com/guide/topics/manifest/activity-element.html)查看相關(guān)的資料。這里甘凭,我們只要知道稀拐,這個(gè)MainActivity要在一個(gè)新的Task中啟動(dòng)就可以了。
    
    Step 2\. Activity.startActivity
    
    在Step 1中对蒲,我們看到钩蚊,Launcher繼承于Activity類贡翘,而Activity類實(shí)現(xiàn)了startActivity函數(shù),因此砰逻,這里就調(diào)用了Activity.startActivity函數(shù)鸣驱,它實(shí)現(xiàn)在frameworks/base/core/java/android/app/Activity.java文件中:
    
  43. public class Activity extends ContextThemeWrapper

  44. implements LayoutInflater.Factory,

  45. Window.Callback, KeyEvent.Callback,

  46. OnCreateContextMenuListener, ComponentCallbacks {

  47. ......

  48. @Override

  49. public void startActivity(Intent intent) {

  50. startActivityForResult(intent, -1);

  51. }

  52. ......

  53. }

    這個(gè)函數(shù)實(shí)現(xiàn)很簡單,它調(diào)用startActivityForResult來進(jìn)一步處理蝠咆,第二個(gè)參數(shù)傳入-1表示不需要這個(gè)Actvity結(jié)束后的返回結(jié)果踊东。

    Step 3. Activity.startActivityForResult

    這個(gè)函數(shù)也是實(shí)現(xiàn)在frameworks/base/core/java/android/app/Activity.java文件中:

  54. public class Activity extends ContextThemeWrapper

  55. implements LayoutInflater.Factory,

  56. Window.Callback, KeyEvent.Callback,

  57. OnCreateContextMenuListener, ComponentCallbacks {

  58. ......

  59. public void startActivityForResult(Intent intent, int requestCode) {

  60. if (mParent == null) {

  61. Instrumentation.ActivityResult ar =

  62. mInstrumentation.execStartActivity(

  63. this, mMainThread.getApplicationThread(), mToken, this,

  64. intent, requestCode);

  65. ......

  66. } else {

  67. ......

  68. }

  69. ......

  70. }

    這里的mInstrumentation是Activity類的成員變量,它的類型是Intrumentation刚操,定義在frameworks/base/core/java/android/app/Instrumentation.java文件中闸翅,它用來監(jiān)控應(yīng)用程序和系統(tǒng)的交互。
    
    這里的mMainThread也是Activity類的成員變量菊霜,它的類型是ActivityThread坚冀,它代表的是應(yīng)用程序的主線程,我們在[Android系統(tǒng)在新進(jìn)程中啟動(dòng)自定義服務(wù)過程(startService)的原理分析](http://blog.csdn.net/luoshengyang/article/details/6677029)一文中已經(jīng)介紹過了鉴逞。這里通過mMainThread.getApplicationThread獲得它里面的ApplicationThread成員變量记某,它是一個(gè)Binder對象,后面我們會(huì)看到构捡,ActivityManagerService會(huì)使用它來和ActivityThread來進(jìn)行進(jìn)程間通信液南。這里我們需注意的是,這里的mMainThread代表的是Launcher應(yīng)用程序運(yùn)行的進(jìn)程勾徽。
    
    這里的mToken也是Activity類的成員變量滑凉,它是一個(gè)Binder對象的遠(yuǎn)程接口。
    
    Step 4\. Instrumentation.execStartActivity
    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/Instrumentation.java文件中:
    
  71. public class Instrumentation {

  72. ......

  73. public ActivityResult execStartActivity(

  74. Context who, IBinder contextThread, IBinder token, Activity target,

  75. Intent intent, int requestCode) {

  76. IApplicationThread whoThread = (IApplicationThread) contextThread;

  77. if (mActivityMonitors != null) {

  78. ......

  79. }

  80. try {

  81. int result = ActivityManagerNative.getDefault()

  82. .startActivity(whoThread, intent,

  83. intent.resolveTypeIfNeeded(who.getContentResolver()),

  84. null, 0, token, target != null ? target.mEmbeddedID : null,

  85. requestCode, false, false);

  86. ......

  87. } catch (RemoteException e) {

  88. }

  89. return null;

  90. }

  91. ......

  92. }

    這里的ActivityManagerNative.getDefault返回ActivityManagerService的遠(yuǎn)程接口喘帚,即ActivityManagerProxy接口畅姊,具體可以參考[Android系統(tǒng)在新進(jìn)程中啟動(dòng)自定義服務(wù)過程(startService)的原理分析](http://blog.csdn.net/luoshengyang/article/details/6677029)一文。
    
    這里的intent.resolveTypeIfNeeded返回這個(gè)intent的MIME類型啥辨,在這個(gè)例子中涡匀,沒有AndroidManifest.xml設(shè)置MainActivity的MIME類型,因此溉知,這里返回null陨瘩。
    
    這里的target不為null,但是target.mEmbddedID為null级乍,我們不用關(guān)注舌劳。
    
    Step 5\. ActivityManagerProxy.startActivity
    
    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ActivityManagerNative.java文件中:
    
  93. class ActivityManagerProxy implements IActivityManager

  94. {

  95. ......

  96. public int startActivity(IApplicationThread caller, Intent intent,

  97. String resolvedType, Uri[] grantedUriPermissions, int grantedMode,

  98. IBinder resultTo, String resultWho,

  99. int requestCode, boolean onlyIfNeeded,

  100. boolean debug) throws RemoteException {

  101. Parcel data = Parcel.obtain();

  102. Parcel reply = Parcel.obtain();

  103. data.writeInterfaceToken(IActivityManager.descriptor);

  104. data.writeStrongBinder(caller != null ? caller.asBinder() : null);

  105. intent.writeToParcel(data, 0);

  106. data.writeString(resolvedType);

  107. data.writeTypedArray(grantedUriPermissions, 0);

  108. data.writeInt(grantedMode);

  109. data.writeStrongBinder(resultTo);

  110. data.writeString(resultWho);

  111. data.writeInt(requestCode);

  112. data.writeInt(onlyIfNeeded ? 1 : 0);

  113. data.writeInt(debug ? 1 : 0);

  114. mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);

  115. reply.readException();

  116. int result = reply.readInt();

  117. reply.recycle();

  118. data.recycle();

  119. return result;

  120. }

  121. ......

  122. }

    這里的參數(shù)比較多,我們先整理一下玫荣。從上面的調(diào)用可以知道甚淡,這里的參數(shù)resolvedType、grantedUriPermissions和resultWho均為null捅厂;參數(shù)caller為ApplicationThread類型的Binder實(shí)體贯卦;參數(shù)resultTo為一個(gè)Binder實(shí)體的遠(yuǎn)程接口资柔,我們先不關(guān)注它;參數(shù)grantedMode為0撵割,我們也先不關(guān)注它贿堰;參數(shù)requestCode為-1;參數(shù)onlyIfNeeded和debug均空false啡彬。

    Step 6. ActivityManagerService.startActivity

    上一步Step 5通過Binder驅(qū)動(dòng)程序就進(jìn)入到ActivityManagerService的startActivity函數(shù)來了羹与,它定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:

  123. public final class ActivityManagerService extends ActivityManagerNative

  124. implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

  125. ......

  126. public final int startActivity(IApplicationThread caller,

  127. Intent intent, String resolvedType, Uri[] grantedUriPermissions,

  128. int grantedMode, IBinder resultTo,

  129. String resultWho, int requestCode, boolean onlyIfNeeded,

  130. boolean debug) {

  131. return mMainStack.startActivityMayWait(caller, intent, resolvedType,

  132. grantedUriPermissions, grantedMode, resultTo, resultWho,

  133. requestCode, onlyIfNeeded, debug, null, null);

  134. }

  135. ......

  136. }

    這里只是簡單地將操作轉(zhuǎn)發(fā)給成員變量mMainStack的startActivityMayWait函數(shù),這里的mMainStack的類型為ActivityStack庶灿。

    Step 7. ActivityStack.startActivityMayWait

    這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:

  137. public class ActivityStack {

  138. ......

  139. final int startActivityMayWait(IApplicationThread caller,

  140. Intent intent, String resolvedType, Uri[] grantedUriPermissions,

  141. int grantedMode, IBinder resultTo,

  142. String resultWho, int requestCode, boolean onlyIfNeeded,

  143. boolean debug, WaitResult outResult, Configuration config) {

  144. ......

  145. boolean componentSpecified = intent.getComponent() != null;

  146. // Don't modify the client's object!

  147. intent = new Intent(intent);

  148. // Collect information about the target of the Intent.

  149. ActivityInfo aInfo;

  150. try {

  151. ResolveInfo rInfo =

  152. AppGlobals.getPackageManager().resolveIntent(

  153. intent, resolvedType,

  154. PackageManager.MATCH_DEFAULT_ONLY

  155. | ActivityManagerService.STOCK_PM_FLAGS);

  156. aInfo = rInfo != null ? rInfo.activityInfo : null;

  157. } catch (RemoteException e) {

  158. ......

  159. }

  160. if (aInfo != null) {

  161. // Store the found target back into the intent, because now that

  162. // we have it we never want to do this again. For example, if the

  163. // user navigates back to this point in the history, we should

  164. // always restart the exact same activity.

  165. intent.setComponent(new ComponentName(

  166. aInfo.applicationInfo.packageName, aInfo.name));

  167. ......

  168. }

  169. synchronized (mService) {

  170. int callingPid;

  171. int callingUid;

  172. if (caller == null) {

  173. ......

  174. } else {

  175. callingPid = callingUid = -1;

  176. }

  177. mConfigWillChange = config != null

  178. && mService.mConfiguration.diff(config) != 0;

  179. ......

  180. if (mMainStack && aInfo != null &&

  181. (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {

  182. ......

  183. }

  184. int res = startActivityLocked(caller, intent, resolvedType,

  185. grantedUriPermissions, grantedMode, aInfo,

  186. resultTo, resultWho, requestCode, callingPid, callingUid,

  187. onlyIfNeeded, componentSpecified);

  188. if (mConfigWillChange && mMainStack) {

  189. ......

  190. }

  191. ......

  192. if (outResult != null) {

  193. ......

  194. }

  195. return res;

  196. }

  197. }

  198. ......

  199. }

    注意纵搁,從Step 6傳下來的參數(shù)outResult和config均為null,此外往踢,表達(dá)式(aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0為false腾誉,因此,這里忽略了無關(guān)代碼峻呕。

    下面語句對參數(shù)intent的內(nèi)容進(jìn)行解析妄辩,得到MainActivity的相關(guān)信息,保存在aInfo變量中:

  200. ActivityInfo aInfo;

  201. try {

  202. ResolveInfo rInfo =

  203. AppGlobals.getPackageManager().resolveIntent(

  204. intent, resolvedType,

  205. PackageManager.MATCH_DEFAULT_ONLY

  206. | ActivityManagerService.STOCK_PM_FLAGS);

  207. aInfo = rInfo != null ? rInfo.activityInfo : null;

  208. } catch (RemoteException e) {

  209. ......

  210. }

解析之后山上,得到的aInfo.applicationInfo.packageName的值為"shy.luo.activity",aInfo.name的值為"shy.luo.activity.MainActivity"英支,這是在這個(gè)實(shí)例的配置文件AndroidManifest.xml里面配置的佩憾。

此外,函數(shù)開始的地方調(diào)用intent.getComponent()函數(shù)的返回值不為null干花,因此妄帘,這里的componentSpecified變量為true。

接下去就調(diào)用startActivityLocked進(jìn)一步處理了池凄。

Step 8\. ActivityStack.startActivityLocked

這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:

  1. public class ActivityStack {

  2. ......

  3. final int startActivityLocked(IApplicationThread caller,

  4. Intent intent, String resolvedType,

  5. Uri[] grantedUriPermissions,

  6. int grantedMode, ActivityInfo aInfo, IBinder resultTo,

  7. String resultWho, int requestCode,

  8. int callingPid, int callingUid, boolean onlyIfNeeded,

  9. boolean componentSpecified) {

  10. int err = START_SUCCESS;

  11. ProcessRecord callerApp = null;

  12. if (caller != null) {

  13. callerApp = mService.getRecordForAppLocked(caller);

  14. if (callerApp != null) {

  15. callingPid = callerApp.pid;

  16. callingUid = callerApp.info.uid;

  17. } else {

  18. ......

  19. }

  20. }

  21. ......

  22. ActivityRecord sourceRecord = null;

  23. ActivityRecord resultRecord = null;

  24. if (resultTo != null) {

  25. int index = indexOfTokenLocked(resultTo);

  26. ......

  27. if (index >= 0) {

  28. sourceRecord = (ActivityRecord)mHistory.get(index);

  29. if (requestCode >= 0 && !sourceRecord.finishing) {

  30. ......

  31. }

  32. }

  33. }

  34. int launchFlags = intent.getFlags();

  35. if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0

  36. && sourceRecord != null) {

  37. ......

  38. }

  39. if (err == START_SUCCESS && intent.getComponent() == null) {

  40. ......

  41. }

  42. if (err == START_SUCCESS && aInfo == null) {

  43. ......

  44. }

  45. if (err != START_SUCCESS) {

  46. ......

  47. }

  48. ......

  49. ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,

  50. intent, resolvedType, aInfo, mService.mConfiguration,

  51. resultRecord, resultWho, requestCode, componentSpecified);

  52. ......

  53. return startActivityUncheckedLocked(r, sourceRecord,

  54. grantedUriPermissions, grantedMode, onlyIfNeeded, true);

  55. }

  56. ......

  57. }

    從傳進(jìn)來的參數(shù)caller得到調(diào)用者的進(jìn)程信息抡驼,并保存在callerApp變量中,這里就是Launcher應(yīng)用程序的進(jìn)程信息了肿仑。

    前面說過致盟,參數(shù)resultTo是Launcher這個(gè)Activity里面的一個(gè)Binder對象,通過它可以獲得Launcher這個(gè)Activity的相關(guān)信息尤慰,保存在sourceRecord變量中馏锡。
    再接下來,創(chuàng)建即將要啟動(dòng)的Activity的相關(guān)信息伟端,并保存在r變量中:

  58. ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,

  59. intent, resolvedType, aInfo, mService.mConfiguration,

  60. resultRecord, resultWho, requestCode, componentSpecified);

接著調(diào)用startActivityUncheckedLocked函數(shù)進(jìn)行下一步操作杯道。

Step 9\. ActivityStack.startActivityUncheckedLocked

這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:

  1. public class ActivityStack {

  2. ......

  3. final int startActivityUncheckedLocked(ActivityRecord r,

  4. ActivityRecord sourceRecord, Uri[] grantedUriPermissions,

  5. int grantedMode, boolean onlyIfNeeded, boolean doResume) {

  6. final Intent intent = r.intent;

  7. final int callingUid = r.launchedFromUid;

  8. int launchFlags = intent.getFlags();

  9. // We'll invoke onUserLeaving before onPause only if the launching

  10. // activity did not explicitly state that this is an automated launch.

  11. mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;

  12. ......

  13. ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)

  14. != 0 ? r : null;

  15. // If the onlyIfNeeded flag is set, then we can do this if the activity

  16. // being launched is the same as the one making the call... or, as

  17. // a special case, if we do not know the caller then we count the

  18. // current top activity as the caller.

  19. if (onlyIfNeeded) {

  20. ......

  21. }

  22. if (sourceRecord == null) {

  23. ......

  24. } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {

  25. ......

  26. } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE

  27. || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {

  28. ......

  29. }

  30. if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {

  31. ......

  32. }

  33. boolean addingToTask = false;

  34. if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&

  35. (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)

  36. || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK

  37. || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {

  38. // If bring to front is requested, and no result is requested, and

  39. // we can find a task that was started with this same

  40. // component, then instead of launching bring that one to the front.

  41. if (r.resultTo == null) {

  42. // See if there is a task to bring to the front. If this is

  43. // a SINGLE_INSTANCE activity, there can be one and only one

  44. // instance of it in the history, and it is always in its own

  45. // unique task, so we do a special search.

  46. ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE

  47. ? findTaskLocked(intent, r.info)

  48. : findActivityLocked(intent, r.info);

  49. if (taskTop != null) {

  50. ......

  51. }

  52. }

  53. }

  54. ......

  55. if (r.packageName != null) {

  56. // If the activity being launched is the same as the one currently

  57. // at the top, then we need to check if it should only be launched

  58. // once.

  59. ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);

  60. if (top != null && r.resultTo == null) {

  61. if (top.realActivity.equals(r.realActivity)) {

  62. ......

  63. }

  64. }

  65. } else {

  66. ......

  67. }

  68. boolean newTask = false;

  69. // Should this be considered a new task?

  70. if (r.resultTo == null && !addingToTask

  71. && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {

  72. // todo: should do better management of integers.

  73. mService.mCurTask++;

  74. if (mService.mCurTask <= 0) {

  75. mService.mCurTask = 1;

  76. }

  77. r.task = new TaskRecord(mService.mCurTask, r.info, intent,

  78. (r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);

  79. ......

  80. newTask = true;

  81. if (mMainStack) {

  82. mService.addRecentTaskLocked(r.task);

  83. }

  84. } else if (sourceRecord != null) {

  85. ......

  86. } else {

  87. ......

  88. }

  89. ......

  90. startActivityLocked(r, newTask, doResume);

  91. return START_SUCCESS;

  92. }

  93. ......

  94. }

    函數(shù)首先獲得intent的標(biāo)志值,保存在launchFlags變量中责蝠。

    這個(gè)intent的標(biāo)志值的位Intent.FLAG_ACTIVITY_NO_USER_ACTION沒有置位党巾,因此 萎庭,成員變量mUserLeaving的值為true。

    這個(gè)intent的標(biāo)志值的位Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP也沒有置位齿拂,因此驳规,變量notTop的值為null。

    由于在這個(gè)例子的AndroidManifest.xml文件中创肥,MainActivity沒有配置launchMode屬值达舒,因此,這里的r.launchMode為默認(rèn)值0叹侄,表示以標(biāo)準(zhǔn)(Standard巩搏,或者稱為ActivityInfo.LAUNCH_MULTIPLE)的方式來啟動(dòng)這個(gè)Activity。Activity的啟動(dòng)方式有四種趾代,其余三種分別是ActivityInfo.LAUNCH_SINGLE_INSTANCE贯底、ActivityInfo.LAUNCH_SINGLE_TASK和ActivityInfo.LAUNCH_SINGLE_TOP,具體可以參考官方網(wǎng)站http://developer.android.com/reference/android/content/pm/ActivityInfo.html撒强。

    傳進(jìn)來的參數(shù)r.resultTo為null禽捆,表示Launcher不需要等這個(gè)即將要啟動(dòng)的MainActivity的執(zhí)行結(jié)果。

    由于這個(gè)intent的標(biāo)志值的位Intent.FLAG_ACTIVITY_NEW_TASK被置位飘哨,而且Intent.FLAG_ACTIVITY_MULTIPLE_TASK沒有置位胚想,因此,下面的if語句會(huì)被執(zhí)行:

  95. if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&

  96. (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)

  97. || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK

  98. || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {

  99. // If bring to front is requested, and no result is requested, and

  100. // we can find a task that was started with this same

  101. // component, then instead of launching bring that one to the front.

  102. if (r.resultTo == null) {

  103. // See if there is a task to bring to the front. If this is

  104. // a SINGLE_INSTANCE activity, there can be one and only one

  105. // instance of it in the history, and it is always in its own

  106. // unique task, so we do a special search.

  107. ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE

  108. ? findTaskLocked(intent, [r.info](http://r.info))

  109. : findActivityLocked(intent, [r.info](http://r.info));

  110. if (taskTop != null) {

  111. ......

  112. }

  113. }

  114. }

這段代碼的邏輯是查看一下芽隆,當(dāng)前有沒有Task可以用來執(zhí)行這個(gè)Activity浊服。由于r.launchMode的值不為ActivityInfo.LAUNCH_SINGLE_INSTANCE,因此胚吁,它通過findTaskLocked函數(shù)來查找存不存這樣的Task牙躺,這里返回的結(jié)果是null近速,即taskTop為null定鸟,因此,需要?jiǎng)?chuàng)建一個(gè)新的Task來啟動(dòng)這個(gè)Activity斩个。

接著往下看:

  1. if (r.packageName != null) {

  2. // If the activity being launched is the same as the one currently

  3. // at the top, then we need to check if it should only be launched

  4. // once.

  5. ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);

  6. if (top != null && r.resultTo == null) {

  7. if (top.realActivity.equals(r.realActivity)) {

  8. ......

  9. }

  10. }

  11. }

這段代碼的邏輯是看一下半抱,當(dāng)前在堆棧頂端的Activity是否就是即將要啟動(dòng)的Activity脓恕,有些情況下,如果即將要啟動(dòng)的Activity就在堆棧的頂端窿侈,那么进肯,就不會(huì)重新啟動(dòng)這個(gè)Activity的別一個(gè)實(shí)例了,具體可以參考官方網(wǎng)站[http://developer.android.com/reference/android/content/pm/ActivityInfo.html](http://developer.android.com/reference/android/content/pm/ActivityInfo.html)∶弈ィ現(xiàn)在處理堆棧頂端的Activity是Launcher江掩,與我們即將要啟動(dòng)的MainActivity不是同一個(gè)Activity,因此,這里不用進(jìn)一步處理上述介紹的情況环形。

執(zhí)行到這里策泣,我們知道,要在一個(gè)新的Task里面來啟動(dòng)這個(gè)Activity了抬吟,于是新創(chuàng)建一個(gè)Task:

  1. if (r.resultTo == null && !addingToTask

  2. && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {

  3. // todo: should do better management of integers.

  4. mService.mCurTask++;

  5. if (mService.mCurTask <= 0) {

  6. mService.mCurTask = 1;

  7. }

  8. r.task = new TaskRecord(mService.mCurTask, [r.info](http://r.info), intent,

  9. (r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);

  10. ......

  11. newTask = true;

  12. if (mMainStack) {

  13. mService.addRecentTaskLocked(r.task);

  14. }

  15. }

新建的Task保存在r.task域中萨咕,同時(shí),添加到mService中去火本,這里的mService就是ActivityManagerService了危队。

最后就進(jìn)入startActivityLocked(r, newTask, doResume)進(jìn)一步處理了。這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:

  1. public class ActivityStack {

  2. ......

  3. private final void startActivityLocked(ActivityRecord r, boolean newTask,

  4. boolean doResume) {

  5. final int NH = mHistory.size();

  6. int addPos = -1;

  7. if (!newTask) {

  8. ......

  9. }

  10. // Place a new activity at top of stack, so it is next to interact

  11. // with the user.

  12. if (addPos < 0) {

  13. addPos = NH;

  14. }

  15. // If we are not placing the new activity frontmost, we do not want

  16. // to deliver the onUserLeaving callback to the actual frontmost

  17. // activity

  18. if (addPos < NH) {

  19. ......

  20. }

  21. // Slot the activity into the history stack and proceed

  22. mHistory.add(addPos, r);

  23. r.inHistory = true;

  24. r.frontOfTask = newTask;

  25. r.task.numActivities++;

  26. if (NH > 0) {

  27. // We want to show the starting preview window if we are

  28. // switching to a new task, or the next activity's process is

  29. // not currently running.

  30. ......

  31. } else {

  32. // If this is the first activity, don't do any fancy animations,

  33. // because there is nothing for it to animate on top of.

  34. ......

  35. }

  36. ......

  37. if (doResume) {

  38. resumeTopActivityLocked(null);

  39. }

  40. }

  41. ......

  42. }

    這里的NH表示當(dāng)前系統(tǒng)中歷史任務(wù)的個(gè)數(shù)钙畔,這里肯定是大于0茫陆,因?yàn)長auncher已經(jīng)跑起來了。當(dāng)NH>0時(shí)擎析,并且現(xiàn)在要切換新任務(wù)時(shí)簿盅,要做一些任務(wù)切的界面操作,這段代碼我們就不看了揍魂,這里不會(huì)影響到下面啟Activity的過程桨醋,有興趣的讀取可以自己研究一下。

    這里傳進(jìn)來的參數(shù)doResume為true现斋,于是調(diào)用resumeTopActivityLocked進(jìn)一步操作喜最。

    Step 10. Activity.resumeTopActivityLocked

    這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:

  43. public class ActivityStack {

  44. ......

  45. /**

    • Ensure that the top activity in the stack is resumed.
    • @param prev The previously resumed activity, for when in the process
    • of pausing; can be null to call from elsewhere.
    • @return Returns true if something is being resumed, or false if
    • nothing happened.
  46. */

  47. final boolean resumeTopActivityLocked(ActivityRecord prev) {

  48. // Find the first activity that is not finishing.

  49. ActivityRecord next = topRunningActivityLocked(null);

  50. // Remember how we'll process this pause/resume situation, and ensure

  51. // that the state is reset however we wind up proceeding.

  52. final boolean userLeaving = mUserLeaving;

  53. mUserLeaving = false;

  54. if (next == null) {

  55. ......

  56. }

  57. next.delayedResume = false;

  58. // If the top activity is the resumed one, nothing to do.

  59. if (mResumedActivity == next && next.state == ActivityState.RESUMED) {

  60. ......

  61. }

  62. // If we are sleeping, and there is no resumed activity, and the top

  63. // activity is paused, well that is the state we want.

  64. if ((mService.mSleeping || mService.mShuttingDown)

  65. && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {

  66. ......

  67. }

  68. ......

  69. // If we are currently pausing an activity, then don't do anything

  70. // until that is done.

  71. if (mPausingActivity != null) {

  72. ......

  73. }

  74. ......

  75. // We need to start pausing the current activity so the top one

  76. // can be resumed...

  77. if (mResumedActivity != null) {

  78. ......

  79. startPausingLocked(userLeaving, false);

  80. return true;

  81. }

  82. ......

  83. }

  84. ......

  85. }

    函數(shù)先通過調(diào)用topRunningActivityLocked函數(shù)獲得堆棧頂端的Activity,這里就是MainActivity了庄蹋,這是在上面的Step 9設(shè)置好的返顺,保存在next變量中。

    接下來把mUserLeaving的保存在本地變量userLeaving中蔓肯,然后重新設(shè)置為false,在上面的Step 9中振乏,mUserLeaving的值為true蔗包,因此,這里的userLeaving為true慧邮。

    這里的mResumedActivity為Launcher调限,因?yàn)長auncher是當(dāng)前正被執(zhí)行的Activity。

    當(dāng)我們處理休眠狀態(tài)時(shí)误澳,mLastPausedActivity保存堆棧頂端的Activity耻矮,因?yàn)楫?dāng)前不是休眠狀態(tài),所以mLastPausedActivity為null忆谓。

    有了這些信息之后裆装,下面的語句就容易理解了:

  86. // If the top activity is the resumed one, nothing to do.

  87. if (mResumedActivity == next && next.state == ActivityState.RESUMED) {

  88. ......

  89. }

  90. // If we are sleeping, and there is no resumed activity, and the top

  91. // activity is paused, well that is the state we want.

  92. if ((mService.mSleeping || mService.mShuttingDown)

  93. && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {

  94. ......

  95. }

它首先看要啟動(dòng)的Activity是否就是當(dāng)前處理Resumed狀態(tài)的Activity,如果是的話,那就什么都不用做哨免,直接返回就可以了茎活;否則再看一下系統(tǒng)當(dāng)前是否休眠狀態(tài),如果是的話琢唾,再看看要啟動(dòng)的Activity是否就是當(dāng)前處于堆棧頂端的Activity载荔,如果是的話,也是什么都不用做采桃。

上面兩個(gè)條件都不滿足懒熙,因此,在繼續(xù)往下執(zhí)行之前普办,首先要把當(dāng)處于Resumed狀態(tài)的Activity推入Paused狀態(tài)工扎,然后才可以啟動(dòng)新的Activity。但是在將當(dāng)前這個(gè)Resumed狀態(tài)的Activity推入Paused狀態(tài)之前泌豆,首先要看一下當(dāng)前是否有Activity正在進(jìn)入Pausing狀態(tài)定庵,如果有的話,當(dāng)前這個(gè)Resumed狀態(tài)的Activity就要稍后才能進(jìn)入Paused狀態(tài)了踪危,這樣就保證了所有需要進(jìn)入Paused狀態(tài)的Activity串行處理蔬浙。

這里沒有處于Pausing狀態(tài)的Activity,即mPausingActivity為null贞远,而且mResumedActivity也不為null畴博,于是就調(diào)用startPausingLocked函數(shù)把Launcher推入Paused狀態(tài)去了。

Step 11\. ActivityStack.startPausingLocked

這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:

  1. public class ActivityStack {

  2. ......

  3. private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {

  4. if (mPausingActivity != null) {

  5. ......

  6. }

  7. ActivityRecord prev = mResumedActivity;

  8. if (prev == null) {

  9. ......

  10. }

  11. ......

  12. mResumedActivity = null;

  13. mPausingActivity = prev;

  14. mLastPausedActivity = prev;

  15. prev.state = ActivityState.PAUSING;

  16. ......

  17. if (prev.app != null && prev.app.thread != null) {

  18. ......

  19. try {

  20. ......

  21. prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,

  22. prev.configChangeFlags);

  23. ......

  24. } catch (Exception e) {

  25. ......

  26. }

  27. } else {

  28. ......

  29. }

  30. ......

  31. }

  32. ......

  33. }

    函數(shù)首先把mResumedActivity保存在本地變量prev中蓝仲。在上一步Step 10中俱病,說到mResumedActivity就是Launcher,因此袱结,這里把Launcher進(jìn)程中的ApplicationThread對象取出來亮隙,通過它來通知Launcher這個(gè)Activity它要進(jìn)入Paused狀態(tài)了。當(dāng)然垢夹,這里的prev.app.thread是一個(gè)ApplicationThread對象的遠(yuǎn)程接口溢吻,通過調(diào)用這個(gè)遠(yuǎn)程接口的schedulePauseActivity來通知Launcher進(jìn)入Paused狀態(tài)。

    參數(shù)prev.finishing表示prev所代表的Activity是否正在等待結(jié)束的Activity列表中果元,由于Laucher這個(gè)Activity還沒結(jié)束促王,所以這里為false;參數(shù)prev.configChangeFlags表示哪些config發(fā)生了變化而晒,這里我們不關(guān)心它的值蝇狼。

    Step 12. ApplicationThreadProxy.schedulePauseActivity

    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ApplicationThreadNative.java文件中:

  34. class ApplicationThreadProxy implements IApplicationThread {

  35. ......

  36. public final void schedulePauseActivity(IBinder token, boolean finished,

  37. boolean userLeaving, int configChanges) throws RemoteException {

  38. Parcel data = Parcel.obtain();

  39. data.writeInterfaceToken(IApplicationThread.descriptor);

  40. data.writeStrongBinder(token);

  41. data.writeInt(finished ? 1 : 0);

  42. data.writeInt(userLeaving ? 1 :0);

  43. data.writeInt(configChanges);

  44. mRemote.transact(SCHEDULE_PAUSE_ACTIVITY_TRANSACTION, data, null,

  45. IBinder.FLAG_ONEWAY);

  46. data.recycle();

  47. }

  48. ......

  49. }

    這個(gè)函數(shù)通過Binder進(jìn)程間通信機(jī)制進(jìn)入到ApplicationThread.schedulePauseActivity函數(shù)中。

    Step 13. ApplicationThread.schedulePauseActivity

    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中倡怎,它是ActivityThread的內(nèi)部類:

  50. public final class ActivityThread {

  51. ......

  52. private final class ApplicationThread extends ApplicationThreadNative {

  53. ......

  54. public final void schedulePauseActivity(IBinder token, boolean finished,

  55. boolean userLeaving, int configChanges) {

  56. queueOrSendMessage(

  57. finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,

  58. token,

  59. (userLeaving ? 1 : 0),

  60. configChanges);

  61. }

  62. ......

  63. }

  64. ......

  65. }

    這里調(diào)用的函數(shù)queueOrSendMessage是ActivityThread類的成員函數(shù)迅耘。

    上面說到贱枣,這里的finished值為false,因此豹障,queueOrSendMessage的第一個(gè)參數(shù)值為H.PAUSE_ACTIVITY冯事,表示要暫停token所代表的Activity,即Launcher血公。

    Step 14. ActivityThread.queueOrSendMessage

    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:

  66. public final class ActivityThread {

  67. ......

  68. private final void queueOrSendMessage(int what, Object obj, int arg1) {

  69. queueOrSendMessage(what, obj, arg1, 0);

  70. }

  71. private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {

  72. synchronized (this) {

  73. ......

  74. Message msg = Message.obtain();

  75. msg.what = what;

  76. msg.obj = obj;

  77. msg.arg1 = arg1;

  78. msg.arg2 = arg2;

  79. mH.sendMessage(msg);

  80. }

  81. }

  82. ......

  83. }

    這里首先將相關(guān)信息組裝成一個(gè)msg昵仅,然后通過mH成員變量發(fā)送出去,mH的類型是H累魔,繼承于Handler類摔笤,是ActivityThread的內(nèi)部類,因此垦写,這個(gè)消息最后由H.handleMessage來處理吕世。

    Step 15. H.handleMessage

    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:

  84. public final class ActivityThread {

  85. ......

  86. private final class H extends Handler {

  87. ......

  88. public void handleMessage(Message msg) {

  89. ......

  90. switch (msg.what) {

  91. ......

  92. case PAUSE_ACTIVITY:

  93. handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);

  94. maybeSnapshot();

  95. break;

  96. ......

  97. }

  98. ......

  99. }

  100. ......

  101. }

    這里調(diào)用ActivityThread.handlePauseActivity進(jìn)一步操作,msg.obj是一個(gè)ActivityRecord對象的引用梯投,它代表的是Launcher這個(gè)Activity命辖。
    Step 16. ActivityThread.handlePauseActivity

    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:

  102. public final class ActivityThread {

  103. ......

  104. private final void handlePauseActivity(IBinder token, boolean finished,

  105. boolean userLeaving, int configChanges) {

  106. ActivityClientRecord r = mActivities.get(token);

  107. if (r != null) {

  108. //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);

  109. if (userLeaving) {

  110. performUserLeavingActivity(r);

  111. }

  112. r.activity.mConfigChangeFlags |= configChanges;

  113. Bundle state = performPauseActivity(token, finished, true);

  114. // Make sure any pending writes are now committed.

  115. QueuedWork.waitToFinish();

  116. // Tell the activity manager we have paused.

  117. try {

  118. ActivityManagerNative.getDefault().activityPaused(token, state);

  119. } catch (RemoteException ex) {

  120. }

  121. }

  122. }

  123. ......

  124. }

    函數(shù)首先將Binder引用token轉(zhuǎn)換成ActivityRecord的遠(yuǎn)程接口ActivityClientRecord,然后做了三個(gè)事情:1\. 如果userLeaving為true分蓖,則通過調(diào)用performUserLeavingActivity函數(shù)來調(diào)用Activity.onUserLeaveHint通知Activity尔艇,用戶要離開它了;2\. 調(diào)用performPauseActivity函數(shù)來調(diào)用Activity.onPause函數(shù)么鹤,我們知道终娃,在Activity的生命周期中,當(dāng)它要讓位于其它的Activity時(shí)蒸甜,系統(tǒng)就會(huì)調(diào)用它的onPause函數(shù)棠耕;3\. 它通知ActivityManagerService,這個(gè)Activity已經(jīng)進(jìn)入Paused狀態(tài)了柠新,ActivityManagerService現(xiàn)在可以完成未竟的事情窍荧,即啟動(dòng)MainActivity了。
    

    Step 17. ActivityManagerProxy.activityPaused

    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ActivityManagerNative.java文件中:

  125. class ActivityManagerProxy implements IActivityManager

  126. {

  127. ......

  128. public void activityPaused(IBinder token, Bundle state) throws RemoteException

  129. {

  130. Parcel data = Parcel.obtain();

  131. Parcel reply = Parcel.obtain();

  132. data.writeInterfaceToken(IActivityManager.descriptor);

  133. data.writeStrongBinder(token);

  134. data.writeBundle(state);

  135. mRemote.transact(ACTIVITY_PAUSED_TRANSACTION, data, reply, 0);

  136. reply.readException();

  137. data.recycle();

  138. reply.recycle();

  139. }

  140. ......

  141. }

    這里通過Binder進(jìn)程間通信機(jī)制就進(jìn)入到ActivityManagerService.activityPaused函數(shù)中去了恨憎。

    Step 18. ActivityManagerService.activityPaused

    這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:

  142. public final class ActivityManagerService extends ActivityManagerNative

  143. implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

  144. ......

  145. public final void activityPaused(IBinder token, Bundle icicle) {

  146. ......

  147. final long origId = Binder.clearCallingIdentity();

  148. mMainStack.activityPaused(token, icicle, false);

  149. ......

  150. }

  151. ......

  152. }

    這里蕊退,又再次進(jìn)入到ActivityStack類中,執(zhí)行activityPaused函數(shù)框咙。

    Step 19. ActivityStack.activityPaused

    這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:

  153. public class ActivityStack {

  154. ......

  155. final void activityPaused(IBinder token, Bundle icicle, boolean timeout) {

  156. ......

  157. ActivityRecord r = null;

  158. synchronized (mService) {

  159. int index = indexOfTokenLocked(token);

  160. if (index >= 0) {

  161. r = (ActivityRecord)mHistory.get(index);

  162. if (!timeout) {

  163. r.icicle = icicle;

  164. r.haveState = true;

  165. }

  166. mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);

  167. if (mPausingActivity == r) {

  168. r.state = ActivityState.PAUSED;

  169. completePauseLocked();

  170. } else {

  171. ......

  172. }

  173. }

  174. }

  175. }

  176. ......

  177. }

    這里通過參數(shù)token在mHistory列表中得到ActivityRecord,從上面我們知道痢甘,這個(gè)ActivityRecord代表的是Launcher這個(gè)Activity喇嘱,而我們在Step 11中,把Launcher這個(gè)Activity的信息保存在mPausingActivity中塞栅,因此者铜,這里mPausingActivity等于r,于是,執(zhí)行completePauseLocked操作作烟。

    Step 20. ActivityStack.completePauseLocked

    這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:

  178. public class ActivityStack {

  179. ......

  180. private final void completePauseLocked() {

  181. ActivityRecord prev = mPausingActivity;

  182. ......

  183. if (prev != null) {

  184. ......

  185. mPausingActivity = null;

  186. }

  187. if (!mService.mSleeping && !mService.mShuttingDown) {

  188. resumeTopActivityLocked(prev);

  189. } else {

  190. ......

  191. }

  192. ......

  193. }

  194. ......

  195. }

    函數(shù)首先把mPausingActivity變量清空愉粤,因?yàn)楝F(xiàn)在不需要它了,然后調(diào)用resumeTopActivityLokced進(jìn)一步操作拿撩,它傳入的參數(shù)即為代表Launcher這個(gè)Activity的ActivityRecord衣厘。

    Step 21. ActivityStack.resumeTopActivityLokced
    這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:

  196. public class ActivityStack {

  197. ......

  198. final boolean resumeTopActivityLocked(ActivityRecord prev) {

  199. ......

  200. // Find the first activity that is not finishing.

  201. ActivityRecord next = topRunningActivityLocked(null);

  202. // Remember how we'll process this pause/resume situation, and ensure

  203. // that the state is reset however we wind up proceeding.

  204. final boolean userLeaving = mUserLeaving;

  205. mUserLeaving = false;

  206. ......

  207. next.delayedResume = false;

  208. // If the top activity is the resumed one, nothing to do.

  209. if (mResumedActivity == next && next.state == ActivityState.RESUMED) {

  210. ......

  211. return false;

  212. }

  213. // If we are sleeping, and there is no resumed activity, and the top

  214. // activity is paused, well that is the state we want.

  215. if ((mService.mSleeping || mService.mShuttingDown)

  216. && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {

  217. ......

  218. return false;

  219. }

  220. .......

  221. // We need to start pausing the current activity so the top one

  222. // can be resumed...

  223. if (mResumedActivity != null) {

  224. ......

  225. return true;

  226. }

  227. ......

  228. if (next.app != null && next.app.thread != null) {

  229. ......

  230. } else {

  231. ......

  232. startSpecificActivityLocked(next, true, true);

  233. }

  234. return true;

  235. }

  236. ......

  237. }

    通過上面的Step 9,我們知道压恒,當(dāng)前在堆棧頂端的Activity為我們即將要啟動(dòng)的MainActivity影暴,這里通過調(diào)用topRunningActivityLocked將它取回來,保存在next變量中探赫。之前最后一個(gè)Resumed狀態(tài)的Activity型宙,即Launcher,到了這里已經(jīng)處于Paused狀態(tài)了伦吠,因此妆兑,mResumedActivity為null。最后一個(gè)處于Paused狀態(tài)的Activity為Launcher毛仪,因此搁嗓,這里的mLastPausedActivity就為Launcher。前面我們?yōu)镸ainActivity創(chuàng)建了ActivityRecord后潭千,它的app域一直保持為null谱姓。有了這些信息后,上面這段代碼就容易理解了刨晴,它最終調(diào)用startSpecificActivityLocked進(jìn)行下一步操作屉来。

    Step 22. ActivityStack.startSpecificActivityLocked
    這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:

  238. public class ActivityStack {

  239. ......

  240. private final void startSpecificActivityLocked(ActivityRecord r,

  241. boolean andResume, boolean checkConfig) {

  242. // Is this activity's application already running?

  243. ProcessRecord app = mService.getProcessRecordLocked(r.processName,

  244. r.info.applicationInfo.uid);

  245. ......

  246. if (app != null && app.thread != null) {

  247. try {

  248. realStartActivityLocked(r, app, andResume, checkConfig);

  249. return;

  250. } catch (RemoteException e) {

  251. ......

  252. }

  253. }

  254. mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,

  255. "activity", r.intent.getComponent(), false);

  256. }

  257. ......

  258. }

    注意,這里由于是第一次啟動(dòng)應(yīng)用程序的Activity狈癞,所以下面語句:

  259. ProcessRecord app = mService.getProcessRecordLocked(r.processName,

  260. r.info.applicationInfo.uid);

取回來的app為null茄靠。在Activity應(yīng)用程序中的AndroidManifest.xml配置文件中,我們沒有指定Application標(biāo)簽的process屬性蝶桶,系統(tǒng)就會(huì)默認(rèn)使用package的名稱慨绳,這里就是"shy.luo.activity"了。每一個(gè)應(yīng)用程序都有自己的uid真竖,因此脐雪,這里uid + process的組合就可以為每一個(gè)應(yīng)用程序創(chuàng)建一個(gè)ProcessRecord。當(dāng)然恢共,我們可以配置兩個(gè)應(yīng)用程序具有相同的uid和package战秋,或者在AndroidManifest.xml配置文件的application標(biāo)簽或者activity標(biāo)簽中顯式指定相同的process屬性值,這樣讨韭,不同的應(yīng)用程序也可以在同一個(gè)進(jìn)程中啟動(dòng)脂信。

函數(shù)最終執(zhí)行ActivityManagerService.startProcessLocked函數(shù)進(jìn)行下一步操作癣蟋。

Step 23. ActivityManagerService.startProcessLocked

這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:

  1. public final class ActivityManagerService extends ActivityManagerNative

  2. implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

  3. ......

  4. final ProcessRecord startProcessLocked(String processName,

  5. ApplicationInfo info, boolean knownToBeDead, int intentFlags,

  6. String hostingType, ComponentName hostingName, boolean allowWhileBooting) {

  7. ProcessRecord app = getProcessRecordLocked(processName, info.uid);

  8. ......

  9. String hostingNameStr = hostingName != null

  10. ? hostingName.flattenToShortString() : null;

  11. ......

  12. if (app == null) {

  13. app = new ProcessRecordLocked(null, info, processName);

  14. mProcessNames.put(processName, info.uid, app);

  15. } else {

  16. // If this is a new package in the process, add the package to the list

  17. app.addPackage(info.packageName);

  18. }

  19. ......

  20. startProcessLocked(app, hostingType, hostingNameStr);

  21. return (app.pid != 0) ? app : null;

  22. }

  23. ......

  24. }

    這里再次檢查是否已經(jīng)有以process + uid命名的進(jìn)程存在,在我們這個(gè)情景中狰闪,返回值app為null疯搅,因此,后面會(huì)創(chuàng)建一個(gè)ProcessRecord埋泵,并存保存在成員變量mProcessNames中幔欧,最后,調(diào)用另一個(gè)startProcessLocked函數(shù)進(jìn)一步操作:

  25. public final class ActivityManagerService extends ActivityManagerNative

  26. implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

  27. ......

  28. private final void startProcessLocked(ProcessRecord app,

  29. String hostingType, String hostingNameStr) {

  30. ......

  31. try {

  32. int uid = app.info.uid;

  33. int[] gids = null;

  34. try {

  35. gids = mContext.getPackageManager().getPackageGids(

  36. app.info.packageName);

  37. } catch (PackageManager.NameNotFoundException e) {

  38. ......

  39. }

  40. ......

  41. int debugFlags = 0;

  42. ......

  43. int pid = Process.start("android.app.ActivityThread",

  44. mSimpleProcessManagement ? app.processName : null, uid, uid,

  45. gids, debugFlags, null);

  46. ......

  47. } catch (RuntimeException e) {

  48. ......

  49. }

  50. }

  51. ......

  52. }

    這里主要是調(diào)用Process.start接口來創(chuàng)建一個(gè)新的進(jìn)程秋泄,新的進(jìn)程會(huì)導(dǎo)入android.app.ActivityThread類琐馆,并且執(zhí)行它的main函數(shù),這就是為什么我們前面說每一個(gè)應(yīng)用程序都有一個(gè)ActivityThread實(shí)例來對應(yīng)的原因恒序。

    Step 24. ActivityThread.main

    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:

  53. public final class ActivityThread {

  54. ......

  55. private final void attach(boolean system) {

  56. ......

  57. mSystemThread = system;

  58. if (!system) {

  59. ......

  60. IActivityManager mgr = ActivityManagerNative.getDefault();

  61. try {

  62. mgr.attachApplication(mAppThread);

  63. } catch (RemoteException ex) {

  64. }

  65. } else {

  66. ......

  67. }

  68. }

  69. ......

  70. public static final void main(String[] args) {

  71. .......

  72. ActivityThread thread = new ActivityThread();

  73. thread.attach(false);

  74. ......

  75. Looper.loop();

  76. .......

  77. thread.detach();

  78. ......

  79. }

  80. }

    這個(gè)函數(shù)在進(jìn)程中創(chuàng)建一個(gè)ActivityThread實(shí)例瘦麸,然后調(diào)用它的attach函數(shù),接著就進(jìn)入消息循環(huán)了歧胁,直到最后進(jìn)程退出滋饲。

    函數(shù)attach最終調(diào)用了ActivityManagerService的遠(yuǎn)程接口ActivityManagerProxy的attachApplication函數(shù),傳入的參數(shù)是mAppThread喊巍,這是一個(gè)ApplicationThread類型的Binder對象屠缭,它的作用是用來進(jìn)行進(jìn)程間通信的。

    Step 25. ActivityManagerProxy.attachApplication

    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ActivityManagerNative.java文件中:

  81. class ActivityManagerProxy implements IActivityManager

  82. {

  83. ......

  84. public void attachApplication(IApplicationThread app) throws RemoteException

  85. {

  86. Parcel data = Parcel.obtain();

  87. Parcel reply = Parcel.obtain();

  88. data.writeInterfaceToken(IActivityManager.descriptor);

  89. data.writeStrongBinder(app.asBinder());

  90. mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0);

  91. reply.readException();

  92. data.recycle();

  93. reply.recycle();

  94. }

  95. ......

  96. }

    這里通過Binder驅(qū)動(dòng)程序崭参,最后進(jìn)入ActivityManagerService的attachApplication函數(shù)中呵曹。

    Step 26. ActivityManagerService.attachApplication

    這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:

  97. public final class ActivityManagerService extends ActivityManagerNative

  98. implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

  99. ......

  100. public final void attachApplication(IApplicationThread thread) {

  101. synchronized (this) {

  102. int callingPid = Binder.getCallingPid();

  103. final long origId = Binder.clearCallingIdentity();

  104. attachApplicationLocked(thread, callingPid);

  105. Binder.restoreCallingIdentity(origId);

  106. }

  107. }

  108. ......

  109. }

    這里將操作轉(zhuǎn)發(fā)給attachApplicationLocked函數(shù)。

    Step 27. ActivityManagerService.attachApplicationLocked

    這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:

  110. public final class ActivityManagerService extends ActivityManagerNative

  111. implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

  112. ......

  113. private final boolean attachApplicationLocked(IApplicationThread thread,

  114. int pid) {

  115. // Find the application record that is being attached... either via

  116. // the pid if we are running in multiple processes, or just pull the

  117. // next app record if we are emulating process with anonymous threads.

  118. ProcessRecord app;

  119. if (pid != MY_PID && pid >= 0) {

  120. synchronized (mPidsSelfLocked) {

  121. app = mPidsSelfLocked.get(pid);

  122. }

  123. } else if (mStartingProcesses.size() > 0) {

  124. ......

  125. } else {

  126. ......

  127. }

  128. if (app == null) {

  129. ......

  130. return false;

  131. }

  132. ......

  133. String processName = app.processName;

  134. try {

  135. thread.asBinder().linkToDeath(new AppDeathRecipient(

  136. app, pid, thread), 0);

  137. } catch (RemoteException e) {

  138. ......

  139. return false;

  140. }

  141. ......

  142. app.thread = thread;

  143. app.curAdj = app.setAdj = -100;

  144. app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;

  145. app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;

  146. app.forcingToForeground = null;

  147. app.foregroundServices = false;

  148. app.debugging = false;

  149. ......

  150. boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);

  151. ......

  152. boolean badApp = false;

  153. boolean didSomething = false;

  154. // See if the top visible activity is waiting to run in this process...

  155. ActivityRecord hr = mMainStack.topRunningActivityLocked(null);

  156. if (hr != null && normalMode) {

  157. if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid

  158. && processName.equals(hr.processName)) {

  159. try {

  160. if (mMainStack.realStartActivityLocked(hr, app, true, true)) {

  161. didSomething = true;

  162. }

  163. } catch (Exception e) {

  164. ......

  165. }

  166. } else {

  167. ......

  168. }

  169. }

  170. ......

  171. return true;

  172. }

  173. ......

  174. }

    在前面的Step 23中何暮,已經(jīng)創(chuàng)建了一個(gè)ProcessRecord奄喂,這里首先通過pid將它取回來,放在app變量中海洼,然后對app的其它成員進(jìn)行初始化跨新,最后調(diào)用mMainStack.realStartActivityLocked執(zhí)行真正的Activity啟動(dòng)操作。這里要啟動(dòng)的Activity通過調(diào)用mMainStack.topRunningActivityLocked(null)從堆棧頂端取回來坏逢,這時(shí)候在堆棧頂端的Activity就是MainActivity了域帐。

    Step 28. ActivityStack.realStartActivityLocked

    這個(gè)函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:

  175. public class ActivityStack {

  176. ......

  177. final boolean realStartActivityLocked(ActivityRecord r,

  178. ProcessRecord app, boolean andResume, boolean checkConfig)

  179. throws RemoteException {

  180. ......

  181. r.app = app;

  182. ......

  183. int idx = app.activities.indexOf(r);

  184. if (idx < 0) {

  185. app.activities.add(r);

  186. }

  187. ......

  188. try {

  189. ......

  190. List<ResultInfo> results = null;

  191. List<Intent> newIntents = null;

  192. if (andResume) {

  193. results = r.results;

  194. newIntents = r.newIntents;

  195. }

  196. ......

  197. app.thread.scheduleLaunchActivity(new Intent(r.intent), r,

  198. System.identityHashCode(r),

  199. r.info, r.icicle, results, newIntents, !andResume,

  200. mService.isNextTransitionForward());

  201. ......

  202. } catch (RemoteException e) {

  203. ......

  204. }

  205. ......

  206. return true;

  207. }

  208. ......

  209. }

    這里最終通過app.thread進(jìn)入到ApplicationThreadProxy的scheduleLaunchActivity函數(shù)中,注意是整,這里的第二個(gè)參數(shù)r肖揣,是一個(gè)ActivityRecord類型的Binder對象,用來作來這個(gè)Activity的token值浮入。

    Step 29. ApplicationThreadProxy.scheduleLaunchActivity
    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ApplicationThreadNative.java文件中:

  210. class ApplicationThreadProxy implements IApplicationThread {

  211. ......

  212. public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,

  213. ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,

  214. List<Intent> pendingNewIntents, boolean notResumed, boolean isForward)

  215. throws RemoteException {

  216. Parcel data = Parcel.obtain();

  217. data.writeInterfaceToken(IApplicationThread.descriptor);

  218. intent.writeToParcel(data, 0);

  219. data.writeStrongBinder(token);

  220. data.writeInt(ident);

  221. info.writeToParcel(data, 0);

  222. data.writeBundle(state);

  223. data.writeTypedList(pendingResults);

  224. data.writeTypedList(pendingNewIntents);

  225. data.writeInt(notResumed ? 1 : 0);

  226. data.writeInt(isForward ? 1 : 0);

  227. mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,

  228. IBinder.FLAG_ONEWAY);

  229. data.recycle();

  230. }

  231. ......

  232. }

    這個(gè)函數(shù)最終通過Binder驅(qū)動(dòng)程序進(jìn)入到ApplicationThread的scheduleLaunchActivity函數(shù)中龙优。

    Step 30. ApplicationThread.scheduleLaunchActivity
    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:

  233. public final class ActivityThread {

  234. ......

  235. private final class ApplicationThread extends ApplicationThreadNative {

  236. ......

  237. // we use token to identify this activity without having to send the

  238. // activity itself back to the activity manager. (matters more with ipc)

  239. public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,

  240. ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,

  241. List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {

  242. ActivityClientRecord r = new ActivityClientRecord();

  243. r.token = token;

  244. r.ident = ident;

  245. r.intent = intent;

  246. r.activityInfo = info;

  247. r.state = state;

  248. r.pendingResults = pendingResults;

  249. r.pendingIntents = pendingNewIntents;

  250. r.startsNotResumed = notResumed;

  251. r.isForward = isForward;

  252. queueOrSendMessage(H.LAUNCH_ACTIVITY, r);

  253. }

  254. ......

  255. }

  256. ......

  257. }

    函數(shù)首先創(chuàng)建一個(gè)ActivityClientRecord實(shí)例溯香,并且初始化它的成員變量谬莹,然后調(diào)用ActivityThread類的queueOrSendMessage函數(shù)進(jìn)一步處理剃允。
    
    Step 31. ActivityThread.queueOrSendMessage
    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:
    
  258. public final class ActivityThread {

  259. ......

  260. private final class ApplicationThread extends ApplicationThreadNative {

  261. ......

  262. // if the thread hasn't started yet, we don't have the handler, so just

  263. // save the messages until we're ready.

  264. private final void queueOrSendMessage(int what, Object obj) {

  265. queueOrSendMessage(what, obj, 0, 0);

  266. }

  267. ......

  268. private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {

  269. synchronized (this) {

  270. ......

  271. Message msg = Message.obtain();

  272. msg.what = what;

  273. msg.obj = obj;

  274. msg.arg1 = arg1;

  275. msg.arg2 = arg2;

  276. mH.sendMessage(msg);

  277. }

  278. }

  279. ......

  280. }

  281. ......

  282. }

    函數(shù)把消息內(nèi)容放在msg中逮刨,然后通過mH把消息分發(fā)出去秽晚,這里的成員變量mH我們在前面已經(jīng)見過瓦糟,消息分發(fā)出去后,最后會(huì)調(diào)用H類的handleMessage函數(shù)赴蝇。

    Step 32. H.handleMessage

    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:

  283. public final class ActivityThread {

  284. ......

  285. private final class H extends Handler {

  286. ......

  287. public void handleMessage(Message msg) {

  288. ......

  289. switch (msg.what) {

  290. case LAUNCH_ACTIVITY: {

  291. ActivityClientRecord r = (ActivityClientRecord)msg.obj;

  292. r.packageInfo = getPackageInfoNoCheck(

  293. r.activityInfo.applicationInfo);

  294. handleLaunchActivity(r, null);

  295. } break;

  296. ......

  297. }

  298. ......

  299. }

  300. ......

  301. }

    這里最后調(diào)用ActivityThread類的handleLaunchActivity函數(shù)進(jìn)一步處理菩浙。

    Step 33. ActivityThread.handleLaunchActivity

    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:

  302. public final class ActivityThread {

  303. ......

  304. private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {

  305. ......

  306. Activity a = performLaunchActivity(r, customIntent);

  307. if (a != null) {

  308. r.createdConfig = new Configuration(mConfiguration);

  309. Bundle oldState = r.state;

  310. handleResumeActivity(r.token, false, r.isForward);

  311. ......

  312. } else {

  313. ......

  314. }

  315. }

  316. ......

  317. }

    這里首先調(diào)用performLaunchActivity函數(shù)來加載這個(gè)Activity類,即shy.luo.activity.MainActivity句伶,然后調(diào)用它的onCreate函數(shù)劲蜻,最后回到handleLaunchActivity函數(shù)時(shí),再調(diào)用handleResumeActivity函數(shù)來使這個(gè)Activity進(jìn)入Resumed狀態(tài)考余,即會(huì)調(diào)用這個(gè)Activity的onResume函數(shù)先嬉,這是遵循Activity的生命周期的。

    Step 34. ActivityThread.performLaunchActivity
    這個(gè)函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:

  318. public final class ActivityThread {

  319. ......

  320. private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

  321. ActivityInfo aInfo = r.activityInfo;

  322. if (r.packageInfo == null) {

  323. r.packageInfo = getPackageInfo(aInfo.applicationInfo,

  324. Context.CONTEXT_INCLUDE_CODE);

  325. }

  326. ComponentName component = r.intent.getComponent();

  327. if (component == null) {

  328. component = r.intent.resolveActivity(

  329. mInitialApplication.getPackageManager());

  330. r.intent.setComponent(component);

  331. }

  332. if (r.activityInfo.targetActivity != null) {

  333. component = new ComponentName(r.activityInfo.packageName,

  334. r.activityInfo.targetActivity);

  335. }

  336. Activity activity = null;

  337. try {

  338. java.lang.ClassLoader cl = r.packageInfo.getClassLoader();

  339. activity = mInstrumentation.newActivity(

  340. cl, component.getClassName(), r.intent);

  341. r.intent.setExtrasClassLoader(cl);

  342. if (r.state != null) {

  343. r.state.setClassLoader(cl);

  344. }

  345. } catch (Exception e) {

  346. ......

  347. }

  348. try {

  349. Application app = r.packageInfo.makeApplication(false, mInstrumentation);

  350. ......

  351. if (activity != null) {

  352. ContextImpl appContext = new ContextImpl();

  353. appContext.init(r.packageInfo, r.token, this);

  354. appContext.setOuterContext(activity);

  355. CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());

  356. Configuration config = new Configuration(mConfiguration);

  357. ......

  358. activity.attach(appContext, this, getInstrumentation(), r.token,

  359. r.ident, app, r.intent, r.activityInfo, title, r.parent,

  360. r.embeddedID, r.lastNonConfigurationInstance,

  361. r.lastNonConfigurationChildInstances, config);

  362. if (customIntent != null) {

  363. activity.mIntent = customIntent;

  364. }

  365. r.lastNonConfigurationInstance = null;

  366. r.lastNonConfigurationChildInstances = null;

  367. activity.mStartedActivity = false;

  368. int theme = r.activityInfo.getThemeResource();

  369. if (theme != 0) {

  370. activity.setTheme(theme);

  371. }

  372. activity.mCalled = false;

  373. mInstrumentation.callActivityOnCreate(activity, r.state);

  374. ......

  375. r.activity = activity;

  376. r.stopped = true;

  377. if (!r.activity.mFinished) {

  378. activity.performStart();

  379. r.stopped = false;

  380. }

  381. if (!r.activity.mFinished) {

  382. if (r.state != null) {

  383. mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);

  384. }

  385. }

  386. if (!r.activity.mFinished) {

  387. activity.mCalled = false;

  388. mInstrumentation.callActivityOnPostCreate(activity, r.state);

  389. if (!activity.mCalled) {

  390. throw new SuperNotCalledException(

  391. "Activity " + r.intent.getComponent().toShortString() +

  392. " did not call through to super.onPostCreate()");

  393. }

  394. }

  395. }

  396. r.paused = true;

  397. mActivities.put(r.token, r);

  398. } catch (SuperNotCalledException e) {

  399. ......

  400. } catch (Exception e) {

  401. ......

  402. }

  403. return activity;

  404. }

  405. ......

  406. }

    函數(shù)前面是收集要啟動(dòng)的Activity的相關(guān)信息楚堤,主要package和component信息:

  407. ActivityInfo aInfo = r.activityInfo;

  408. if (r.packageInfo == null) {

  409. r.packageInfo = getPackageInfo(aInfo.applicationInfo,

  410. Context.CONTEXT_INCLUDE_CODE);

  411. }

  412. ComponentName component = r.intent.getComponent();

  413. if (component == null) {

  414. component = r.intent.resolveActivity(

  415. mInitialApplication.getPackageManager());

  416. r.intent.setComponent(component);

  417. }

  418. if (r.activityInfo.targetActivity != null) {

  419. component = new ComponentName(r.activityInfo.packageName,

  420. r.activityInfo.targetActivity);

  421. }

然后通過ClassLoader將shy.luo.activity.MainActivity類加載進(jìn)來:

  1. Activity activity = null;

  2. try {

  3. java.lang.ClassLoader cl = r.packageInfo.getClassLoader();

  4. activity = mInstrumentation.newActivity(

  5. cl, component.getClassName(), r.intent);

  6. r.intent.setExtrasClassLoader(cl);

  7. if (r.state != null) {

  8. r.state.setClassLoader(cl);

  9. }

  10. } catch (Exception e) {

  11. ......

  12. }

接下來是創(chuàng)建Application對象疫蔓,這是根據(jù)AndroidManifest.xml配置文件中的Application標(biāo)簽的信息來創(chuàng)建的:

   Application app = r.packageInfo.makeApplication(false, mInstrumentation);
  后面的代碼主要?jiǎng)?chuàng)建Activity的上下文信息,并通過attach方法將這些上下文信息設(shè)置到MainActivity中去:
  1. activity.attach(appContext, this, getInstrumentation(), r.token,

  2. r.ident, app, r.intent, r.activityInfo, title, r.parent,

  3. r.embeddedID, r.lastNonConfigurationInstance,

  4. r.lastNonConfigurationChildInstances, config);

最后還要調(diào)用MainActivity的onCreate函數(shù):

   mInstrumentation.callActivityOnCreate(activity, r.state);
  這里不是直接調(diào)用MainActivity的onCreate函數(shù)身冬,而是通過mInstrumentation的callActivityOnCreate函數(shù)來間接調(diào)用衅胀,前面我們說過,mInstrumentation在這里的作用是監(jiān)控Activity與系統(tǒng)的交互操作酥筝,相當(dāng)于是系統(tǒng)運(yùn)行日志滚躯。

  Step 35\. MainActivity.onCreate

  這個(gè)函數(shù)定義在packages/experimental/Activity/src/shy/luo/activity/MainActivity.java文件中,這是我們自定義的app工程文件:
  1. public class MainActivity extends Activity implements OnClickListener {

  2. ......

  3. @Override

  4. public void onCreate(Bundle savedInstanceState) {

  5. ......

  6. Log.i(LOG_TAG, "Main Activity Created.");

  7. }

  8. ......

  9. }

    這樣嘿歌,MainActivity就啟動(dòng)起來了掸掏,整個(gè)應(yīng)用程序也啟動(dòng)起來了。

    整個(gè)應(yīng)用程序的啟動(dòng)過程要執(zhí)行很多步驟搅幅,但是整體來看阅束,主要分為以下五個(gè)階段:

    一. Step1 - Step 11:Launcher通過Binder進(jìn)程間通信機(jī)制通知ActivityManagerService,它要啟動(dòng)一個(gè)Activity茄唐;

    二. Step 12 - Step 16:ActivityManagerService通過Binder進(jìn)程間通信機(jī)制通知Launcher進(jìn)入Paused狀態(tài)息裸;

    三. Step 17 - Step 24:Launcher通過Binder進(jìn)程間通信機(jī)制通知ActivityManagerService,它已經(jīng)準(zhǔn)備就緒進(jìn)入Paused狀態(tài)沪编,于是ActivityManagerService就創(chuàng)建一個(gè)新的進(jìn)程呼盆,用來啟動(dòng)一個(gè)ActivityThread實(shí)例,即將要啟動(dòng)的Activity就是在這個(gè)ActivityThread實(shí)例中運(yùn)行蚁廓;

    四. Step 25 - Step 27:ActivityThread通過Binder進(jìn)程間通信機(jī)制將一個(gè)ApplicationThread類型的Binder對象傳遞給ActivityManagerService访圃,以便以后ActivityManagerService能夠通過這個(gè)Binder對象和它進(jìn)行通信;

    五. Step 28 - Step 35:ActivityManagerService通過Binder進(jìn)程間通信機(jī)制通知ActivityThread相嵌,現(xiàn)在一切準(zhǔn)備就緒腿时,它可以真正執(zhí)行Activity的啟動(dòng)操作了况脆。

    這里不少地方涉及到了Binder進(jìn)程間通信機(jī)制,相關(guān)資料請參考Android進(jìn)程間通信(IPC)機(jī)制Binder簡要介紹和學(xué)習(xí)計(jì)劃一文批糟。

    這樣格了,應(yīng)用程序的啟動(dòng)過程就介紹完了,它實(shí)質(zhì)上是啟動(dòng)應(yīng)用程序的默認(rèn)Activity徽鼎。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末盛末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子否淤,更是在濱河造成了極大的恐慌悄但,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,214評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件石抡,死亡現(xiàn)場離奇詭異檐嚣,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)啰扛,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評論 2 382
  • 文/潘曉璐 我一進(jìn)店門净嘀,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人侠讯,你說我怎么就攤上這事挖藏。” “怎么了厢漩?”我有些...
    開封第一講書人閱讀 152,543評論 0 341
  • 文/不壞的土叔 我叫張陵膜眠,是天一觀的道長。 經(jīng)常有香客問我溜嗜,道長宵膨,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,221評論 1 279
  • 正文 為了忘掉前任炸宵,我火速辦了婚禮辟躏,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘土全。我一直安慰自己捎琐,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,224評論 5 371
  • 文/花漫 我一把揭開白布裹匙。 她就那樣靜靜地躺著瑞凑,像睡著了一般。 火紅的嫁衣襯著肌膚如雪概页。 梳的紋絲不亂的頭發(fā)上籽御,一...
    開封第一講書人閱讀 49,007評論 1 284
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼技掏。 笑死铃将,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的哑梳。 我是一名探鬼主播麸塞,決...
    沈念sama閱讀 38,313評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼涧衙!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起奥此,我...
    開封第一講書人閱讀 36,956評論 0 259
  • 序言:老撾萬榮一對情侶失蹤弧哎,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后稚虎,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體撤嫩,經(jīng)...
    沈念sama閱讀 43,441評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,925評論 2 323
  • 正文 我和宋清朗相戀三年蠢终,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了序攘。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,018評論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡寻拂,死狀恐怖程奠,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情祭钉,我是刑警寧澤瞄沙,帶...
    沈念sama閱讀 33,685評論 4 322
  • 正文 年R本政府宣布,位于F島的核電站慌核,受9級特大地震影響距境,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜垮卓,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,234評論 3 307
  • 文/蒙蒙 一垫桂、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧粟按,春花似錦诬滩、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,240評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至宗侦,卻和暖如春愚臀,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背矾利。 一陣腳步聲響...
    開封第一講書人閱讀 31,464評論 1 261
  • 我被黑心中介騙來泰國打工姑裂, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留馋袜,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,467評論 2 352
  • 正文 我出身青樓舶斧,卻偏偏與公主長得像欣鳖,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子茴厉,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,762評論 2 345

推薦閱讀更多精彩內(nèi)容