当前位置:   article > 正文

Android程序入口ActivityThread和Android应用程序启动流程详解_update_package_compatibility_info

update_package_compatibility_info

          大家初学java时候都知道java的程序入口是从main方法进入,那么Android是基于java编写的,那Android的程序入口做了哪些操作呢?还有Android的应用程序到底是怎样启动的呢?我们一起来看一下.

首先附上ActivityThread.java的main方法:

  1. public static void main(String[] args) {
  2. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
  3. SamplingProfilerIntegration.start();
  4. // CloseGuard defaults to true and can be quite spammy. We
  5. // disable it here, but selectively enable it later (via
  6. // StrictMode) on debug builds, but using DropBox, not logs.
  7. CloseGuard.setEnabled(false);
  8. Environment.initForCurrentUser();
  9. // Set the reporter for event logging in libcore
  10. EventLogger.setReporter(new EventLoggingReporter());
  11. AndroidKeyStoreProvider.install();
  12. // Make sure TrustedCertificateStore looks in the right place for CA certificates
  13. final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
  14. TrustedCertificateStore.setDefaultUserDirectory(configDir);
  15. Process.setArgV0("<pre-initialized>");
  16. Looper.prepareMainLooper(); //实例化Looper并设置到ThreadLocal里面,赋值MainLooper
  17. ActivityThread thread = new ActivityThread(); //实例化一个ActivityThread
  18. thread.attach(false); //主要是获取AMS接口 然后设置ApplicationThread 的接口 给AMS和应用程序通信
  19. if (sMainThreadHandler == null) {
  20. sMainThreadHandler = thread.getHandler(); //设置MainHandler 是一些接受生命周期的方法
  21. }
  22. if (false) {
  23. Looper.myLooper().setMessageLogging(new
  24. LogPrinter(Log.DEBUG, "ActivityThread"));
  25. }
  26. // End of event ActivityThreadMain.
  27. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  28. Looper.loop(); //开始接收消息
  29. throw new RuntimeException("Main thread loop unexpectedly exited");
  30. }

首先我们看第23行:

Looper.prepareMainLooper();

做Android的都知道Looper是handler机制的一个组件

(那么这里就延伸了一个问题,子线程里面能不能创建Handler呢?答案是可以的,但是必须要创建Looper,那么就有人问了,为什么主线程里面不用创建呢?看了Android的代码以后知道了,原来Android已经默默的给创建好了,Android的组件的生命周期也都是由Handler来调用的,下面就会看到)

那么我们来看一下prepareMainLooper()都做了一些什么事情:

  1. public static void prepareMainLooper() {
  2. prepare(false);
  3. synchronized (Looper.class) {
  4. if (sMainLooper != null) {
  5. throw new IllegalStateException("The main Looper has already been prepared.");
  6. }
  7. sMainLooper = myLooper();
  8. }
  9. }
  1. private static void prepare(boolean quitAllowed) {
  2. if (sThreadLocal.get() != null) {
  3. throw new RuntimeException("Only one Looper may be created per thread");
  4. }
  5. sThreadLocal.set(new Looper(quitAllowed));
  6. }
  1. /**
  2. * Return the Looper object associated with the current thread. Returns
  3. * null if the calling thread is not associated with a Looper.
  4. */
  5. public static @Nullable Looper myLooper() {
  6. return sThreadLocal.get();
  7. }

  1. private Looper(boolean quitAllowed) {
  2. mQueue = new MessageQueue(quitAllowed);
  3. mThread = Thread.currentThread();
  4. }


好大家看进入了prepareMainLooper以后首先调用了prepare方法,在prepare方法里面判断了sThreadLocal!=null以后才往下走,这就解释了一个线程只能有一个Looper,实例化了一个Looper并设置给sThreadLocal,那么看到Looper的构造方法里面创建了MessageQueue一个消息队列和获取当前的线程Thread并赋值.

然后在prepareMainLooper下面又执行了一句代码把刚才创建的Looper赋值给sMainLooper.

(这个sMainLooper就是主线程的Looper也就是UI线程的Looper,在开发Android应用时有时也会获取它和当前线程的Looper比较,可以知道当前是不是在主线程....额...有点跑题了)

那么这段代码就结束了,我们继续往下看.

第25行实例化了ActivityThread对象:

