2018-09-06

本文重点介绍应用程序的启动过程,应用程序的启动过程实际上就是应用程序中的默认Activity的启动过程,本文将详细分析应用程序框架层的源代码,了解Android应用程序的启动过程。

    下面详细分析每一步是如何实现的。

    Step 1\. Launcher.startActivitySafely

    在Android系统中,应用程序是由Launcher启动起来的,其实,Launcher本身也是一个应用程序,其它的应用程序安装后,就会Launcher的界面上出现一个相应的图标,点击这个图标时,Launcher就会对应的应用程序启动起来。

    Launcher的源代码工程在packages/apps/Launcher2目录下,负责启动其它应用程序的源代码实现在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应用程序的Activity启动过程简要介绍和学习计划说到的应用程序Activity,它的默认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",表示它要启动的Activity为shy.luo.activity.MainActivity。Intent.FLAG_ACTIVITY_NEW_TASK表示要在一个新的Task中启动这个Activity,注意,Task是Android系统中的概念,它不同于进程Process的概念。简单地说,一个Task是一系列Activity的集合,这个集合是以堆栈的形式来组织的,遵循后进先出的原则。事实上,Task是一个非常复杂的概念,有兴趣的读者可以到官网[http://developer.android.com/guide/topics/manifest/activity-element.html](http://developer.android.com/guide/topics/manifest/activity-element.html)查看相关的资料。这里,我们只要知道,这个MainActivity要在一个新的Task中启动就可以了。
    
    Step 2\. Activity.startActivity
    
    在Step 1中,我们看到,Launcher继承于Activity类,而Activity类实现了startActivity函数,因此,这里就调用了Activity.startActivity函数,它实现在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. }

    这个函数实现很简单,它调用startActivityForResult来进一步处理,第二个参数传入-1表示不需要这个Actvity结束后的返回结果。

    Step 3. Activity.startActivityForResult

    这个函数也是实现在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文件中,它用来监控应用程序和系统的交互。
    
    这里的mMainThread也是Activity类的成员变量,它的类型是ActivityThread,它代表的是应用程序的主线程,我们在[Android系统在新进程中启动自定义服务过程(startService)的原理分析](http://blog.csdn.net/luoshengyang/article/details/6677029)一文中已经介绍过了。这里通过mMainThread.getApplicationThread获得它里面的ApplicationThread成员变量,它是一个Binder对象,后面我们会看到,ActivityManagerService会使用它来和ActivityThread来进行进程间通信。这里我们需注意的是,这里的mMainThread代表的是Launcher应用程序运行的进程。
    
    这里的mToken也是Activity类的成员变量,它是一个Binder对象的远程接口。
    
    Step 4\. Instrumentation.execStartActivity
    这个函数定义在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的远程接口,即ActivityManagerProxy接口,具体可以参考[Android系统在新进程中启动自定义服务过程(startService)的原理分析](http://blog.csdn.net/luoshengyang/article/details/6677029)一文。
    
    这里的intent.resolveTypeIfNeeded返回这个intent的MIME类型,在这个例子中,没有AndroidManifest.xml设置MainActivity的MIME类型,因此,这里返回null。
    
    这里的target不为null,但是target.mEmbddedID为null,我们不用关注。
    
    Step 5\. ActivityManagerProxy.startActivity
    
    这个函数定义在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. }

    这里的参数比较多,我们先整理一下。从上面的调用可以知道,这里的参数resolvedType、grantedUriPermissions和resultWho均为null;参数caller为ApplicationThread类型的Binder实体;参数resultTo为一个Binder实体的远程接口,我们先不关注它;参数grantedMode为0,我们也先不关注它;参数requestCode为-1;参数onlyIfNeeded和debug均空false。

    Step 6. ActivityManagerService.startActivity

    上一步Step 5通过Binder驱动程序就进入到ActivityManagerService的startActivity函数来了,它定义在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. }

    这里只是简单地将操作转发给成员变量mMainStack的startActivityMayWait函数,这里的mMainStack的类型为ActivityStack。

    Step 7. ActivityStack.startActivityMayWait

    这个函数定义在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传下来的参数outResult和config均为null,此外,表达式(aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0为false,因此,这里忽略了无关代码。

    下面语句对参数intent的内容进行解析,得到MainActivity的相关信息,保存在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",这是在这个实例的配置文件AndroidManifest.xml里面配置的。

此外,函数开始的地方调用intent.getComponent()函数的返回值不为null,因此,这里的componentSpecified变量为true。

接下去就调用startActivityLocked进一步处理了。

Step 8\. ActivityStack.startActivityLocked

这个函数定义在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. }

    从传进来的参数caller得到调用者的进程信息,并保存在callerApp变量中,这里就是Launcher应用程序的进程信息了。

    前面说过,参数resultTo是Launcher这个Activity里面的一个Binder对象,通过它可以获得Launcher这个Activity的相关信息,保存在sourceRecord变量中。
    再接下来,创建即将要启动的Activity的相关信息,并保存在r变量中:

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

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

  60. resultRecord, resultWho, requestCode, componentSpecified);

