自动化零件服务商 - 供应SMC,FESTO,CKD全新正品气动元件
自动化零件服务商 - 供应SMC,FESTO,CKD全新正品气动元件
自动化零件服务商 - 供应SMC,FESTO,CKD全新正品气动元件

前言

记录一下Android开机时ACTION_USER_UNLOCKEDACTION_BOOT_COMPLETED啥时候发送的过程记录,主要是方便自己回顾。

Android P分析为例。

正文

本文跟《Android开机动画关闭源码分析》存在大量重复,这就简单过一下。

ResumeActivityItem.java

execute()
  1. @Override
  2. public void execute(ClientTransactionHandler client, IBinder token,
  3.       PendingTransactionActions pendingActions) {
  4.   // 看子类ActivityThread.java的实现
  5.   client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
  6.           "RESUME_ACTIVITY");
  7. }
复制

ActivityThread.java

handleResumeActivity()
  1. @Override
  2. public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
  3.       String reason) {
  4.   //略
  5.   //[重]就是调用onResume()
  6.   final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
  7.   if (r == null) {
  8.       return;
  9.   }
  10.   //略
  11.   r.nextIdle = mNewActivities;
  12.   mNewActivities = r;
  13.   //[重] 这个是表示onResume()进入idler状态啦
  14.   Looper.myQueue().addIdleHandler(new Idler());
  15. }
复制

performResumeActivity()不是这次的关心点,我们看addIdleHandler()。

这里添加了一个Idler对象,这部分看MessageQueue类。

反正就是MessageQueue总的next()会调用Idler对象,具体看《Android开机动画关闭源码分析

Idler
  1. private class Idler implements MessageQueue.IdleHandler {
  2.   @Override
  3.   public final boolean queueIdle() {
  4.       ActivityClientRecord a = mNewActivities;
  5.       boolean stopProfiling = false;
  6.       if (mBoundApplication != null && mProfiler.profileFd != null
  7.               && mProfiler.autoStopProfiler) {
  8.           stopProfiling = true;
  9.       }
  10.       if (a != null) {
  11.           mNewActivities = null;
  12.           //获取ActivityManagerService
  13.           IActivityManager am = ActivityManager.getService();
  14.           ActivityClientRecord prev;
  15.           do {
  16.               if (a.activity != null && !a.activity.mFinished) {
  17.                   try {
  18.                   //[重],看这里
  19.                       am.activityIdle(a.token, a.createdConfig, stopProfiling);
  20.                       a.createdConfig = null;
  21.                   } catch (RemoteException ex) {
  22.                       throw ex.rethrowFromSystemServer();
  23.                   }
  24.               }
  25.               prev = a;
  26.               a = a.nextIdle;
  27.               prev.nextIdle = null;
  28.           } while (a != null);
  29.       }
  30.       if (stopProfiling) {
  31.           mProfiler.stopProfiling();
  32.       }
  33.       ensureJitEnabled();
  34.       return false;
  35.   }
  36. }
复制

这里的am就是ActivityManagerService。

ActivityManagerService.java

activityIdle()
  1. @Override
  2. public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
  3.   final long origId = Binder.clearCallingIdentity();
  4.   synchronized (this) {
  5.       ActivityStack stack = ActivityRecord.getStackLocked(token);
  6. //不为null,
  7.       if (stack != null) {
  8.       //关注这个activityIdleInternalLocked
  9.       //mStackSupervisor是ActivityStackSupervisor对象
  10.           ActivityRecord r =
  11.                   mStackSupervisor.activityIdleInternalLocked(token, false /* fromTimeout */,
  12.                           false /* processPausingActivities */, config);
  13. //false
  14.           if (stopProfiling) {
  15.               if ((mProfileProc == r.app) && mProfilerInfo != null) {
  16.                   clearProfilerLocked();
  17.               }
  18.           }
  19.       }
  20.   }
  21.   Binder.restoreCallingIdentity(origId);
  22. }
复制

ActivityStackSupervisor.java