第26行调用了AcitivityThread对象的attach方法,那么来看一下究竟做了什么:

  1. private void attach(boolean system) {
  2. sCurrentActivityThread = this;
  3. mSystemThread = system;
  4. if (!system) {
  5. ViewRootImpl.addFirstDrawHandler(new Runnable() {
  6. @Override
  7. public void run() {
  8. ensureJitEnabled();
  9. }
  10. });
  11. android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
  12. UserHandle.myUserId());
  13. RuntimeInit.setApplicationObject(mAppThread.asBinder());
  14. final IActivityManager mgr = ActivityManagerNative.getDefault();
  15. try {
  16. mgr.attachApplication(mAppThread);
  17. } catch (RemoteException ex) {
  18. // Ignore
  19. }
  20. // Watch for getting close to heap limit.
  21. BinderInternal.addGcWatcher(new Runnable() {
  22. @Override public void run() {
  23. if (!mSomeActivitiesChanged) {
  24. return;
  25. }
  26. Runtime runtime = Runtime.getRuntime();
  27. long dalvikMax = runtime.maxMemory();
  28. long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
  29. if (dalvikUsed > ((3*dalvikMax)/4)) {
  30. if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
  31. + " total=" + (runtime.totalMemory()/1024)
  32. + " used=" + (dalvikUsed/1024));
  33. mSomeActivitiesChanged = false;
  34. try {
  35. mgr.releaseSomeActivities(mAppThread);
  36. } catch (RemoteException e) {
  37. }
  38. }
  39. }
  40. });
  41. } else {
  42. // Don't set application object here -- if the system crashes,
  43. // we can't display an alert, we just want to die die die.
  44. android.ddm.DdmHandleAppName.setAppName("system_process",
  45. UserHandle.myUserId());
  46. try {
  47. mInstrumentation = new Instrumentation();
  48. ContextImpl context = ContextImpl.createAppContext(
  49. this, getSystemContext().mPackageInfo);
  50. mInitialApplication = context.mPackageInfo.makeApplication(true, null);
  51. mInitialApplication.onCreate();
  52. } catch (Exception e) {
  53. throw new RuntimeException(
  54. "Unable to instantiate Application():" + e.toString(), e);
  55. }
  56. }
  57. // add dropbox logging to libcore
  58. DropBox.setReporter(new DropBoxReporter());
  59. ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
  60. @Override
  61. public void onConfigurationChanged(Configuration newConfig) {
  62. synchronized (mResourcesManager) {
  63. // We need to apply this change to the resources
  64. // immediately, because upon returning the view
  65. // hierarchy will be informed about it.
  66. if (mResourcesManager.applyConfigurationToResourcesLocked(newConfig, null)) {
  67. // This actually changed the resources! Tell
  68. // everyone about it.
  69. if (mPendingConfiguration == null ||
  70. mPendingConfiguration.isOtherSeqNewer(newConfig)) {
  71. mPendingConfiguration = newConfig;
  72. sendMessage(H.CONFIGURATION_CHANGED, newConfig);
  73. }
  74. }
  75. }
  76. }
  77. @Override
  78. public void onLowMemory() {
  79. }
  80. @Override
  81. public void onTrimMemory(int level) {
  82. }
  83. });
  84. }
调用的时候参数传递false说明不是系统调用的,那么我们就看if语句块里面的,主要就看14行和16行的代码:

 final IActivityManager mgr = ActivityManagerNative.getDefault();        
 mgr.attachApplication(mAppThread);

那么这两句代码首先Android系统中存在一个ActivityManagerService(简称AMS)(大白话就叫Activity管理服务),他是来调度Android程序里面的Activity的开启等工作.

那么ActivityManagerNative.getDefault()就是获取了这个ActivityManagerService的Binder接口(Binder:跨进程通信),然后调用了attachApplication传入了一个mAppThread.

那么这个mAppThread是什么呢?

它是ApplicationThread在全局声明并初始化,这个东西也是一个继承了Binder的类,把他传递给AMS,以后AMS就拿这个东西和应用程序进行通信.
            