接着调用startActivityUncheckedLocked函数进行下一步操作。

Step 9\. ActivityStack.startActivityUncheckedLocked

这个函数定义在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. }

    函数首先获得intent的标志值,保存在launchFlags变量中。

    这个intent的标志值的位Intent.FLAG_ACTIVITY_NO_USER_ACTION没有置位,因此 ,成员变量mUserLeaving的值为true。

    这个intent的标志值的位Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP也没有置位,因此,变量notTop的值为null。

    由于在这个例子的AndroidManifest.xml文件中,MainActivity没有配置launchMode属值,因此,这里的r.launchMode为默认值0,表示以标准(Standard,或者称为ActivityInfo.LAUNCH_MULTIPLE)的方式来启动这个Activity。Activity的启动方式有四种,其余三种分别是ActivityInfo.LAUNCH_SINGLE_INSTANCE、ActivityInfo.LAUNCH_SINGLE_TASK和ActivityInfo.LAUNCH_SINGLE_TOP,具体可以参考官方网站http://developer.android.com/reference/android/content/pm/ActivityInfo.html

    传进来的参数r.resultTo为null,表示Launcher不需要等这个即将要启动的MainActivity的执行结果。

    由于这个intent的标志值的位Intent.FLAG_ACTIVITY_NEW_TASK被置位,而且Intent.FLAG_ACTIVITY_MULTIPLE_TASK没有置位,因此,下面的if语句会被执行:

  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. }

这段代码的逻辑是查看一下,当前有没有Task可以用来执行这个Activity。由于r.launchMode的值不为ActivityInfo.LAUNCH_SINGLE_INSTANCE,因此,它通过findTaskLocked函数来查找存不存这样的Task,这里返回的结果是null,即taskTop为null,因此,需要创建一个新的Task来启动这个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. }

这段代码的逻辑是看一下,当前在堆栈顶端的Activity是否就是即将要启动的Activity,有些情况下,如果即将要启动的Activity就在堆栈的顶端,那么,就不会重新启动这个Activity的别一个实例了,具体可以参考官方网站[http://developer.android.com/reference/android/content/pm/ActivityInfo.html](http://developer.android.com/reference/android/content/pm/ActivityInfo.html)。现在处理堆栈顶端的Activity是Launcher,与我们即将要启动的MainActivity不是同一个Activity,因此,这里不用进一步处理上述介绍的情况。

执行到这里,我们知道,要在一个新的Task里面来启动这个Activity了,于是新创建一个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域中,同时,添加到mService中去,这里的mService就是ActivityManagerService了。

最后就进入startActivityLocked(r, newTask, doResume)进一步处理了。这个函数定义在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表示当前系统中历史任务的个数,这里肯定是大于0,因为Launcher已经跑起来了。当NH>0时,并且现在要切换新任务时,要做一些任务切的界面操作,这段代码我们就不看了,这里不会影响到下面启Activity的过程,有兴趣的读取可以自己研究一下。

    这里传进来的参数doResume为true,于是调用resumeTopActivityLocked进一步操作。

    Step 10. Activity.resumeTopActivityLocked

    这个函数定义在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. }

    函数先通过调用topRunningActivityLocked函数获得堆栈顶端的Activity,这里就是MainActivity了,这是在上面的Step 9设置好的,保存在next变量中。

    接下来把mUserLeaving的保存在本地变量userLeaving中,然后重新设置为false,在上面的Step 9中,mUserLeaving的值为true,因此,这里的userLeaving为true。

    这里的mResumedActivity为Launcher,因为Launcher是当前正被执行的Activity。

    当我们处理休眠状态时,mLastPausedActivity保存堆栈顶端的Activity,因为当前不是休眠状态,所以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. }