activityIdleInternalLocked()
  1. @GuardedBy("mService")
  2. final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
  3.       boolean processPausingActivities, Configuration config) {
  4.   ActivityRecord r = ActivityRecord.forTokenLocked(token);
  5. //略
  6. //r不为null
  7.   if (r != null) {
  8. //移除IDLE_TIMEOUT_MSG
  9.       mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
  10.       r.finishLaunchTickingLocked();
  11. //略
  12. //第一个为true,满足条件
  13. //fromTimeout为false,没有超时
  14.       if (isFocusedStack(r.getStack()) || fromTimeout) {
  15.       //true [重],这个检测是否开机成功
  16.           booting = checkFinishBootingLocked();
  17.       }
  18.   }
  19. //true
  20.   if (allResumedActivitiesIdle()) {
  21.       if (r != null) {
  22.           mService.scheduleAppGcsLocked();
  23.       }
  24.       if (mLaunchingActivity.isHeld()) {
  25. //略
  26.       }
  27. //就是遍历Activity状态啥的,不是我们关系的
  28.       ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
  29.   }
  30. //略
  31.   mService.trimApplications();
  32. //activityRemoved = false
  33.   if (activityRemoved) {
  34.       resumeFocusedStackTopActivityLocked();
  35.   }
  36.   return r;
  37. }
复制

重点关心

  1. booting = checkFinishBootingLocked();
复制
checkFinishBootingLocked()
  1. @GuardedBy("mService")
  2. private boolean checkFinishBootingLocked() {
  3.   final boolean booting = mService.mBooting;
  4.   boolean enableScreen = false;
  5.   mService.mBooting = false;
  6. //false
  7.   if (!mService.mBooted) {
  8.       mService.mBooted = true;
  9.       enableScreen = true;
  10.   }
  11. // booting = true,
  12. //enableScreen = true
  13.   if (booting || enableScreen) {
  14.   //进入这里,两个都是为true
  15.       mService.postFinishBooting(booting, enableScreen);
  16.   }
  17.   return booting;
  18. }
复制

ActivityManagerService.java

  1. void postFinishBooting(boolean finishBooting, boolean enableScreen) {
  2.   mHandler.sendMessage(mHandler.obtainMessage(FINISH_BOOTING_MSG,
  3.           finishBooting ? 1 : 0, enableScreen ? 1 : 0));
  4. }
复制

发送的消息是FINISH_BOOTING_MSG

finishBooting和enableScreen都为true,因此msg.arg1和msg.arg2都为1

handleMessage()

是在MainHandler类中

  1. final class MainHandler extends Handler {
  2. //略
  3.   @Override
  4.   public void handleMessage(Message msg) {
  5. switch (msg.what) {
  6. //略
  7. case FINISH_BOOTING_MSG: {
  8. if (msg.arg1 != 0) {//为1
  9. finishBooting();
  10. }
  11. if (msg.arg2 != 0) {//为1
  12. enableScreenAfterBoot();
  13. }
  14. break;
  15. }
  16. //略
  17. }
  18. }
  19. }
复制
finishBooting()

第一次是mBootAnimationComplete为false,进入if语句后,仅mCallFinishBooting置为true,然后return。

  1. final void finishBooting() {
  2. synchronized (this) {
  3. //mBootAnimationComplete此时为false
  4. if (!mBootAnimationComplete) {
  5. mCallFinishBooting = true;
  6. return;
  7. }
  8. mCallFinishBooting = false;
  9. }
  10. //略
  11. }
复制
enableScreenAfterBoot()
  1. void enableScreenAfterBoot() {
  2. //调用的WindowManagerService.enableScreenAfterBoot()
  3. mWindowManager.enableScreenAfterBoot();
  4. synchronized (this) {
  5. updateEventDispatchingLocked();
  6. }
  7. }
复制

WindowManagerService.java

enableScreenAfterBoot()
  1. public void enableScreenAfterBoot() {
  2. synchronized(mWindowMap) {
  3. //false
  4. if (mSystemBooted) {
  5. return;
  6. }
  7. //置为true,后面会用到
  8. mSystemBooted = true;
  9. //处理处理boot弹框提示[Android系统正在启动或者Android系统正在升级的dialog提示]
  10. //里面的mShowingBootMessages条件不满足,这里不关心
  11. hideBootMessagesLocked();
  12. //发送超时30s处理
  13. mH.sendEmptyMessageDelayed(H.BOOT_TIMEOUT, 30 * 1000);
  14. }
  15. //mPolicy是PhoneWindowManager对象,这里暂不关心
  16. mPolicy.systemBooted();
  17. //重点
  18. performEnableScreen();
  19. }