然后再回到ActivityThread的代码中,设置了一个sMainThreadHandler,这个thread.getHandler()方法返回了一个名为H的继承自Handler的一个类:

  1. private class H extends Handler {
  2. public static final int LAUNCH_ACTIVITY = 100;
  3. public static final int PAUSE_ACTIVITY = 101;
  4. public static final int PAUSE_ACTIVITY_FINISHING= 102;
  5. public static final int STOP_ACTIVITY_SHOW = 103;
  6. public static final int STOP_ACTIVITY_HIDE = 104;
  7. public static final int SHOW_WINDOW = 105;
  8. public static final int HIDE_WINDOW = 106;
  9. public static final int RESUME_ACTIVITY = 107;
  10. public static final int SEND_RESULT = 108;
  11. public static final int DESTROY_ACTIVITY = 109;
  12. public static final int BIND_APPLICATION = 110;
  13. public static final int EXIT_APPLICATION = 111;
  14. public static final int NEW_INTENT = 112;
  15. public static final int RECEIVER = 113;
  16. public static final int CREATE_SERVICE = 114;
  17. public static final int SERVICE_ARGS = 115;
  18. public static final int STOP_SERVICE = 116;
  19. public static final int CONFIGURATION_CHANGED = 118;
  20. public static final int CLEAN_UP_CONTEXT = 119;
  21. public static final int GC_WHEN_IDLE = 120;
  22. public static final int BIND_SERVICE = 121;
  23. public static final int UNBIND_SERVICE = 122;
  24. public static final int DUMP_SERVICE = 123;
  25. public static final int LOW_MEMORY = 124;
  26. public static final int ACTIVITY_CONFIGURATION_CHANGED = 125;
  27. public static final int RELAUNCH_ACTIVITY = 126;
  28. public static final int PROFILER_CONTROL = 127;
  29. public static final int CREATE_BACKUP_AGENT = 128;
  30. public static final int DESTROY_BACKUP_AGENT = 129;
  31. public static final int SUICIDE = 130;
  32. public static final int REMOVE_PROVIDER = 131;
  33. public static final int ENABLE_JIT = 132;
  34. public static final int DISPATCH_PACKAGE_BROADCAST = 133;
  35. public static final int SCHEDULE_CRASH = 134;
  36. public static final int DUMP_HEAP = 135;
  37. public static final int DUMP_ACTIVITY = 136;
  38. public static final int SLEEPING = 137;
  39. public static final int SET_CORE_SETTINGS = 138;
  40. public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
  41. public static final int TRIM_MEMORY = 140;
  42. public static final int DUMP_PROVIDER = 141;
  43. public static final int UNSTABLE_PROVIDER_DIED = 142;
  44. public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
  45. public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
  46. public static final int INSTALL_PROVIDER = 145;
  47. public static final int ON_NEW_ACTIVITY_OPTIONS = 146;
  48. public static final int CANCEL_VISIBLE_BEHIND = 147;
  49. public static final int BACKGROUND_VISIBLE_BEHIND_CHANGED = 148;
  50. public static final int ENTER_ANIMATION_COMPLETE = 149;
  51. String codeToString(int code) {
  52. if (DEBUG_MESSAGES) {
  53. switch (code) {
  54. case LAUNCH_ACTIVITY: return "LAUNCH_ACTIVITY";
  55. case PAUSE_ACTIVITY: return "PAUSE_ACTIVITY";
  56. case PAUSE_ACTIVITY_FINISHING: return "PAUSE_ACTIVITY_FINISHING";
  57. case STOP_ACTIVITY_SHOW: return "STOP_ACTIVITY_SHOW";
  58. case STOP_ACTIVITY_HIDE: return "STOP_ACTIVITY_HIDE";
  59. case SHOW_WINDOW: return "SHOW_WINDOW";
  60. case HIDE_WINDOW: return "HIDE_WINDOW";
  61. case RESUME_ACTIVITY: return "RESUME_ACTIVITY";
  62. case SEND_RESULT: return "SEND_RESULT";
  63. case DESTROY_ACTIVITY: return "DESTROY_ACTIVITY";
  64. case BIND_APPLICATION: return "BIND_APPLICATION";
  65. case EXIT_APPLICATION: return "EXIT_APPLICATION";
  66. case NEW_INTENT: return "NEW_INTENT";
  67. case RECEIVER: return "RECEIVER";
  68. case CREATE_SERVICE: return "CREATE_SERVICE";
  69. case SERVICE_ARGS: return "SERVICE_ARGS";
  70. case STOP_SERVICE: return "STOP_SERVICE";
  71. case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
  72. case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
  73. case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
  74. case BIND_SERVICE: return "BIND_SERVICE";
  75. case UNBIND_SERVICE: return "UNBIND_SERVICE";
  76. case DUMP_SERVICE: return "DUMP_SERVICE";
  77. case LOW_MEMORY: return "LOW_MEMORY";
  78. case ACTIVITY_CONFIGURATION_CHANGED: return "ACTIVITY_CONFIGURATION_CHANGED";
  79. case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
  80. case PROFILER_CONTROL: return "PROFILER_CONTROL";
  81. case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
  82. case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
  83. case SUICIDE: return "SUICIDE";
  84. case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
  85. case ENABLE_JIT: return "ENABLE_JIT";
  86. case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
  87. case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
  88. case DUMP_HEAP: return "DUMP_HEAP";
  89. case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
  90. case SLEEPING: return "SLEEPING";
  91. case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
  92. case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
  93. case TRIM_MEMORY: return "TRIM_MEMORY";
  94. case DUMP_PROVIDER: return "DUMP_PROVIDER";
  95. case UNSTABLE_PROVIDER_DIED: return "UNSTABLE_PROVIDER_DIED";
  96. case REQUEST_ASSIST_CONTEXT_EXTRAS: return "REQUEST_ASSIST_CONTEXT_EXTRAS";
  97. case TRANSLUCENT_CONVERSION_COMPLETE: return "TRANSLUCENT_CONVERSION_COMPLETE";
  98. case INSTALL_PROVIDER: return "INSTALL_PROVIDER";
  99. case ON_NEW_ACTIVITY_OPTIONS: return "ON_NEW_ACTIVITY_OPTIONS";
  100. case CANCEL_VISIBLE_BEHIND: return "CANCEL_VISIBLE_BEHIND";
  101. case BACKGROUND_VISIBLE_BEHIND_CHANGED: return "BACKGROUND_VISIBLE_BEHIND_CHANGED";
  102. case ENTER_ANIMATION_COMPLETE: return "ENTER_ANIMATION_COMPLETE";
  103. }
  104. }
  105. return Integer.toString(code);
  106. }
  107. public void handleMessage(Message msg) {
  108. if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
  109. switch (msg.what) {
  110. case LAUNCH_ACTIVITY: {
  111. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
  112. final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
  113. r.packageInfo = getPackageInfoNoCheck(
  114. r.activityInfo.applicationInfo, r.compatInfo);
  115. handleLaunchActivity(r, null);
  116. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  117. } break;
  118. case RELAUNCH_ACTIVITY: {
  119. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
  120. ActivityClientRecord r = (ActivityClientRecord)msg.obj;
  121. handleRelaunchActivity(r);
  122. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  123. } break;
  124. case PAUSE_ACTIVITY:
  125. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
  126. handlePauseActivity((IBinder)msg.obj, false, (msg.arg1&1) != 0, msg.arg2,
  127. (msg.arg1&2) != 0);
  128. maybeSnapshot();
  129. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  130. break;
  131. case PAUSE_ACTIVITY_FINISHING:
  132. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
  133. handlePauseActivity((IBinder)msg.obj, true, (msg.arg1&1) != 0, msg.arg2,
  134. (msg.arg1&1) != 0);
  135. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  136. break;
  137. case STOP_ACTIVITY_SHOW:
  138. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStop");
  139. handleStopActivity((IBinder)msg.obj, true, msg.arg2);
  140. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  141. break;
  142. case STOP_ACTIVITY_HIDE:
  143. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStop");
  144. handleStopActivity((IBinder)msg.obj, false, msg.arg2);
  145. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  146. break;
  147. case SHOW_WINDOW:
  148. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityShowWindow");
  149. handleWindowVisibility((IBinder)msg.obj, true);
  150. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  151. break;
  152. case HIDE_WINDOW:
  153. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityHideWindow");
  154. handleWindowVisibility((IBinder)msg.obj, false);
  155. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  156. break;
  157. case RESUME_ACTIVITY:
  158. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
  159. handleResumeActivity((IBinder) msg.obj, true, msg.arg1 != 0, true);
  160. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  161. break;
  162. case SEND_RESULT:
  163. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityDeliverResult");
  164. handleSendResult((ResultData)msg.obj);
  165. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  166. break;
  167. case DESTROY_ACTIVITY:
  168. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityDestroy");
  169. handleDestroyActivity((IBinder)msg.obj, msg.arg1 != 0,
  170. msg.arg2, false);
  171. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  172. break;
  173. case BIND_APPLICATION:
  174. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
  175. AppBindData data = (AppBindData)msg.obj;
  176. handleBindApplication(data);
  177. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  178. break;
  179. case EXIT_APPLICATION:
  180. if (mInitialApplication != null) {
  181. mInitialApplication.onTerminate();
  182. }
  183. Looper.myLooper().quit();
  184. break;
  185. case NEW_INTENT:
  186. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityNewIntent");
  187. handleNewIntent((NewIntentData)msg.obj);
  188. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  189. break;
  190. case RECEIVER:
  191. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveComp");
  192. handleReceiver((ReceiverData)msg.obj);
  193. maybeSnapshot();
  194. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  195. break;
  196. case CREATE_SERVICE:
  197. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceCreate");
  198. handleCreateService((CreateServiceData)msg.obj);
  199. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  200. break;
  201. case BIND_SERVICE:
  202. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
  203. handleBindService((BindServiceData)msg.obj);
  204. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  205. break;
  206. case UNBIND_SERVICE:
  207. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceUnbind");
  208. handleUnbindService((BindServiceData)msg.obj);
  209. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  210. break;
  211. case SERVICE_ARGS:
  212. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStart");
  213. handleServiceArgs((ServiceArgsData)msg.obj);
  214. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  215. break;
  216. case STOP_SERVICE:
  217. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
  218. handleStopService((IBinder)msg.obj);
  219. maybeSnapshot();
  220. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  221. break;
  222. case CONFIGURATION_CHANGED:
  223. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "configChanged");
  224. mCurDefaultDisplayDpi = ((Configuration)msg.obj).densityDpi;
  225. handleConfigurationChanged((Configuration)msg.obj, null);
  226. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  227. break;
  228. case CLEAN_UP_CONTEXT:
  229. ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
  230. cci.context.performFinalCleanup(cci.who, cci.what);
  231. break;
  232. case GC_WHEN_IDLE:
  233. scheduleGcIdler();
  234. break;
  235. case DUMP_SERVICE:
  236. handleDumpService((DumpComponentInfo)msg.obj);
  237. break;
  238. case LOW_MEMORY:
  239. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "lowMemory");
  240. handleLowMemory();
  241. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  242. break;
  243. case ACTIVITY_CONFIGURATION_CHANGED:
  244. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityConfigChanged");
  245. handleActivityConfigurationChanged((ActivityConfigChangeData)msg.obj);
  246. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  247. break;
  248. case PROFILER_CONTROL:
  249. handleProfilerControl(msg.arg1 != 0, (ProfilerInfo)msg.obj, msg.arg2);
  250. break;
  251. case CREATE_BACKUP_AGENT:
  252. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupCreateAgent");
  253. handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
  254. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  255. break;
  256. case DESTROY_BACKUP_AGENT:
  257. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupDestroyAgent");
  258. handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
  259. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  260. break;
  261. case SUICIDE:
  262. Process.killProcess(Process.myPid());
  263. break;
  264. case REMOVE_PROVIDER:
  265. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "providerRemove");
  266. completeRemoveProvider((ProviderRefCount)msg.obj);
  267. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  268. break;
  269. case ENABLE_JIT:
  270. ensureJitEnabled();
  271. break;
  272. case DISPATCH_PACKAGE_BROADCAST:
  273. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastPackage");
  274. handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
  275. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  276. break;
  277. case SCHEDULE_CRASH:
  278. throw new RemoteServiceException((String)msg.obj);
  279. case DUMP_HEAP:
  280. handleDumpHeap(msg.arg1 != 0, (DumpHeapData)msg.obj);
  281. break;
  282. case DUMP_ACTIVITY:
  283. handleDumpActivity((DumpComponentInfo)msg.obj);
  284. break;
  285. case DUMP_PROVIDER:
  286. handleDumpProvider((DumpComponentInfo)msg.obj);
  287. break;
  288. case SLEEPING:
  289. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "sleeping");
  290. handleSleeping((IBinder)msg.obj, msg.arg1 != 0);
  291. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  292. break;
  293. case SET_CORE_SETTINGS:
  294. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setCoreSettings");
  295. handleSetCoreSettings((Bundle) msg.obj);
  296. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  297. break;
  298. case UPDATE_PACKAGE_COMPATIBILITY_INFO:
  299. handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
  300. break;
  301. case TRIM_MEMORY:
  302. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "trimMemory");
  303. handleTrimMemory(msg.arg1);
  304. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  305. break;
  306. case UNSTABLE_PROVIDER_DIED:
  307. handleUnstableProviderDied((IBinder)msg.obj, false);
  308. break;
  309. case REQUEST_ASSIST_CONTEXT_EXTRAS:
  310. handleRequestAssistContextExtras((RequestAssistContextExtras)msg.obj);
  311. break;
  312. case TRANSLUCENT_CONVERSION_COMPLETE:
  313. handleTranslucentConversionComplete((IBinder)msg.obj, msg.arg1 == 1);
  314. break;
  315. case INSTALL_PROVIDER:
  316. handleInstallProvider((ProviderInfo) msg.obj);
  317. break;
  318. case ON_NEW_ACTIVITY_OPTIONS:
  319. Pair<IBinder, ActivityOptions> pair = (Pair<IBinder, ActivityOptions>) msg.obj;
  320. onNewActivityOptions(pair.first, pair.second);
  321. break;
  322. case CANCEL_VISIBLE_BEHIND:
  323. handleCancelVisibleBehind((IBinder) msg.obj);
  324. break;
  325. case BACKGROUND_VISIBLE_BEHIND_CHANGED:
  326. handleOnBackgroundVisibleBehindChanged((IBinder) msg.obj, msg.arg1 > 0);
  327. break;
  328. case ENTER_ANIMATION_COMPLETE:
  329. handleEnterAnimationComplete((IBinder) msg.obj);
  330. break;
  331. }
  332. if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
  333. }
  334. private void maybeSnapshot() {
  335. if (mBoundApplication != null && SamplingProfilerIntegration.isEnabled()) {
  336. // convert the *private* ActivityThread.PackageInfo to *public* known
  337. // android.content.pm.PackageInfo
  338. String packageName = mBoundApplication.info.mPackageName;
  339. android.content.pm.PackageInfo packageInfo = null;
  340. try {
  341. Context context = getSystemContext();
  342. if(context == null) {
  343. Log.e(TAG, "cannot get a valid context");
  344. return;
  345. }
  346. PackageManager pm = context.getPackageManager();
  347. if(pm == null) {
  348. Log.e(TAG, "cannot get a valid PackageManager");
  349. return;
  350. }
  351. packageInfo = pm.getPackageInfo(
  352. packageName, PackageManager.GET_ACTIVITIES);
  353. } catch (NameNotFoundException e) {
  354. Log.e(TAG, "cannot get package info for " + packageName, e);
  355. }
  356. SamplingProfilerIntegration.writeSnapshot(mBoundApplication.processName, packageInfo);
  357. }
  358. }
  359. }
