程序入口函数,ActivityThread的main()函数

  1. public static void main(String[] args) {
  2. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
  3. SamplingProfilerIntegration.start();
  4. CloseGuard.setEnabled(false);
  5. Environment.initForCurrentUser();
  6. EventLogger.setReporter(new EventLoggingReporter());
  7. final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
  8. TrustedCertificateStore.setDefaultUserDirectory(configDir);
  9. Process.setArgV0("<pre-initialized>");
  10. //创建Lopper
  11. Looper.prepareMainLooper();
  12. //创建ActivityThread对象
  13. ActivityThread thread = new ActivityThread();
  14. //false,首次启动,需要初始化
  15. thread.attach(false);
  16. if (sMainThreadHandler == null) {
  17. sMainThreadHandler = thread.getHandler();
  18. }
  19. if (false) {
  20. Looper.myLooper().setMessageLogging(new
  21. LogPrinter(Log.DEBUG, "ActivityThread"));
  22. }
  23. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  24. // 主线程looper,开启死循环,不断处理按键、触摸等消息,activity的生命周期也由其处理
  25. //若在activity的某个生命周期执行耗时操作,那么其他的消息无法及时执行,那么整个loop循环会卡顿
  26. //时间一长,就会触发抛出ANR
  27. Looper.loop();
  28. throw new RuntimeException("Main thread loop unexpectedly exited");

Looper.prepareMainLooper()分析

  1. public static void prepareMainLooper() {
  2. //这也解释了为什么我们在子线程中使用Handler不用创建Looper,获取它即可。
  3. //因为系统已经帮我们实现了
  4. prepare(false);
  5. synchronized (Looper.class) {
  6. if (sMainLooper != null) {
  7. throw new IllegalStateException("The main Looper has already been prepared.");
  8. }
  9. sMainLooper = myLooper();
  10. }
  11. }
  1. private void attach(boolean system) {
  2. sCurrentActivityThread = this;
  3. mSystemThread = system;
  4. //main入口传入的fasle
  5. if (!system) {
  6. //先走该分支代码
  7. //先获取ActivityManagerService对象,调用ActivityManagerService的attachApplication()
  8. final IActivityManager mgr = ActivityManagerNative.getDefault();
  9. try {
  10. // ======= 展开分析1 ========
  11. mgr.attachApplication(mAppThread);
  12. } catch (RemoteException ex) {
  13. throw ex.rethrowFromSystemServer();
  14. }
  15. //此处省略N行代码
  16. } else {
  17. try {
  18. //Instrumentation类会在应用的任何代码执行前被实列化,用来监控系统与应用的交互
  19. //另一个重要作用是提供Android组件单元测试。
  20. mInstrumentation = new Instrumentation();
  21. //应用进程conext创建 ====== 展开分析2 =======
  22. ContextImpl context = ContextImpl.createAppContext(
  23. this, getSystemContext().mPackageInfo);
  24. //创建mInitialApplication ===== 展开分析3 ========
  25. mInitialApplication = context.mPackageInfo.makeApplication(true, null);
  26. mInitialApplication.onCreate();
  27. } catch (Exception e) {
  28. throw new RuntimeException(
  29. "Unable to instantiate Application():" + e.toString(), e);
  30. }
  31. }
  32. DropBox.setReporter(new DropBoxReporter());
  33. ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
  34. @Override
  35. public void onConfigurationChanged(Configuration newConfig) {
  36. synchronized (mResourcesManager) {
  37. //立即将此更改应用于资源,因为在返回时,将查看视图层次结构。
  38. if (mResourcesManager.applyConfigurationToResourcesLocked(newConfig, null)) {
  39. updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
  40. mResourcesManager.getConfiguration().getLocales());
  41. //资源被更改,发送消息通知
  42. if (mPendingConfiguration == null ||
  43. mPendingConfiguration.isOtherSeqNewer(newConfig)) {
  44. mPendingConfiguration = newConfig;
  45. sendMessage(H.CONFIGURATION_CHANGED, newConfig);
  46. }
  47. }
  48. }
  49. }
  50. @Override
  51. public void onLowMemory() {
  52. }
  53. @Override
  54. public void onTrimMemory(int level) {
  55. }
  56. });