复制
performEnableScreen()
  1. private void performEnableScreen() {
  2. synchronized(mWindowMap) {
  3. //false
  4. if (mDisplayEnabled) {
  5. return;
  6. }
  7. //mSystemBooted为true, mShowingBootMessages=false
  8. if (!mSystemBooted && !mShowingBootMessages) {
  9. return;
  10. }
  11. //mShowingBootMessages设置成了false,关键判断canDismissBootAnimation()
  12. //canDismissBootAnimation()返回false,因此这里直接return了
  13. if (!mShowingBootMessages && !mPolicy.canDismissBootAnimation()) {
  14. return;
  15. }
  16. //略
  17. }
  18. //略
  19. }
复制

这个方法很重要,会反复进入,上面由于条件不支持,进入直接return了。

打印日志大致如下(部分):

  1. WindowManagerService: ENABLE_SCREEN performEnableScreen
  2. WindowManagerService: performEnableScreen ---------1----------
  3. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  4. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  5. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :false
  6. WindowManagerService: ENABLE_SCREEN performEnableScreen
  7. WindowManagerService: performEnableScreen ---------1----------
  8. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  9. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  10. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :false
  11. WindowManagerService: ENABLE_SCREEN performEnableScreen
  12. WindowManagerService: performEnableScreen ---------1----------
  13. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  14. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  15. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :false
  16. WindowManagerService: ENABLE_SCREEN performEnableScreen
  17. WindowManagerService: performEnableScreen ---------1----------
  18. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  19. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  20. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :false
  21. WindowManagerService: ENABLE_SCREEN performEnableScreen
  22. WindowManagerService: performEnableScreen ---------1----------
  23. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  24. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  25. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :false
  26. WindowManagerService: ENABLE_SCREEN performEnableScreen
  27. WindowManagerService: performEnableScreen ---------1----------
  28. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  29. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  30. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :false
  31. WindowManagerService: ENABLE_SCREEN performEnableScreen
  32. WindowManagerService: performEnableScreen ---------1----------
  33. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  34. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  35. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true
  36. WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false
  37. WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :true
  38. WindowManagerService: ENABLE_SCREEN performEnableScreen
  39. WindowManagerService: performEnableScreen ---------1----------
  40. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  41. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  42. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true
  43. WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false
  44. WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :true
  45. WindowManagerService: ENABLE_SCREEN performEnableScreen
  46. WindowManagerService: performEnableScreen ---------1----------
  47. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  48. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  49. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true
  50. WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false
  51. WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :true
  52. WindowManagerService: ENABLE_SCREEN performEnableScreen
  53. WindowManagerService: performEnableScreen ---------1----------
  54. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  55. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  56. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true
  57. WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false
  58. WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :true
  59. WindowManagerService: ENABLE_SCREEN performEnableScreen
  60. WindowManagerService: performEnableScreen ---------1----------
  61. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  62. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  63. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true
  64. WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false
  65. WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :true
  66. WindowManagerService: ENABLE_SCREEN performEnableScreen
  67. WindowManagerService: performEnableScreen ---------1----------
  68. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  69. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  70. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true
  71. WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false
  72. WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :true
  73. WindowManagerService: ENABLE_SCREEN performEnableScreen
  74. WindowManagerService: performEnableScreen ---------1----------
  75. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  76. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  77. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true
  78. WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false
  79. WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :false
  80. WindowManagerService: performEnableScreen 7 mBootAnimationStopped :false
  81. WindowManagerService: performEnableScreen 8 mForceDisplayEnabled :false
  82. WindowManagerService: ENABLE_SCREEN performEnableScreen
  83. WindowManagerService: performEnableScreen ---------1----------
  84. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  85. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  86. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true
  87. WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false
  88. WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :false
  89. WindowManagerService: performEnableScreen 7 mBootAnimationStopped :true
  90. WindowManagerService: performEnableScreen 8 mForceDisplayEnabled :false
  91. WindowManagerService: ENABLE_SCREEN performEnableScreen
  92. WindowManagerService: performEnableScreen ---------1----------
  93. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  94. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  95. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true
  96. WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false
  97. WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :false
  98. WindowManagerService: performEnableScreen 7 mBootAnimationStopped :true
  99. WindowManagerService: performEnableScreen 8 mForceDisplayEnabled :false
  100. WindowManagerService: performEnableScreen ---------1----------
  101. WindowManagerService: performEnableScreen 2 mDisplayEnabled :false
  102. WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false
  103. WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true
  104. WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false
  105. WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :false
  106. WindowManagerService: performEnableScreen 7 mBootAnimationStopped :true
  107. WindowManagerService: performEnableScreen 8 mForceDisplayEnabled :false
  108. WindowManagerService: performEnableScreen 9 :
  109. WindowManagerService: performEnableScreen 10 surfaceFlinger :android.os.BinderProxy@91905a0
  110. WindowManagerService: performEnableScreen ******* TELLING SURFACE FLINGER WE ARE BOOTED!
  111. WindowManagerService: performEnableScreen ******************** ENABLING SCREEN!