看着是不是很亲切,有PAUSE_ACTIVITY、STOP_ACTIVITY、BIND_SERVICE等,就看到了组件的声明周期都是通过这去发起的.

最后ActivityThread第39行,调用Looper.loop()方法开始循环获取Message.

完事了? 没了?  怎么可能.... 记不记得咱们给AMS设置了一个ApplicationThread,设置了以后AMS就说了,行了可以.

当AMS看我能调用到你了,好,你可以干你的事了,那么它会通过ApplicationThread告诉你,那么来看一下ApplicationThread的类:

  1. private class ApplicationThread extends ApplicationThreadNative {
  2. private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
  3. private int mLastProcessState = -1;
  4. private void updatePendingConfiguration(Configuration config) {
  5. synchronized (mResourcesManager) {
  6. if (mPendingConfiguration == null ||
  7. mPendingConfiguration.isOtherSeqNewer(config)) {
  8. mPendingConfiguration = config;
  9. }
  10. }
  11. }
  12. public final void schedulePauseActivity(IBinder token, boolean finished,
  13. boolean userLeaving, int configChanges, boolean dontReport) {
  14. sendMessage(
  15. finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
  16. token,
  17. (userLeaving ? 1 : 0) | (dontReport ? 2 : 0),
  18. configChanges);
  19. }
  20. public final void scheduleStopActivity(IBinder token, boolean showWindow,
  21. int configChanges) {
  22. sendMessage(
  23. showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
  24. token, 0, configChanges);
  25. }
  26. public final void scheduleWindowVisibility(IBinder token, boolean showWindow) {
  27. sendMessage(
  28. showWindow ? H.SHOW_WINDOW : H.HIDE_WINDOW,
  29. token);
  30. }
  31. public final void scheduleSleeping(IBinder token, boolean sleeping) {
  32. sendMessage(H.SLEEPING, token, sleeping ? 1 : 0);
  33. }
  34. public final void scheduleResumeActivity(IBinder token, int processState,
  35. boolean isForward, Bundle resumeArgs) {
  36. updateProcessState(processState, false);
  37. sendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0);
  38. }
  39. public final void scheduleSendResult(IBinder token, List<ResultInfo> results) {
  40. ResultData res = new ResultData();
  41. res.token = token;
  42. res.results = results;
  43. sendMessage(H.SEND_RESULT, res);
  44. }
  45. // we use token to identify this activity without having to send the
  46. // activity itself back to the activity manager. (matters more with ipc)
  47. @Override
  48. public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
  49. ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
  50. CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
  51. int procState, Bundle state, PersistableBundle persistentState,
  52. List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
  53. boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
  54. updateProcessState(procState, false);
  55. ActivityClientRecord r = new ActivityClientRecord();
  56. r.token = token;
  57. r.ident = ident;
  58. r.intent = intent;
  59. r.referrer = referrer;
  60. r.voiceInteractor = voiceInteractor;
  61. r.activityInfo = info;
  62. r.compatInfo = compatInfo;
  63. r.state = state;
  64. r.persistentState = persistentState;
  65. r.pendingResults = pendingResults;
  66. r.pendingIntents = pendingNewIntents;
  67. r.startsNotResumed = notResumed;
  68. r.isForward = isForward;
  69. r.profilerInfo = profilerInfo;
  70. r.overrideConfig = overrideConfig;
  71. updatePendingConfiguration(curConfig);
  72. sendMessage(H.LAUNCH_ACTIVITY, r);
  73. }
  74. @Override
  75. public final void scheduleRelaunchActivity(IBinder token,
  76. List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
  77. int configChanges, boolean notResumed, Configuration config,
  78. Configuration overrideConfig) {
  79. requestRelaunchActivity(token, pendingResults, pendingNewIntents,
  80. configChanges, notResumed, config, overrideConfig, true);
  81. }
  82. public final void scheduleNewIntent(List<ReferrerIntent> intents, IBinder token) {
  83. NewIntentData data = new NewIntentData();
  84. data.intents = intents;
  85. data.token = token;
  86. sendMessage(H.NEW_INTENT, data);
  87. }
  88. public final void scheduleDestroyActivity(IBinder token, boolean finishing,
  89. int configChanges) {
  90. sendMessage(H.DESTROY_ACTIVITY, token, finishing ? 1 : 0,
  91. configChanges);
  92. }