它首先看要启动的Activity是否就是当前处理Resumed状态的Activity,如果是的话,那就什么都不用做,直接返回就可以了;否则再看一下系统当前是否休眠状态,如果是的话,再看看要启动的Activity是否就是当前处于堆栈顶端的Activity,如果是的话,也是什么都不用做。

上面两个条件都不满足,因此,在继续往下执行之前,首先要把当处于Resumed状态的Activity推入Paused状态,然后才可以启动新的Activity。但是在将当前这个Resumed状态的Activity推入Paused状态之前,首先要看一下当前是否有Activity正在进入Pausing状态,如果有的话,当前这个Resumed状态的Activity就要稍后才能进入Paused状态了,这样就保证了所有需要进入Paused状态的Activity串行处理。

这里没有处于Pausing状态的Activity,即mPausingActivity为null,而且mResumedActivity也不为null,于是就调用startPausingLocked函数把Launcher推入Paused状态去了。

Step 11\. ActivityStack.startPausingLocked

这个函数定义在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. }

    函数首先把mResumedActivity保存在本地变量prev中。在上一步Step 10中,说到mResumedActivity就是Launcher,因此,这里把Launcher进程中的ApplicationThread对象取出来,通过它来通知Launcher这个Activity它要进入Paused状态了。当然,这里的prev.app.thread是一个ApplicationThread对象的远程接口,通过调用这个远程接口的schedulePauseActivity来通知Launcher进入Paused状态。

    参数prev.finishing表示prev所代表的Activity是否正在等待结束的Activity列表中,由于Laucher这个Activity还没结束,所以这里为false;参数prev.configChangeFlags表示哪些config发生了变化,这里我们不关心它的值。

    Step 12. ApplicationThreadProxy.schedulePauseActivity

    这个函数定义在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. }

    这个函数通过Binder进程间通信机制进入到ApplicationThread.schedulePauseActivity函数中。

    Step 13. ApplicationThread.schedulePauseActivity

    这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中,它是ActivityThread的内部类:

  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. }

    这里调用的函数queueOrSendMessage是ActivityThread类的成员函数。

    上面说到,这里的finished值为false,因此,queueOrSendMessage的第一个参数值为H.PAUSE_ACTIVITY,表示要暂停token所代表的Activity,即Launcher。

    Step 14. ActivityThread.queueOrSendMessage

    这个函数定义在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. }

    这里首先将相关信息组装成一个msg,然后通过mH成员变量发送出去,mH的类型是H,继承于Handler类,是ActivityThread的内部类,因此,这个消息最后由H.handleMessage来处理。

    Step 15. H.handleMessage

    这个函数定义在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. }

    这里调用ActivityThread.handlePauseActivity进一步操作,msg.obj是一个ActivityRecord对象的引用,它代表的是Launcher这个Activity。
    Step 16. ActivityThread.handlePauseActivity

    这个函数定义在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. }

    函数首先将Binder引用token转换成ActivityRecord的远程接口ActivityClientRecord,然后做了三个事情:1\. 如果userLeaving为true,则通过调用performUserLeavingActivity函数来调用Activity.onUserLeaveHint通知Activity,用户要离开它了;2\. 调用performPauseActivity函数来调用Activity.onPause函数,我们知道,在Activity的生命周期中,当它要让位于其它的Activity时,系统就会调用它的onPause函数;3\. 它通知ActivityManagerService,这个Activity已经进入Paused状态了,ActivityManagerService现在可以完成未竟的事情,即启动MainActivity了。
    

    Step 17. ActivityManagerProxy.activityPaused

    这个函数定义在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进程间通信机制就进入到ActivityManagerService.activityPaused函数中去了。

    Step 18. ActivityManagerService.activityPaused

    这个函数定义在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. }

    这里,又再次进入到ActivityStack类中,执行activityPaused函数。

    Step 19. ActivityStack.activityPaused

    这个函数定义在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. }

    这里通过参数token在mHistory列表中得到ActivityRecord,从上面我们知道,这个ActivityRecord代表的是Launcher这个Activity,而我们在Step 11中,把Launcher这个Activity的信息保存在mPausingActivity中,因此,这里mPausingActivity等于r,于是,执行completePauseLocked操作。

    Step 20. ActivityStack.completePauseLocked

    这个函数定义在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. }

    函数首先把mPausingActivity变量清空,因为现在不需要它了,然后调用resumeTopActivityLokced进一步操作,它传入的参数即为代表Launcher这个Activity的ActivityRecord。

    Step 21. ActivityStack.resumeTopActivityLokced
    这个函数定义在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,我们知道,当前在堆栈顶端的Activity为我们即将要启动的MainActivity,这里通过调用topRunningActivityLocked将它取回来,保存在next变量中。之前最后一个Resumed状态的Activity,即Launcher,到了这里已经处于Paused状态了,因此,mResumedActivity为null。最后一个处于Paused状态的Activity为Launcher,因此,这里的mLastPausedActivity就为Launcher。前面我们为MainActivity创建了ActivityRecord后,它的app域一直保持为null。有了这些信息后,上面这段代码就容易理解了,它最终调用startSpecificActivityLocked进行下一步操作。

    Step 22. ActivityStack.startSpecificActivityLocked
    这个函数定义在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. }

    注意,这里由于是第一次启动应用程序的Activity,所以下面语句:

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

  260. r.info.applicationInfo.uid);

