目录
前言
记录一下Android开机时ACTION_USER_UNLOCKED和ACTION_BOOT_COMPLETED啥时候发送的过程记录,主要是方便自己回顾。
Android P分析为例。
正文
本文跟《》存在大量重复,这就简单过一下。
ResumeActivityItem.java
execute()
@Override public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) { // 看子类ActivityThread.java的实现 client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward, "RESUME_ACTIVITY"); }
ActivityThread.java
handleResumeActivity()
@Override public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward, String reason) { //略 //[重]就是调用onResume() final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason); if (r == null) { return; } //略 r.nextIdle = mNewActivities; mNewActivities = r; //[重] 这个是表示onResume()进入idler状态啦 Looper.myQueue().addIdleHandler(new Idler()); }
performResumeActivity()不是这次的关心点,我们看addIdleHandler()。
这里添加了一个Idler对象,这部分看MessageQueue类。
反正就是MessageQueue总的next()会调用Idler对象,具体看《》
Idler
private class Idler implements MessageQueue.IdleHandler { @Override public final boolean queueIdle() { ActivityClientRecord a = mNewActivities; boolean stopProfiling = false; if (mBoundApplication != null && mProfiler.profileFd != null && mProfiler.autoStopProfiler) { stopProfiling = true; } if (a != null) { mNewActivities = null; //获取ActivityManagerService IActivityManager am = ActivityManager.getService(); ActivityClientRecord prev; do { if (a.activity != null && !a.activity.mFinished) { try { //[重],看这里 am.activityIdle(a.token, a.createdConfig, stopProfiling); a.createdConfig = null; } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } } prev = a; a = a.nextIdle; prev.nextIdle = null; } while (a != null); } if (stopProfiling) { mProfiler.stopProfiling(); } ensureJitEnabled(); return false; } }
这里的am就是ActivityManagerService。
ActivityManagerService.java
activityIdle()
@Override public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) { final long origId = Binder.clearCallingIdentity(); synchronized (this) { ActivityStack stack = ActivityRecord.getStackLocked(token); //不为null, if (stack != null) { //关注这个activityIdleInternalLocked //mStackSupervisor是ActivityStackSupervisor对象 ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token, false /* fromTimeout */, false /* processPausingActivities */, config); //false if (stopProfiling) { if ((mProfileProc == r.app) && mProfilerInfo != null) { clearProfilerLocked(); } } } } Binder.restoreCallingIdentity(origId); }
ActivityStackSupervisor.java
activityIdleInternalLocked()
@GuardedBy("mService") final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout, boolean processPausingActivities, Configuration config) { ActivityRecord r = ActivityRecord.forTokenLocked(token); //略 //r不为null if (r != null) { //移除IDLE_TIMEOUT_MSG mHandler.removeMessages(IDLE_TIMEOUT_MSG, r); r.finishLaunchTickingLocked(); //略 //第一个为true,满足条件 //fromTimeout为false,没有超时 if (isFocusedStack(r.getStack()) || fromTimeout) { //true [重],这个检测是否开机成功 booting = checkFinishBootingLocked(); } } //true if (allResumedActivitiesIdle()) { if (r != null) { mService.scheduleAppGcsLocked(); } if (mLaunchingActivity.isHeld()) { //略 } //就是遍历Activity状态啥的,不是我们关系的 ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS); } //略 mService.trimApplications(); //activityRemoved = false if (activityRemoved) { resumeFocusedStackTopActivityLocked(); } return r; }
重点关心
booting = checkFinishBootingLocked();
checkFinishBootingLocked()
@GuardedBy("mService") private boolean checkFinishBootingLocked() { final boolean booting = mService.mBooting; boolean enableScreen = false; mService.mBooting = false; //false if (!mService.mBooted) { mService.mBooted = true; enableScreen = true; } // booting = true, //enableScreen = true if (booting || enableScreen) { //进入这里,两个都是为true mService.postFinishBooting(booting, enableScreen); } return booting; }
ActivityManagerService.java
void postFinishBooting(boolean finishBooting, boolean enableScreen) { mHandler.sendMessage(mHandler.obtainMessage(FINISH_BOOTING_MSG, finishBooting ? 1 : 0, enableScreen ? 1 : 0)); }
发送的消息是FINISH_BOOTING_MSG
finishBooting和enableScreen都为true,因此msg.arg1和msg.arg2都为1
handleMessage()
是在MainHandler类中
final class MainHandler extends Handler { //略 @Override public void handleMessage(Message msg) { switch (msg.what) { //略 case FINISH_BOOTING_MSG: { if (msg.arg1 != 0) {//为1 finishBooting(); } if (msg.arg2 != 0) {//为1 enableScreenAfterBoot(); } break; } //略 } } }
finishBooting()
第一次是mBootAnimationComplete为false,进入if语句后,仅mCallFinishBooting置为true,然后return。
final void finishBooting() { synchronized (this) { //mBootAnimationComplete此时为false if (!mBootAnimationComplete) { mCallFinishBooting = true; return; } mCallFinishBooting = false; } //略 }
enableScreenAfterBoot()
void enableScreenAfterBoot() { //调用的WindowManagerService.enableScreenAfterBoot() mWindowManager.enableScreenAfterBoot(); synchronized (this) { updateEventDispatchingLocked(); } }
WindowManagerService.java
enableScreenAfterBoot()
public void enableScreenAfterBoot() { synchronized(mWindowMap) { //false if (mSystemBooted) { return; } //置为true,后面会用到 mSystemBooted = true; //处理处理boot弹框提示[Android系统正在启动或者Android系统正在升级的dialog提示] //里面的mShowingBootMessages条件不满足,这里不关心 hideBootMessagesLocked(); //发送超时30s处理 mH.sendEmptyMessageDelayed(H.BOOT_TIMEOUT, 30 * 1000); } //mPolicy是PhoneWindowManager对象,这里暂不关心 mPolicy.systemBooted(); //重点 performEnableScreen(); }
performEnableScreen()
private void performEnableScreen() { synchronized(mWindowMap) { //false if (mDisplayEnabled) { return; } //mSystemBooted为true, mShowingBootMessages=false if (!mSystemBooted && !mShowingBootMessages) { return; } //mShowingBootMessages设置成了false,关键判断canDismissBootAnimation() //canDismissBootAnimation()返回false,因此这里直接return了 if (!mShowingBootMessages && !mPolicy.canDismissBootAnimation()) { return; } //略 } //略 }
这个方法很重要,会反复进入,上面由于条件不支持,进入直接return了。
打印日志大致如下(部分):
WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :false WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :false WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :false WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :false WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :false WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :false WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :true WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :true WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :true WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :true WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :true WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :true WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :false WindowManagerService: performEnableScreen 7 mBootAnimationStopped :false WindowManagerService: performEnableScreen 8 mForceDisplayEnabled :false WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :false WindowManagerService: performEnableScreen 7 mBootAnimationStopped :true WindowManagerService: performEnableScreen 8 mForceDisplayEnabled :false WindowManagerService: ENABLE_SCREEN performEnableScreen WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :false WindowManagerService: performEnableScreen 7 mBootAnimationStopped :true WindowManagerService: performEnableScreen 8 mForceDisplayEnabled :false WindowManagerService: performEnableScreen ---------1---------- WindowManagerService: performEnableScreen 2 mDisplayEnabled :false WindowManagerService: performEnableScreen 3 mSystemBooted :true , mShowingBootMessages: false WindowManagerService: performEnableScreen 4 mPolicy.canDismissBootAnimation() :true WindowManagerService: performEnableScreen 5 mForceDisplayEnabled :false WindowManagerService: performEnableScreen 6 checkWaitingForWindows() :false WindowManagerService: performEnableScreen 7 mBootAnimationStopped :true WindowManagerService: performEnableScreen 8 mForceDisplayEnabled :false WindowManagerService: performEnableScreen 9 : WindowManagerService: performEnableScreen 10 surfaceFlinger :android.os.BinderProxy@91905a0 WindowManagerService: performEnableScreen ******* TELLING SURFACE FLINGER WE ARE BOOTED! WindowManagerService: performEnableScreen ******************** ENABLING SCREEN!
经过多次的执行performEnableScreen(),最终结束开机动画
private void performEnableScreen() { synchronized(mWindowMap) { //false if (mDisplayEnabled) { return; } //mSystemBooted = true, mShowingBootMessages = false if (!mSystemBooted && !mShowingBootMessages) { return; } //mShowingBootMessages= false //mPolicy.canDismissBootAnimation()一开始为false,后为true //具体看PhoneWindowManager.java if (!mShowingBootMessages && !mPolicy.canDismissBootAnimation()) { return; } // mForceDisplayEnabled默认为false,强制性显示屏幕意思,也就是开机超时 // 超时设置为30s,具体看enableScreenAfterBoot() // checkWaitingForWindows()一开始为false,后面为true if (!mForceDisplayEnabled && getDefaultDisplayContentLocked().checkWaitingForWindows()) { return; } //第一次肯定为false if (!mBootAnimationStopped) { //退出开机动画 //service.bootanim.exit属性值为1,标志系统要结束开机动画了 SystemProperties.set("service.bootanim.exit", "1"); //置为true, mBootAnimationStopped = true; } //mForceDisplayEnabled 为false,上面解释过了 //checkBootAnimationCompleteLocked()检查开机动画是否完成,退出需要时间和设置其他状态 if (!mForceDisplayEnabled && !checkBootAnimationCompleteLocked()) { return; } //BOLT_BOOTANIM = true if (android.os.Bolt.BOLT_BOOTANIM) { try { //关闭开机动画,还可以用adb shell控制,之前有文章写过 SystemProperties.set("ctl.stop", "bootanim"); } catch (Exception e) { Slog.e(android.os.Bolt.TAG, "Try 'setprop ctl.stop bootanim' failed. Check SELinux policy."); } } else { //略,因为我这走上面,这里就懒得看了 } mDisplayEnabled = true; } try { //开机动画结束 //ActivityManagerService.java mActivityManager.bootAnimationComplete(); } catch (RemoteException e) { } //PhoneWindowManager.java mPolicy.enableScreenAfterBoot(); updateRotationUnchecked(false, false); }
至此,开机动画退出了。但用户还没创建,我们这里关注
mActivityManager.bootAnimationComplete();
ActivityManagerService.java
bootAnimationComplete()
@Override public void bootAnimationComplete() { final boolean callFinishBooting; synchronized (this) { callFinishBooting = mCallFinishBooting; mBootAnimationComplete = true; } //true if (callFinishBooting) { finishBooting(); } }
finishBooting()
final void finishBooting() { synchronized (this) { //mBootAnimationComplete此时为true,不会return if (!mBootAnimationComplete) { mCallFinishBooting = true; return; } mCallFinishBooting = false; } ArraySet<String> completedIsas = new ArraySet<String>(); //开机完成设置abis[arm64-v8a,armeabi-v7a,armeabi] for (String abi : Build.SUPPORTED_ABIS) { zygoteProcess.establishZygoteConnectionForAbi(abi); final String instructionSet = VMRuntime.getInstructionSet(abi); if (!completedIsas.contains(instructionSet)) { try { mInstaller.markBootComplete(VMRuntime.getInstructionSet(abi)); } catch (InstallerException e) { Slog.w(TAG, "Unable to mark boot complete for abi: " + abi + " (" + e.getMessage() +")"); } completedIsas.add(instructionSet); } } //注册应用重启广播 IntentFilter pkgFilter = new IntentFilter(); pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART); pkgFilter.addDataScheme("package"); mContext.registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES); if (pkgs != null) { for (String pkg : pkgs) { synchronized (ActivityManagerService.this) { //强制性停止某个包名 if (forceStopPackageLocked(pkg, -1, false, false, false, false, false, 0, "query restart")) { setResultCode(Activity.RESULT_OK); return; } } } } } }, pkgFilter); //注册ACTION_DELETE_DUMPHEAP广播 IntentFilter dumpheapFilter = new IntentFilter(); dumpheapFilter.addAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP); mContext.registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getBooleanExtra(DumpHeapActivity.EXTRA_DELAY_DELETE, false)) { mHandler.sendEmptyMessageDelayed(POST_DUMP_HEAP_NOTIFICATION_MSG, 5*60*1000); } else { mHandler.sendEmptyMessage(POST_DUMP_HEAP_NOTIFICATION_MSG); } } }, dumpheapFilter); //通知系统服务开机完成 //这里就SystemServer中启动的服务 //类似的可以参考《StorageManagerService的启动》中Lifecycle就是一个服务。 mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED); synchronized (this) { final int NP = mProcessesOnHold.size(); //之前onhold的进程,开始启动 Slog.d(TAG, "finishBooting 6 NP : "+ NP); if (NP > 0) { ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(mProcessesOnHold); for (int ip=0; ip<NP; ip++) { startProcessLocked(procs.get(ip), "on-hold", null); } } if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) { return; } Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG); mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL); SystemProperties.set("sys.boot_completed", "1"); if (!"trigger_restart_min_framework".equals(SystemProperties.get("vold.decrypt")) || "".equals(SystemProperties.get("vold.encrypt_progress"))) { SystemProperties.set("dev.bootcomplete", "1"); } //调用mUserController发送sendBootCompleted mUserController.sendBootCompleted( new IIntentReceiver.Stub() { @Override public void performReceive(Intent intent, int resultCode, String data, Bundle extras, boolean ordered, boolean sticky, int sendingUser) { synchronized (ActivityManagerService.this) { requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false); } } }); mUserController.scheduleStartProfiles(); } mAnrManager.writeEvent(AnrManager.EVENT_BOOT_COMPLETED); }
上面比较重要的是:
-
mSystemServiceManager调用startBootPhase(),这里会通知SystemService中添加的所有服务
-
mUserController调用sendBootCompleted,通知发送Boot Completed
我们主要关注第二点。
UserController.java
sendBootCompleted()
void sendBootCompleted(IIntentReceiver resultTo) { SparseArray<UserState> startedUsers; synchronized (mLock) { startedUsers = mStartedUsers.clone(); } //此时至少有一个用户 for (int i = 0; i < startedUsers.size(); i++) { UserState uss = startedUsers.valueAt(i); //执行finishUserBoot finishUserBoot(uss, resultTo); } }
finishUserBoot()
private void finishUserBoot(UserState uss, IIntentReceiver resultTo) { final int userId = uss.mHandle.getIdentifier(); synchronized (mLock) { //用户不匹配则返回 if (mStartedUsers.get(userId) != uss) { return; } } //如果用户在锁定状态 if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) { mInjector.getUserManagerInternal().setUserState(userId, uss.state); if (userId == UserHandle.USER_SYSTEM && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) { int uptimeSeconds = (int)(SystemClock.elapsedRealtime() / 1000); MetricsLogger.histogram(mInjector.getContext(), "framework_locked_boot_completed", uptimeSeconds); final int MAX_UPTIME_SECONDS = 120; if (uptimeSeconds > MAX_UPTIME_SECONDS) { if ("user".equals(Build.TYPE)) { Slog.wtf("SystemServerTiming", "finishUserBoot took too long. uptimeSeconds=" + uptimeSeconds); } else { Slog.w("SystemServerTiming", "finishUserBoot took too long. uptimeSeconds=" + uptimeSeconds); } } } //发送锁屏开机广播 mHandler.sendMessage(mHandler.obtainMessage(REPORT_LOCKED_BOOT_COMPLETE_MSG, userId, 0)); Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null); intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); mInjector.broadcastIntent(intent, null, resultTo, 0, null, null, new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED}, AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId); } //解锁用户的credential-encrypted storage //false if (mInjector.getUserManager().isManagedProfile(userId)) { final UserInfo parent = mInjector.getUserManager().getProfileParent(userId); if (parent != null && isUserRunning(parent.id, ActivityManager.FLAG_AND_UNLOCKED)) { Slog.d(TAG, "User " + userId + " (parent " + parent.id + "): attempting unlock because parent is unlocked"); maybeUnlockUser(userId); } else { String parentId = (parent == null) ? "<null>" : String.valueOf(parent.id); Slog.d(TAG, "User " + userId + " (parent " + parentId + "): delaying unlock because parent is locked"); } } else { maybeUnlockUser(userId); } }
maybeUnlockUser()
private boolean maybeUnlockUser(final int userId) { return unlockUserCleared(userId, null, null, null); }
unlockUserCleared()
private boolean unlockUserCleared(final int userId, byte[] token, byte[] secret, IProgressListener listener) { UserState uss; //解锁user storage,isUserKeyUnlocked()返回true,但取反就false if (!StorageManager.isUserKeyUnlocked(userId)) { final UserInfo userInfo = getUserInfo(userId); final IStorageManager storageManager = getStorageManager(); try { // We always want to unlock user storage, even user is not started yet storageManager.unlockUserKey(userId, userInfo.serialNumber, token, secret); } catch (RemoteException | RuntimeException e) { Slog.w(TAG, "Failed to unlock: " + e.getMessage()); } } synchronized (mLock) { // Register the given listener to watch for unlock progress uss = mStartedUsers.get(userId); //不为null if (uss != null) { uss.mUnlockProgress.addListener(listener); uss.tokenProvided = (token != null); } } // Bail if user isn't actually running if (uss == null) { notifyFinished(userId, listener); return false; } //完成解锁 finishUserUnlocking(uss); int[] userIds; synchronized (mLock) { userIds = new int[mStartedUsers.size()]; for (int i = 0; i < userIds.length; i++) { userIds[i] = mStartedUsers.keyAt(i); } } //解锁其他的用户 for (int testUserId : userIds) { final UserInfo parent = mInjector.getUserManager().getProfileParent(testUserId); //parent= null if (parent != null && parent.id == userId && testUserId != userId) { maybeUnlockUser(testUserId); } } return true; }
上面比较关心的是finishUserUnlocking()
finishUserUnlocking()
private void finishUserUnlocking(final UserState uss) { final int userId = uss.mHandle.getIdentifier(); if (!StorageManager.isUserKeyUnlocked(userId)) return; synchronized (mLock) { if (mStartedUsers.get(userId) != uss || uss.state != STATE_RUNNING_LOCKED) { return; } } uss.mUnlockProgress.start(); // 设置进度 uss.mUnlockProgress.setProgress(5, mInjector.getContext().getString(R.string.android_start_title)); // Call onBeforeUnlockUser on a worker thread that allows disk I/O FgThread.getHandler().post(() -> { //isUserKeyUnlocked()=true if (!StorageManager.isUserKeyUnlocked(userId)) { return; } mInjector.getUserManager().onBeforeUnlockUser(userId); synchronized (mLock) { if (!uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) { return; } } mInjector.getUserManagerInternal().setUserState(userId, uss.state); // 设置进度 uss.mUnlockProgress.setProgress(20); //通知系统服务解锁完成 mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0, uss) .sendToTarget(); }); }
Handler发送了SYSTEM_USER_UNLOCK_MSG。
handleMessage()
case SYSTEM_USER_UNLOCK_MSG: final int userId = msg.arg1; mInjector.getSystemServiceManager().unlockUser(userId); // Loads recents on a worker thread that allows disk I/O FgThread.getHandler().post(() -> { mInjector.loadUserRecents(userId); }); //完成用户解锁 finishUserUnlocked((UserState) msg.obj); break;
finishUserUnlocked()
显示几个用户状态
public final static int STATE_BOOTING = 0; // User is in the locked state. public final static int STATE_RUNNING_LOCKED = 1; // User is in the unlocking state. public final static int STATE_RUNNING_UNLOCKING = 2; // User is in the running state. public final static int STATE_RUNNING_UNLOCKED = 3; // User is in the initial process of being stopped. public final static int STATE_STOPPING = 4; // User is in the final phase of stopping, sending Intent.ACTION_SHUTDOWN. public final static int STATE_SHUTDOWN = 5;
void finishUserUnlocked(final UserState uss) { final int userId = uss.mHandle.getIdentifier(); //没有解锁返回 if (!StorageManager.isUserKeyUnlocked(userId)) return; synchronized (mLock) { // Bail if we ended up with a stale user if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return; // Do not proceed if unexpected state if (!uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) { return; } } //解锁完成 mInjector.getUserManagerInternal().setUserState(userId, uss.state); uss.mUnlockProgress.finish(); //发送ACTION_USER_UNLOCKED广播 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED); unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); unlockedIntent.addFlags( Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND); mInjector.broadcastIntent(unlockedIntent, null, null, 0, null, null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID, userId); //略 //info.lastLoggedInFingerprint, Build.FINGERPRINT相等,取反就不满足条件,走else if (!Objects.equals(info.lastLoggedInFingerprint, Build.FINGERPRINT)) { final boolean quiet; if (info.isManagedProfile()) { quiet = !uss.tokenProvided || !mLockPatternUtils.isSeparateProfileChallengeEnabled(userId); } else { quiet = false; } mInjector.sendPreBootBroadcast(userId, quiet, () -> finishUserUnlockedCompleted(uss)); } else { //进入这里 finishUserUnlockedCompleted(uss); } }
这里最重要的一个点,发送了ACTION_USER_UNLOCKED。
也就是这里才会有ACTION_USER_UNLOCKED广播发送。
继续看finishUserUnlockedCompleted()
finishUserUnlockedCompleted()
private void finishUserUnlockedCompleted(UserState uss) { final int userId = uss.mHandle.getIdentifier(); synchronized (mLock) { if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return; } UserInfo userInfo = getUserInfo(userId); if (userInfo == null) { return; } // Only keep marching forward if user is actually unlocked if (!StorageManager.isUserKeyUnlocked(userId)) return; // Remember that we logged in mInjector.getUserManager().onUserLoggedIn(userId); //userInfo.isInitialized() = true,不进入 if (!userInfo.isInitialized()) { if (userId != UserHandle.USER_SYSTEM) { //发送ACTION_USER_INITIALIZE广播去给user初始化 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE); intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); mInjector.broadcastIntent(intent, null, new IIntentReceiver.Stub() { @Override public void performReceive(Intent intent, int resultCode, String data, Bundle extras, boolean ordered, boolean sticky, int sendingUser) { // Note: performReceive is called with mService lock held mInjector.getUserManager().makeInitialized(userInfo.id); } }, 0, null, null, null, AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId); } } // Do not report secondary users, runtime restarts or first boot/upgrade //userId = 0 if (userId == UserHandle.USER_SYSTEM && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) { int uptimeSeconds = (int) (SystemClock.elapsedRealtime() / 1000); MetricsLogger.histogram(mInjector.getContext(), "framework_boot_completed", uptimeSeconds); } //发送ACTION_BOOT_COMPLETED广播 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null); bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); mInjector.broadcastIntent(bootIntent, null, new IIntentReceiver.Stub() { @Override public void performReceive(Intent intent, int resultCode, String data, Bundle extras, boolean ordered, boolean sticky, int sendingUser) throws RemoteException { Slog.i(UserController.TAG, "Finished processing BOOT_COMPLETED for u" + userId); } }, 0, null, null, new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED}, AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId); if (!SystemProperties.get("vendor.android.home.ready").equals("1")) { SystemProperties.set("vendor.android.home.ready", "1"); } Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { final Intent readyIntent = new Intent(Intent.ACTION_HOME_READY, null); readyIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); readyIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); mInjector.broadcastIntent(readyIntent, null, new IIntentReceiver.Stub() { @Override public void performReceive(Intent intent, int resultCode, String data, Bundle extras, boolean ordered, boolean sticky, int sendingUser) throws RemoteException { Slog.i(UserController.TAG, "Finished processing HOME_READY for u" + userId); } }, 0, null, null, new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED}, AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId); } }, 1000); // Delay 1s }
这里会发送ACTION_BOOT_COMPLETED,至此,才算真正的开机成功。
参考文章
-
《》
-
《》
-
《》