那么这里贴出了ApplicationThread的部分代码,这个类很多,都是一些创建组件啊,和组件的暂停,销毁的一些声明周期,通过Binder机制调用了以后,在方法里面调用sendMessage()方法,最后会走到刚才H类的handleMessage方法做处理.

那么主要看一下scheduleLaunchActivity,从AMS传递过来一堆参数,都是Activity的一些信息,把他们都封装到了ActivityClientRecord对象里,然后调用sendMessage方法最终调用到handleMessage里面.

那么看H类的handleMessage的switch语句,第一个就是LAUNCH_ACTIVITY那么看一下handleLaunchActivity把ActivityClientRecord传递进去,看一下代码:

  1. private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
  2. // If we are getting ready to gc after going to the background, well
  3. // we are back active so skip it.
  4. unscheduleGcIdler();
  5. mSomeActivitiesChanged = true;
  6. if (r.profilerInfo != null) {
  7. mProfiler.setProfiler(r.profilerInfo);
  8. mProfiler.startProfiling();
  9. }
  10. // Make sure we are running with the most recent config.
  11. handleConfigurationChanged(null, null);
  12. if (localLOGV) Slog.v(
  13. TAG, "Handling launch of " + r);
  14. // Initialize before creating the activity
  15. WindowManagerGlobal.initialize(); //创建Activity之前初始化全局窗口管理者
  16. Activity a = performLaunchActivity(r, customIntent); //获得一个Activity对象
  17. if (a != null) {
  18. r.createdConfig = new Configuration(mConfiguration);
  19. Bundle oldState = r.state;
  20. handleResumeActivity(r.token, false, r.isForward,
  21. !r.activity.mFinished && !r.startsNotResumed);
  22. if (!r.activity.mFinished && r.startsNotResumed) {
  23. // The activity manager actually wants this one to start out
  24. // paused, because it needs to be visible but isn't in the
  25. // foreground. We accomplish this by going through the
  26. // normal startup (because activities expect to go through
  27. // onResume() the first time they run, before their window
  28. // is displayed), and then pausing it. However, in this case
  29. // we do -not- need to do the full pause cycle (of freezing
  30. // and such) because the activity manager assumes it can just
  31. // retain the current state it has.
  32. try {
  33. r.activity.mCalled = false;
  34. mInstrumentation.callActivityOnPause(r.activity);
  35. // We need to keep around the original state, in case
  36. // we need to be created again. But we only do this
  37. // for pre-Honeycomb apps, which always save their state
  38. // when pausing, so we can not have them save their state
  39. // when restarting from a paused state. For HC and later,
  40. // we want to (and can) let the state be saved as the normal
  41. // part of stopping the activity.
  42. if (r.isPreHoneycomb()) {
  43. r.state = oldState;
  44. }
  45. if (!r.activity.mCalled) {
  46. throw new SuperNotCalledException(
  47. "Activity " + r.intent.getComponent().toShortString() +
  48. " did not call through to super.onPause()");
  49. }
  50. } catch (SuperNotCalledException e) {
  51. throw e;
  52. } catch (Exception e) {
  53. if (!mInstrumentation.onException(r.activity, e)) {
  54. throw new RuntimeException(
  55. "Unable to pause activity "
  56. + r.intent.getComponent().toShortString()
  57. + ": " + e.toString(), e);
  58. }
  59. }
  60. r.paused = true;
  61. }
  62. } else {
  63. // If there was an error, for any reason, tell the activity
  64. // manager to stop us.
  65. try {
  66. ActivityManagerNative.getDefault()
  67. .finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
  68. } catch (RemoteException ex) {
  69. // Ignore
  70. }
  71. }
  72. }