====展开分析1 ======

ActivityManagerNative,抽象类,一个Binder通信类
检索系统的默认/全局活动管理器。

  1. static public IActivityManager getDefault() {
  2. //这里返回的是ActivityManagerService,继承自ActivityManagerService
  3. return gDefault.get();
  4. }

最终调用ActivityManagerService内的attachAppliocation()

  1. @Override
  2. public final void attachApplication(IApplicationThread thread) {
  3. synchronized (this) {
  4. int callingPid = Binder.getCallingPid();
  5. final long origId = Binder.clearCallingIdentity();
  6. attachApplicationLocked(thread, callingPid);
  7. Binder.restoreCallingIdentity(origId);
  8. }
  9. }

进入attachAoolicationLockede()

  1. boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
  2. final String processName = app.processName;
  3. boolean didSomething = false;
  4. //遍历activity栈,找到栈顶的Activity
  5. for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
  6. ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
  7. for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
  8. final ActivityStack stack = stacks.get(stackNdx);
  9. if (!isFrontStack(stack)) {
  10. continue;
  11. }
  12. //解锁
  13. ActivityRecord hr = stack.topRunningActivityLocked(null);
  14. if (hr != null) {
  15. if (hr.app == null && app.uid == hr.info.applicationInfo.uid
  16. && processName.equals(hr.processName)) {
  17. try {
  18. //找到符合条件的Activity,真正启动Activity
  19. if (realStartActivityLocked(hr, app, true, true)) {
  20. didSomething = true;
  21. }
  22. } catch (RemoteException e) {
  23. //此处省略N行......
  24. }
  25. }
  26. }
  27. }
  28. }
  29. //此处省略N行......
  30. return didSomething;
  31. }

realStartActivityLocked内调用了ActivityThread的scheduleLaunchActivity()

  1. public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
  2. ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
  3. CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
  4. int procState, Bundle state, PersistableBundle persistentState,
  5. List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
  6. boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
  7. updateProcessState(procState, false);
  8. ActivityClientRecord r = new ActivityClientRecord();
  9. //赋值各类信息信息
  10. r.token = token;
  11. r.ident = ident;
  12. r.intent = intent;
  13. r.referrer = referrer;
  14. r.voiceInteractor = voiceInteractor;
  15. r.activityInfo = info;
  16. r.compatInfo = compatInfo;
  17. r.state = state;
  18. r.persistentState = persistentState;
  19. r.pendingResults = pendingResults;
  20. r.pendingIntents = pendingNewIntents;
  21. r.startsNotResumed = notResumed;
  22. r.isForward = isForward;
  23. r.profilerInfo = profilerInfo;
  24. r.overrideConfig = overrideConfig;
  25. updatePendingConfiguration(curConfig);
  26. //发送启动Activity的消息,使用内部继承Handelr的H,在ActivityThread创建时初始化
  27. sendMessage(H.LAUNCH_ACTIVITY, r);
  28. }