复制

经过多次的执行performEnableScreen(),最终结束开机动画

  1. private void performEnableScreen() {
  2. synchronized(mWindowMap) {
  3. //false
  4. if (mDisplayEnabled) {
  5. return;
  6. }
  7. //mSystemBooted = true, mShowingBootMessages = false
  8. if (!mSystemBooted && !mShowingBootMessages) {
  9. return;
  10. }
  11. //mShowingBootMessages= false
  12. //mPolicy.canDismissBootAnimation()一开始为false,后为true
  13. //具体看PhoneWindowManager.java
  14. if (!mShowingBootMessages && !mPolicy.canDismissBootAnimation()) {
  15. return;
  16. }
  17. // mForceDisplayEnabled默认为false,强制性显示屏幕意思,也就是开机超时
  18. // 超时设置为30s,具体看enableScreenAfterBoot()
  19. // checkWaitingForWindows()一开始为false,后面为true
  20. if (!mForceDisplayEnabled
  21. && getDefaultDisplayContentLocked().checkWaitingForWindows()) {
  22. return;
  23. }
  24. //第一次肯定为false
  25. if (!mBootAnimationStopped) {
  26. //退出开机动画
  27. //service.bootanim.exit属性值为1,标志系统要结束开机动画了
  28. SystemProperties.set("service.bootanim.exit", "1");
  29. //置为true,
  30. mBootAnimationStopped = true;
  31. }
  32. //mForceDisplayEnabled 为false,上面解释过了
  33. //checkBootAnimationCompleteLocked()检查开机动画是否完成,退出需要时间和设置其他状态
  34. if (!mForceDisplayEnabled && !checkBootAnimationCompleteLocked()) {
  35. return;
  36. }
  37. //BOLT_BOOTANIM = true
  38. if (android.os.Bolt.BOLT_BOOTANIM) {
  39. try {
  40. //关闭开机动画,还可以用adb shell控制,之前有文章写过
  41. SystemProperties.set("ctl.stop", "bootanim");
  42. } catch (Exception e) {
  43. Slog.e(android.os.Bolt.TAG, "Try 'setprop ctl.stop bootanim' failed. Check SELinux policy.");
  44. }
  45. } else {
  46. //略,因为我这走上面,这里就懒得看了
  47. }
  48. mDisplayEnabled = true;
  49. }
  50. try {
  51. //开机动画结束
  52. //ActivityManagerService.java
  53. mActivityManager.bootAnimationComplete();
  54. } catch (RemoteException e) {
  55. }
  56. //PhoneWindowManager.java
  57. mPolicy.enableScreenAfterBoot();
  58. updateRotationUnchecked(false, false);
  59. }
复制

至此,开机动画退出了。但用户还没创建,我们这里关注

  1. mActivityManager.bootAnimationComplete();
复制

ActivityManagerService.java

bootAnimationComplete()
  1. @Override
  2. public void bootAnimationComplete() {
  3. final boolean callFinishBooting;
  4. synchronized (this) {
  5. callFinishBooting = mCallFinishBooting;
  6. mBootAnimationComplete = true;
  7. }
  8. //true
  9. if (callFinishBooting) {
  10. finishBooting();
  11. }
  12. }