取回来的app为null。在Activity应用程序中的AndroidManifest.xml配置文件中,我们没有指定Application标签的process属性,系统就会默认使用package的名称,这里就是"shy.luo.activity"了。每一个应用程序都有自己的uid,因此,这里uid + process的组合就可以为每一个应用程序创建一个ProcessRecord。当然,我们可以配置两个应用程序具有相同的uid和package,或者在AndroidManifest.xml配置文件的application标签或者activity标签中显式指定相同的process属性值,这样,不同的应用程序也可以在同一个进程中启动。

函数最终执行ActivityManagerService.startProcessLocked函数进行下一步操作。

Step 23. ActivityManagerService.startProcessLocked

这个函数定义在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. }

    这里再次检查是否已经有以process + uid命名的进程存在,在我们这个情景中,返回值app为null,因此,后面会创建一个ProcessRecord,并存保存在成员变量mProcessNames中,最后,调用另一个startProcessLocked函数进一步操作:

  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. }

    这里主要是调用Process.start接口来创建一个新的进程,新的进程会导入android.app.ActivityThread类,并且执行它的main函数,这就是为什么我们前面说每一个应用程序都有一个ActivityThread实例来对应的原因。

    Step 24. ActivityThread.main

    这个函数定义在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. }

    这个函数在进程中创建一个ActivityThread实例,然后调用它的attach函数,接着就进入消息循环了,直到最后进程退出。

    函数attach最终调用了ActivityManagerService的远程接口ActivityManagerProxy的attachApplication函数,传入的参数是mAppThread,这是一个ApplicationThread类型的Binder对象,它的作用是用来进行进程间通信的。

    Step 25. ActivityManagerProxy.attachApplication

    这个函数定义在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驱动程序,最后进入ActivityManagerService的attachApplication函数中。

    Step 26. ActivityManagerService.attachApplication

    这个函数定义在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. }

    这里将操作转发给attachApplicationLocked函数。

    Step 27. ActivityManagerService.attachApplicationLocked

    这个函数定义在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中,已经创建了一个ProcessRecord,这里首先通过pid将它取回来,放在app变量中,然后对app的其它成员进行初始化,最后调用mMainStack.realStartActivityLocked执行真正的Activity启动操作。这里要启动的Activity通过调用mMainStack.topRunningActivityLocked(null)从堆栈顶端取回来,这时候在堆栈顶端的Activity就是MainActivity了。

    Step 28. ActivityStack.realStartActivityLocked

    这个函数定义在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进入到ApplicationThreadProxy的scheduleLaunchActivity函数中,注意,这里的第二个参数r,是一个ActivityRecord类型的Binder对象,用来作来这个Activity的token值。

    Step 29. ApplicationThreadProxy.scheduleLaunchActivity
    这个函数定义在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. }

    这个函数最终通过Binder驱动程序进入到ApplicationThread的scheduleLaunchActivity函数中。

    Step 30. ApplicationThread.scheduleLaunchActivity
    这个函数定义在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. }

    函数首先创建一个ActivityClientRecord实例,并且初始化它的成员变量,然后调用ActivityThread类的queueOrSendMessage函数进一步处理。
    
    Step 31. ActivityThread.queueOrSendMessage
    这个函数定义在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. }

    函数把消息内容放在msg中,然后通过mH把消息分发出去,这里的成员变量mH我们在前面已经见过,消息分发出去后,最后会调用H类的handleMessage函数。

    Step 32. H.handleMessage

    这个函数定义在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. }

    这里最后调用ActivityThread类的handleLaunchActivity函数进一步处理。

    Step 33. ActivityThread.handleLaunchActivity

    这个函数定义在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. }

    这里首先调用performLaunchActivity函数来加载这个Activity类,即shy.luo.activity.MainActivity,然后调用它的onCreate函数,最后回到handleLaunchActivity函数时,再调用handleResumeActivity函数来使这个Activity进入Resumed状态,即会调用这个Activity的onResume函数,这是遵循Activity的生命周期的。

    Step 34. ActivityThread.performLaunchActivity
    这个函数定义在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. }

    函数前面是收集要启动的Activity的相关信息,主要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类加载进来:

  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. }