那么主要看一下performLaunchActivity把Activity信息传递进去获取了一个Activity对象,那么下面直接就调用resume了,那么也就是说在performLaunchActivity里面已经调用了onCreate和onStart了,看一下代码:

  1. private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
  2. // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
  3. ActivityInfo aInfo = r.activityInfo; //Activity的信息,启动模式Theme 烂七八糟的
  4. if (r.packageInfo == null) {
  5. r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
  6. Context.CONTEXT_INCLUDE_CODE);
  7. }
  8. ComponentName component = r.intent.getComponent(); //应该就是完整的包名+类名
  9. if (component == null) {
  10. component = r.intent.resolveActivity(
  11. mInitialApplication.getPackageManager());
  12. r.intent.setComponent(component);
  13. }
  14. if (r.activityInfo.targetActivity != null) {
  15. component = new ComponentName(r.activityInfo.packageName,
  16. r.activityInfo.targetActivity);
  17. }
  18. Activity activity = null;
  19. try {
  20. java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
  21. activity = mInstrumentation.newActivity(
  22. cl, component.getClassName(), r.intent); //ClassLoader加载Activity类
  23. StrictMode.incrementExpectedActivityCount(activity.getClass());
  24. r.intent.setExtrasClassLoader(cl);
  25. r.intent.prepareToEnterProcess();
  26. if (r.state != null) {
  27. r.state.setClassLoader(cl);
  28. }
  29. } catch (Exception e) {
  30. if (!mInstrumentation.onException(activity, e)) {
  31. throw new RuntimeException(
  32. "Unable to instantiate activity " + component
  33. + ": " + e.toString(), e);
  34. }
  35. }
  36. try {
  37. Application app = r.packageInfo.makeApplication(false, mInstrumentation); //搞到Application
  38. if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
  39. if (localLOGV) Slog.v(
  40. TAG, r + ": app=" + app
  41. + ", appName=" + app.getPackageName()
  42. + ", pkg=" + r.packageInfo.getPackageName()
  43. + ", comp=" + r.intent.getComponent().toShortString()
  44. + ", dir=" + r.packageInfo.getAppDir());
  45. if (activity != null) {
  46. Context appContext = createBaseContextForActivity(r, activity);
  47. CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager()); //Lable
  48. Configuration config = new Configuration(mCompatConfiguration);
  49. if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
  50. + r.activityInfo.name + " with config " + config);
  51. activity.attach(appContext, this, getInstrumentation(), r.token,
  52. r.ident, app, r.intent, r.activityInfo, title, r.parent,
  53. r.embeddedID, r.lastNonConfigurationInstances, config,
  54. r.referrer, r.voiceInteractor);
  55. if (customIntent != null) {
  56. activity.mIntent = customIntent;
  57. }
  58. r.lastNonConfigurationInstances = null;
  59. activity.mStartedActivity = false;
  60. int theme = r.activityInfo.getThemeResource();
  61. if (theme != 0) {
  62. activity.setTheme(theme);
  63. }
  64. activity.mCalled = false;
  65. if (r.isPersistable()) {
  66. mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
  67. } else {
  68. mInstrumentation.callActivityOnCreate(activity, r.state);
  69. }
  70. if (!activity.mCalled) {
  71. throw new SuperNotCalledException(
  72. "Activity " + r.intent.getComponent().toShortString() +
  73. " did not call through to super.onCreate()");
  74. }
  75. r.activity = activity;
  76. r.stopped = true;
  77. if (!r.activity.mFinished) {
  78. activity.performStart();
  79. r.stopped = false;
  80. }
  81. if (!r.activity.mFinished) {
  82. if (r.isPersistable()) {
  83. if (r.state != null || r.persistentState != null) {
  84. mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
  85. r.persistentState);
  86. }
  87. } else if (r.state != null) {
  88. mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
  89. }
  90. }
  91. if (!r.activity.mFinished) {
  92. activity.mCalled = false;
  93. if (r.isPersistable()) {
  94. mInstrumentation.callActivityOnPostCreate(activity, r.state,
  95. r.persistentState);
  96. } else {
  97. mInstrumentation.callActivityOnPostCreate(activity, r.state);
  98. }
  99. if (!activity.mCalled) {
  100. throw new SuperNotCalledException(
  101. "Activity " + r.intent.getComponent().toShortString() +
  102. " did not call through to super.onPostCreate()");
  103. }
  104. }
  105. }
  106. r.paused = true;
  107. mActivities.put(r.token, r);
  108. } catch (SuperNotCalledException e) {
  109. throw e;
  110. } catch (Exception e) {
  111. if (!mInstrumentation.onException(activity, e)) {
  112. throw new RuntimeException(
  113. "Unable to start activity " + component
  114. + ": " + e.toString(), e);
  115. }
  116. }
  117. return activity;
  118. }