复制
finishBooting()
  1. final void finishBooting() {
  2. synchronized (this) {
  3. //mBootAnimationComplete此时为true,不会return
  4. if (!mBootAnimationComplete) {
  5. mCallFinishBooting = true;
  6. return;
  7. }
  8. mCallFinishBooting = false;
  9. }
  10. ArraySet<String> completedIsas = new ArraySet<String>();
  11. //开机完成设置abis[arm64-v8a,armeabi-v7a,armeabi]
  12. for (String abi : Build.SUPPORTED_ABIS) {
  13. zygoteProcess.establishZygoteConnectionForAbi(abi);
  14. final String instructionSet = VMRuntime.getInstructionSet(abi);
  15. if (!completedIsas.contains(instructionSet)) {
  16. try {
  17. mInstaller.markBootComplete(VMRuntime.getInstructionSet(abi));
  18. } catch (InstallerException e) {
  19. Slog.w(TAG, "Unable to mark boot complete for abi: " + abi + " (" +
  20. e.getMessage() +")");
  21. }
  22. completedIsas.add(instructionSet);
  23. }
  24. }
  25. //注册应用重启广播
  26. IntentFilter pkgFilter = new IntentFilter();
  27. pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
  28. pkgFilter.addDataScheme("package");
  29. mContext.registerReceiver(new BroadcastReceiver() {
  30. @Override
  31. public void onReceive(Context context, Intent intent) {
  32. String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
  33. if (pkgs != null) {
  34. for (String pkg : pkgs) {
  35. synchronized (ActivityManagerService.this) {
  36. //强制性停止某个包名
  37. if (forceStopPackageLocked(pkg, -1, false, false, false, false, false,
  38. 0, "query restart")) {
  39. setResultCode(Activity.RESULT_OK);
  40. return;
  41. }
  42. }
  43. }
  44. }
  45. }
  46. }, pkgFilter);
  47. //注册ACTION_DELETE_DUMPHEAP广播
  48. IntentFilter dumpheapFilter = new IntentFilter();
  49. dumpheapFilter.addAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP);
  50. mContext.registerReceiver(new BroadcastReceiver() {
  51. @Override
  52. public void onReceive(Context context, Intent intent) {
  53. if (intent.getBooleanExtra(DumpHeapActivity.EXTRA_DELAY_DELETE, false)) {
  54. mHandler.sendEmptyMessageDelayed(POST_DUMP_HEAP_NOTIFICATION_MSG, 5*60*1000);
  55. } else {
  56. mHandler.sendEmptyMessage(POST_DUMP_HEAP_NOTIFICATION_MSG);
  57. }
  58. }
  59. }, dumpheapFilter);
  60. //通知系统服务开机完成
  61. //这里就SystemServer中启动的服务
  62. //类似的可以参考《StorageManagerService的启动》中Lifecycle就是一个服务。
  63. mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED);
  64. synchronized (this) {
  65. final int NP = mProcessesOnHold.size();
  66. //之前onhold的进程,开始启动
  67. Slog.d(TAG, "finishBooting 6 NP : "+ NP);
  68. if (NP > 0) {
  69. ArrayList<ProcessRecord> procs =
  70. new ArrayList<ProcessRecord>(mProcessesOnHold);
  71. for (int ip=0; ip<NP; ip++) {
  72. startProcessLocked(procs.get(ip), "on-hold", null);
  73. }
  74. }
  75. if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
  76. return;
  77. }
  78. Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
  79. mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
  80. SystemProperties.set("sys.boot_completed", "1");
  81.  
  82. if (!"trigger_restart_min_framework".equals(SystemProperties.get("vold.decrypt"))
  83. || "".equals(SystemProperties.get("vold.encrypt_progress"))) {
  84. SystemProperties.set("dev.bootcomplete", "1");
  85. }
  86. //调用mUserController发送sendBootCompleted
  87. mUserController.sendBootCompleted(
  88. new IIntentReceiver.Stub() {
  89. @Override
  90. public void performReceive(Intent intent, int resultCode,
  91. String data, Bundle extras, boolean ordered,
  92. boolean sticky, int sendingUser) {
  93. synchronized (ActivityManagerService.this) {
  94. requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false);
  95. }
  96. }
  97. });
  98. mUserController.scheduleStartProfiles();
  99. }
  100. mAnrManager.writeEvent(AnrManager.EVENT_BOOT_COMPLETED);
  101. }
复制

上面比较重要的是:

  1. mSystemServiceManager调用startBootPhase(),这里会通知SystemService中添加的所有服务

  2. mUserController调用sendBootCompleted,通知发送Boot Completed

我们主要关注第二点。

UserController.java

sendBootCompleted()
  1. void sendBootCompleted(IIntentReceiver resultTo) {
  2. SparseArray<UserState> startedUsers;
  3. synchronized (mLock) {
  4. startedUsers = mStartedUsers.clone();
  5. }
  6. //此时至少有一个用户
  7. for (int i = 0; i < startedUsers.size(); i++) {
  8. UserState uss = startedUsers.valueAt(i);
  9. //执行finishUserBoot
  10. finishUserBoot(uss, resultTo);
  11. }
  12. }