接下来是创建Application对象,这是根据AndroidManifest.xml配置文件中的Application标签的信息来创建的:

   Application app = r.packageInfo.makeApplication(false, mInstrumentation);
  后面的代码主要创建Activity的上下文信息,并通过attach方法将这些上下文信息设置到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);

最后还要调用MainActivity的onCreate函数:

   mInstrumentation.callActivityOnCreate(activity, r.state);
  这里不是直接调用MainActivity的onCreate函数,而是通过mInstrumentation的callActivityOnCreate函数来间接调用,前面我们说过,mInstrumentation在这里的作用是监控Activity与系统的交互操作,相当于是系统运行日志。

  Step 35\. MainActivity.onCreate

  这个函数定义在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就启动起来了,整个应用程序也启动起来了。

    整个应用程序的启动过程要执行很多步骤,但是整体来看,主要分为以下五个阶段:

    一. Step1 - Step 11:Launcher通过Binder进程间通信机制通知ActivityManagerService,它要启动一个Activity;

    二. Step 12 - Step 16:ActivityManagerService通过Binder进程间通信机制通知Launcher进入Paused状态;

    三. Step 17 - Step 24:Launcher通过Binder进程间通信机制通知ActivityManagerService,它已经准备就绪进入Paused状态,于是ActivityManagerService就创建一个新的进程,用来启动一个ActivityThread实例,即将要启动的Activity就是在这个ActivityThread实例中运行;

    四. Step 25 - Step 27:ActivityThread通过Binder进程间通信机制将一个ApplicationThread类型的Binder对象传递给ActivityManagerService,以便以后ActivityManagerService能够通过这个Binder对象和它进行通信;

    五. Step 28 - Step 35:ActivityManagerService通过Binder进程间通信机制通知ActivityThread,现在一切准备就绪,它可以真正执行Activity的启动操作了。

    这里不少地方涉及到了Binder进程间通信机制,相关资料请参考Android进程间通信(IPC)机制Binder简要介绍和学习计划一文。

    这样,应用程序的启动过程就介绍完了,它实质上是启动应用程序的默认Activity。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容