handleMessage内调用handleLaunchActivity()

  1. case LAUNCH_ACTIVITY: {
  2. Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
  3. final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
  4. r.packageInfo = getPackageInfoNoCheck(
  5. r.activityInfo.applicationInfo, r.compatInfo);
  6. handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
  7. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
  8. } break;
  1. private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
  2. unscheduleGcIdler();
  3. //此处省略N行.........
  4. //初始化WindowManagerGlobal
  5. WindowManagerGlobal.initialize();
  6. // ======== performLaunchActivity()内部 ============
  7. //1.加载Activity的class类,执行其attach()
  8. //2.调用mInstrumentation.callActivityOnCreate,最终调用Activity的onCreate()
  9. //3.调用Activity的start()方法
  10. Activity a = performLaunchActivity(r, customIntent);
  11. if (a != null) {
  12. r.createdConfig = new Configuration(mConfiguration);
  13. reportSizeConfigurations(r);
  14. Bundle oldState = r.state;
  15. // ========= handleResumeActivity()内部 ==============
  16. //1.获取window,创建DecorView对象
  17. //2.获取windowManager,将DecorView添加到wm,此时开启view的测量,布局,绘制等等
  18. //3.使Activity可见
  19. handleResumeActivity(r.token, false, r.isForward,
  20. !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
  21. if (!r.activity.mFinished && r.startsNotResumed) {
  22. performPauseActivityIfNeeded(r, reason);
  23. if (r.isPreHoneycomb()) {
  24. r.state = oldState;
  25. }
  26. }
  27. } else {
  28. try {
  29. ActivityManagerNative.getDefault()
  30. .finishActivity(r.token, Activity.RESULT_CANCELED, null,
  31. Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
  32. } catch (RemoteException ex) {
  33. throw ex.rethrowFromSystemServer();
  34. }
  35. }
  36. }

====展开分析2 ======

ContextImpl(继承自Context)的构造方法,所以返回的是Context
简要看下一源码,针对Context的分析,另开一篇文章~~

  1. static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) {
  2. if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
  3. return new ContextImpl(null, mainThread,
  4. packageInfo, null, null, 0, null, null, Display.INVALID_DISPLAY);
  5. }
  1. private ContextImpl(ContextImpl container, ActivityThread mainThread,
  2. LoadedApk packageInfo, IBinder activityToken, UserHandle user, int flags,
  3. Display display, Configuration overrideConfiguration, int createDisplayWithId) {
  4. mOuterContext = this;
  5. //如果创建者没有指定使用哪个存储,则使用默认的应用程序位置。
  6. if ((flags & (Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE
  7. | Context.CONTEXT_DEVICE_PROTECTED_STORAGE)) == 0) {
  8. //此处省略N行代码
  9. }
  10. //传入ActvityThread
  11. mMainThread = mainThread;
  12. //传入activityToken
  13. mActivityToken = activityToken;
  14. mFlags = flags;
  15. if (user == null) {
  16. user = Process.myUserHandle();
  17. }
  18. mUser = user;
  19. mPackageInfo = packageInfo;
  20. //初始化ResourcesManager实例,用以获取资源文件
  21. mResourcesManager = ResourcesManager.getInstance();
  22. ///此处省略N行代码...........
  23. }

======展开分析3 =========

LoadApk类,调用makeApplication()入参(true,null)。

  1. public Application makeApplication(boolean forceDefaultAppClass,
  2. Instrumentation instrumentation) {
  3. //此处省略N行............
  4. try {
  5. java.lang.ClassLoader cl = getClassLoader();
  6. //此处省略N行............
  7. ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
  8. //通过mInstrumentation创建Application
  9. //
  10. ======= 展开分析4 =========
  11. app = mActivityThread.mInstrumentation.newApplication(
  12. cl, appClass, appContext);
  13. appContext.setOuterContext(app);
  14. } catch (Exception e) {
  15. //此处省略N行............
  16. }
  17. mActivityThread.mAllApplications.add(app);
  18. mApplication = app;
  19. if (instrumentation != null) {
  20. try {
  21. instrumentation.callApplicationOnCreate(app);
  22. } catch (Exception e) {
  23. //此处省略N行............
  24. }
  25. //此处省略N行............
  26. return app;
  27. }

=======展开分析4=======

Instrumetation类,创建Application,调用attach(context)

  1. public Application newApplication(ClassLoader cl, String className, Context context)
  2. throws InstantiationException, IllegalAccessException,
  3. ClassNotFoundException {
  4. return newApplication(cl.loadClass(className), context);
  5. }
  1. static public Application newApplication(Class<?> clazz, Context context)
  2. throws InstantiationException, IllegalAccessException,
  3. ClassNotFoundException {
  4. Application app = (Application)clazz.newInstance();
  5. app.attach(context);
  6. return app;
  7. }