复制
finishUserBoot()
  1. private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
  2. final int userId = uss.mHandle.getIdentifier();
  3. synchronized (mLock) {
  4. //用户不匹配则返回
  5. if (mStartedUsers.get(userId) != uss) {
  6. return;
  7. }
  8. }
  9. //如果用户在锁定状态
  10. if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) {
  11. mInjector.getUserManagerInternal().setUserState(userId, uss.state);
  12. if (userId == UserHandle.USER_SYSTEM
  13. && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) {
  14. int uptimeSeconds = (int)(SystemClock.elapsedRealtime() / 1000);
  15. MetricsLogger.histogram(mInjector.getContext(),
  16. "framework_locked_boot_completed", uptimeSeconds);
  17. final int MAX_UPTIME_SECONDS = 120;
  18. if (uptimeSeconds > MAX_UPTIME_SECONDS) {
  19. if ("user".equals(Build.TYPE)) {
  20. Slog.wtf("SystemServerTiming",
  21. "finishUserBoot took too long. uptimeSeconds=" + uptimeSeconds);
  22. } else {
  23. Slog.w("SystemServerTiming",
  24. "finishUserBoot took too long. uptimeSeconds=" + uptimeSeconds);
  25. }
  26. }
  27. }
  28. //发送锁屏开机广播
  29. mHandler.sendMessage(mHandler.obtainMessage(REPORT_LOCKED_BOOT_COMPLETE_MSG,
  30. userId, 0));
  31. Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
  32. intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
  33. intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
  34. | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
  35. mInjector.broadcastIntent(intent, null, resultTo, 0, null, null,
  36. new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
  37. AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
  38. }
  39.  
  40. //解锁用户的credential-encrypted storage
  41. //false
  42. if (mInjector.getUserManager().isManagedProfile(userId)) {
  43. final UserInfo parent = mInjector.getUserManager().getProfileParent(userId);
  44. if (parent != null
  45. && isUserRunning(parent.id, ActivityManager.FLAG_AND_UNLOCKED)) {
  46. Slog.d(TAG, "User " + userId + " (parent " + parent.id
  47. + "): attempting unlock because parent is unlocked");
  48. maybeUnlockUser(userId);
  49. } else {
  50. String parentId = (parent == null) ? "<null>" : String.valueOf(parent.id);
  51. Slog.d(TAG, "User " + userId + " (parent " + parentId
  52. + "): delaying unlock because parent is locked");
  53. }
  54. } else {
  55. maybeUnlockUser(userId);
  56. }
  57. }
复制
maybeUnlockUser()
  1. private boolean maybeUnlockUser(final int userId) {
  2. return unlockUserCleared(userId, null, null, null);
  3. }
复制
unlockUserCleared()
  1. private boolean unlockUserCleared(final int userId, byte[] token, byte[] secret,
  2. IProgressListener listener) {
  3. UserState uss;
  4. //解锁user storage,isUserKeyUnlocked()返回true,但取反就false
  5. if (!StorageManager.isUserKeyUnlocked(userId)) {
  6. final UserInfo userInfo = getUserInfo(userId);
  7. final IStorageManager storageManager = getStorageManager();
  8. try {
  9. // We always want to unlock user storage, even user is not started yet
  10. storageManager.unlockUserKey(userId, userInfo.serialNumber, token, secret);
  11. } catch (RemoteException | RuntimeException e) {
  12. Slog.w(TAG, "Failed to unlock: " + e.getMessage());
  13. }
  14. }
  15. synchronized (mLock) {
  16. // Register the given listener to watch for unlock progress
  17. uss = mStartedUsers.get(userId);
  18. //不为null
  19. if (uss != null) {
  20. uss.mUnlockProgress.addListener(listener);
  21. uss.tokenProvided = (token != null);
  22. }
  23. }
  24. // Bail if user isn't actually running
  25. if (uss == null) {
  26. notifyFinished(userId, listener);
  27. return false;
  28. }
  29. //完成解锁
  30. finishUserUnlocking(uss);
  31. int[] userIds;
  32. synchronized (mLock) {
  33. userIds = new int[mStartedUsers.size()];
  34. for (int i = 0; i < userIds.length; i++) {
  35. userIds[i] = mStartedUsers.keyAt(i);
  36. }
  37. }
  38. //解锁其他的用户
  39. for (int testUserId : userIds) {
  40. final UserInfo parent = mInjector.getUserManager().getProfileParent(testUserId);
  41. //parent= null
  42. if (parent != null && parent.id == userId && testUserId != userId) {
  43. maybeUnlockUser(testUserId);
  44. }
  45. }
  46. return true;
  47. }