首先呢通过ActivityClientRecord参数获取到AcitivtyInfo和组件的包名+类名,然后获取了ClassLoader类加载器,接下来使用mInstrumentation.newActivity把类加载器,包名及Intent传递进去,通过反射来获取到编写的Activity类,这样就获取到了Activity.

接下来依序获取了Context,Title之类的配置通过activity调用attach方法设置了以后,获取了Theme设置给Activity通过mInstrumentation.callActivityOnCreate()间接调用了Activity的方法,然后下面又调用了onStart方法,那么这个方法结束以后出去下面又调用了onResume(),至此Activity处于Active(活动状态).

那么最后说一下Activity的启动流程.首先呢从Launch(手机桌面),它本身就是一个应用程序.

1.点击一个图标后他会通过AMS接口告诉AMS我要开启一个应用程序,

2.然后AMS就通过ApplicationThread告诉Launch进入Pause状态,

3.然后进入了pause后会告诉AMS我已经pause了,

4.接下来AMS去创建进程啊,什么Acitivity的任务栈啊供ActivityThread运行

5.,ActivityThread通过AMS的Binder接口传递给它ApplicationThread,

6.AMS一看,好没有问题,你该干啥干啥吧,有事喊我.

那么这就是一个Android应用的启动流程了,那么至于Activity的开启过程呢,就是少了创建进程和Activity任务栈之类的,其他都差不多,都是通过AMS来管理,那么这篇文章就结束,谢谢.










声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/178134
推荐阅读
相关标签
  

闽ICP备14008679号