复制

上面比较关心的是finishUserUnlocking()

finishUserUnlocking()
  1. private void finishUserUnlocking(final UserState uss) {
  2. final int userId = uss.mHandle.getIdentifier();
  3. if (!StorageManager.isUserKeyUnlocked(userId)) return;
  4. synchronized (mLock) {
  5. if (mStartedUsers.get(userId) != uss || uss.state != STATE_RUNNING_LOCKED) {
  6. return;
  7. }
  8. }
  9. uss.mUnlockProgress.start();
  10. // 设置进度
  11. uss.mUnlockProgress.setProgress(5,
  12. mInjector.getContext().getString(R.string.android_start_title));
  13. // Call onBeforeUnlockUser on a worker thread that allows disk I/O
  14. FgThread.getHandler().post(() -> {
  15. //isUserKeyUnlocked()=true
  16. if (!StorageManager.isUserKeyUnlocked(userId)) {
  17. return;
  18. }
  19. mInjector.getUserManager().onBeforeUnlockUser(userId);
  20. synchronized (mLock) {
  21. if (!uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) {
  22. return;
  23. }
  24. }
  25. mInjector.getUserManagerInternal().setUserState(userId, uss.state);
  26. // 设置进度
  27. uss.mUnlockProgress.setProgress(20);
  28. //通知系统服务解锁完成
  29. mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0, uss)
  30. .sendToTarget();
  31. });
  32. }
复制

Handler发送了SYSTEM_USER_UNLOCK_MSG。

handleMessage()
  1. case SYSTEM_USER_UNLOCK_MSG:
  2. final int userId = msg.arg1;
  3. mInjector.getSystemServiceManager().unlockUser(userId);
  4. // Loads recents on a worker thread that allows disk I/O
  5. FgThread.getHandler().post(() -> {
  6. mInjector.loadUserRecents(userId);
  7. });
  8. //完成用户解锁
  9. finishUserUnlocked((UserState) msg.obj);
  10. break;
复制
finishUserUnlocked()

显示几个用户状态

  1. public final static int STATE_BOOTING = 0;
  2. // User is in the locked state.
  3. public final static int STATE_RUNNING_LOCKED = 1;
  4. // User is in the unlocking state.
  5. public final static int STATE_RUNNING_UNLOCKING = 2;
  6. // User is in the running state.
  7. public final static int STATE_RUNNING_UNLOCKED = 3;
  8. // User is in the initial process of being stopped.
  9. public final static int STATE_STOPPING = 4;
  10. // User is in the final phase of stopping, sending Intent.ACTION_SHUTDOWN.
  11. public final static int STATE_SHUTDOWN = 5;
复制
  1. void finishUserUnlocked(final UserState uss) {
  2. final int userId = uss.mHandle.getIdentifier();
  3. //没有解锁返回
  4. if (!StorageManager.isUserKeyUnlocked(userId)) return;
  5. synchronized (mLock) {
  6. // Bail if we ended up with a stale user
  7. if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
  8. // Do not proceed if unexpected state
  9. if (!uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) {
  10. return;
  11. }
  12. }
  13. //解锁完成
  14. mInjector.getUserManagerInternal().setUserState(userId, uss.state);
  15. uss.mUnlockProgress.finish();
  16.  
  17. //发送ACTION_USER_UNLOCKED广播
  18. final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
  19. unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
  20. unlockedIntent.addFlags(
  21. Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
  22. mInjector.broadcastIntent(unlockedIntent, null, null, 0, null,
  23. null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
  24. userId);
  25. //略
  26.  
  27. //info.lastLoggedInFingerprint, Build.FINGERPRINT相等,取反就不满足条件,走else
  28. if (!Objects.equals(info.lastLoggedInFingerprint, Build.FINGERPRINT)) {
  29. final boolean quiet;
  30. if (info.isManagedProfile()) {
  31. quiet = !uss.tokenProvided
  32. || !mLockPatternUtils.isSeparateProfileChallengeEnabled(userId);
  33. } else {
  34. quiet = false;
  35. }
  36. mInjector.sendPreBootBroadcast(userId, quiet,
  37. () -> finishUserUnlockedCompleted(uss));
  38. } else {
  39. //进入这里
  40. finishUserUnlockedCompleted(uss);
  41. }
  42. }
复制

这里最重要的一个点,发送了ACTION_USER_UNLOCKED。

也就是这里才会有ACTION_USER_UNLOCKED广播发送。

继续看finishUserUnlockedCompleted()

finishUserUnlockedCompleted()
  1. private void finishUserUnlockedCompleted(UserState uss) {
  2. final int userId = uss.mHandle.getIdentifier();
  3. synchronized (mLock) {
  4. if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
  5. }
  6. UserInfo userInfo = getUserInfo(userId);
  7. if (userInfo == null) {
  8. return;
  9. }
  10. // Only keep marching forward if user is actually unlocked
  11. if (!StorageManager.isUserKeyUnlocked(userId)) return;
  12. // Remember that we logged in
  13. mInjector.getUserManager().onUserLoggedIn(userId);
  14. //userInfo.isInitialized() = true,不进入
  15. if (!userInfo.isInitialized()) {
  16. if (userId != UserHandle.USER_SYSTEM) {
  17. //发送ACTION_USER_INITIALIZE广播去给user初始化
  18. Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
  19. intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
  20. | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
  21. mInjector.broadcastIntent(intent, null,
  22. new IIntentReceiver.Stub() {
  23. @Override
  24. public void performReceive(Intent intent, int resultCode,
  25. String data, Bundle extras, boolean ordered,
  26. boolean sticky, int sendingUser) {
  27. // Note: performReceive is called with mService lock held
  28. mInjector.getUserManager().makeInitialized(userInfo.id);
  29. }
  30. }, 0, null, null, null, AppOpsManager.OP_NONE,
  31. null, true, false, MY_PID, SYSTEM_UID, userId);
  32. }
  33. }
  34. // Do not report secondary users, runtime restarts or first boot/upgrade
  35. //userId = 0
  36. if (userId == UserHandle.USER_SYSTEM
  37. && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) {
  38. int uptimeSeconds = (int) (SystemClock.elapsedRealtime() / 1000);
  39. MetricsLogger.histogram(mInjector.getContext(), "framework_boot_completed",
  40. uptimeSeconds);
  41. }
  42. //发送ACTION_BOOT_COMPLETED广播
  43. final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
  44. bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
  45. bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
  46. | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
  47. mInjector.broadcastIntent(bootIntent, null, new IIntentReceiver.Stub() {
  48. @Override
  49. public void performReceive(Intent intent, int resultCode, String data,
  50. Bundle extras, boolean ordered, boolean sticky, int sendingUser)
  51. throws RemoteException {
  52. Slog.i(UserController.TAG, "Finished processing BOOT_COMPLETED for u" + userId);
  53. }
  54. }, 0, null, null,
  55. new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
  56. AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
  57.  
  58. if (!SystemProperties.get("vendor.android.home.ready").equals("1")) {
  59. SystemProperties.set("vendor.android.home.ready", "1");
  60. }
  61.  
  62. Timer timer = new Timer();
  63. timer.schedule(new TimerTask() {
  64. @Override
  65. public void run() {
  66. final Intent readyIntent = new Intent(Intent.ACTION_HOME_READY, null);
  67. readyIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
  68. readyIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
  69. mInjector.broadcastIntent(readyIntent, null, new IIntentReceiver.Stub() {
  70. @Override
  71. public void performReceive(Intent intent, int resultCode, String data,
  72. Bundle extras, boolean ordered, boolean sticky, int sendingUser)
  73. throws RemoteException {
  74. Slog.i(UserController.TAG, "Finished processing HOME_READY for u" + userId);
  75. }
  76. }, 0, null, null,
  77. new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
  78. AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
  79. }
  80. }, 1000); // Delay 1s
  81. }
复制

这里会发送ACTION_BOOT_COMPLETED,至此,才算真正的开机成功。

参考文章

  1. Android输入法IMMS服务启动流程(5)(onUnlockUser过程)

  2. Android开机动画关闭源码分析

  3. StorageManagerService的启动

自动化零件服务商 - 供应SMC,FESTO,CKD全新正品气动元件

相关文章

自动化零件服务商 - 供应SMC,FESTO,CKD全新正品气动元件

暂无评论

none
暂无评论...