该系列文章总纲链接:专题分纲目录 Android SystemUI组件
本章关键点总结 & 说明:
说明:本章节持续迭代之前章节的思维导图,主要关注左侧上方锁屏分析部分 唤醒亮屏 即可。
Power按键的处理逻辑最终是由PhoneWindowManager来完成。想了解更多可参考输入子系统的相关文章。整理如下:
Android Framework 输入子系统(01)核心机制 inotify和epoll
Android Framework 输入子系统(02)核心机制 双向通信(socketpair+binder)
Android Framework 输入子系统(03)输入系统框架
Android Framework 输入子系统(04)InputReader解读
Android Framework 输入子系统(05)InputDispatcher解读
Android Framework 输入子系统(06)Global Key 一键启动 应用程序案例
Android Framework 输入子系统(07)APP建立联系
Android Framework 输入子系统(08)View基础(activity window decor view)
Android Framework 输入子系统(09)InputStage解读
Android Framework 输入子系统(10)Input命令解读
Android Framework 输入子系统(11)sendevent与getevent命令解读
本章我们只关注与Power按键相关的内容,InputManagerService处理的按键事件,最终会传递到PhoneWindowManager的interceptKeyBeforeQueueing方法中处理。我们就从这里入手逐步分析。
1 从PhoneWindowManager到PowerManagerService的处理
从PhoneWindowManager的interceptKeyBeforeQueueing方法入口开始分析,代码实现如下:
public class PhoneWindowManager implements WindowManagerPolicy {static final String TAG = "WindowManager";static final boolean DEBUG = false;//...public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {//...//表示屏幕是否点亮final boolean interactive = (policyFlags & FLAG_INTERACTIVE) != 0;final boolean down = event.getAction() == KeyEvent.ACTION_DOWN;final boolean canceled = event.isCanceled();//获取按键编码final int keyCode = event.getKeyCode();final boolean keyguardActive = (mKeyguardDelegate == null ? false :(interactive ?isKeyguardShowingAndNotOccluded() :mKeyguardDelegate.isShowing()));boolean isWakeKey = (policyFlags & WindowManagerPolicy.FLAG_WAKE) != 0|| event.isWakeKey();//...// Handle special keys.switch (keyCode) {//...case KeyEvent.KEYCODE_POWER: {result &= ~ACTION_PASS_TO_USER;isWakeKey = false; // wake-up will be handled separatelyif (down) {//亮屏 step1 按下power按键,亮屏流程interceptPowerKeyDown(event, interactive);} else {//抬起power按键interceptPowerKeyUp(event, interactive, canceled);}break;}case KeyEvent.KEYCODE_SLEEP: {result &= ~ACTION_PASS_TO_USER;if (!mPowerManager.isInteractive()) {useHapticFeedback = false; // suppress feedback if already non-interactive}mPowerManager.goToSleep(event.getEventTime(),PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);isWakeKey = false;break;}case KeyEvent.KEYCODE_WAKEUP: {result &= ~ACTION_PASS_TO_USER;isWakeKey = true;break;}//...}//...if (isWakeKey) {wakeUp(event.getEventTime(), mAllowTheaterModeWakeFromKey);}return result;}private void interceptPowerKeyDown(KeyEvent event, boolean interactive) {//...mPowerKeyHandled = hungUp || mScreenshotChordVolumeDownKeyTriggered|| mScreenshotChordVolumeUpKeyTriggered;if (!mPowerKeyHandled) {//交互模式,表示现在亮屏,点击后会走灭屏流程//当然,灭屏sleep的流程更多的处理在interceptPowerKeyUp中if (interactive) {if (hasLongPressOnPowerBehavior()) {Message msg = mHandler.obtainMessage(MSG_POWER_LONG_PRESS);msg.setAsynchronous(true);mHandler.sendMessageDelayed(msg,ViewConfiguration.get(mContext).getDeviceGlobalActionKeyTimeout());}} else {//亮屏 step2:非交互模式,表示现在灭屏,点击后会走亮屏流程wakeUpFromPowerKey(event.getDownTime());final int maxCount = getMaxMultiPressPowerCount();if (maxCount <= 1) {mPowerKeyHandled = true;} else {mBeganFromNonInteractive = true;}}}}private void wakeUpFromPowerKey(long eventTime) {//亮屏 step3 调用wakeUp方法wakeUp(eventTime, mAllowTheaterModeWakeFromPowerKey);}private boolean wakeUp(long wakeTime, boolean wakeInTheaterMode) {if (!wakeInTheaterMode && isTheaterModeEnabled()) {return false;}//亮屏 step4 走到PowerManagerService中的WakeUp方法中mPowerManager.wakeUp(wakeTime);return true;}
}
2 从PowerManagerService到Notifier的处理
从PhoneWindowManager的interceptKeyBeforeQueueing方法入口开始分析,最终会到达PowerManagerService的wakeUp方法(从PowerManager到PowerManagerService的调用就不在分析了,这个属于binder通信的范畴),对应的代码实现如下:
public final class PowerManagerService extends SystemServiceimplements Watchdog.Monitor {private static final String TAG = "PowerManagerService";private static final boolean DEBUG = false;//...private final class BinderService extends IPowerManager.Stub {//...@Override // Binder callpublic void wakeUp(long eventTime) {if (eventTime > SystemClock.uptimeMillis()) {throw new IllegalArgumentException("event time must not be in the future");}mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);final int uid = Binder.getCallingUid();final long ident = Binder.clearCallingIdentity();try {wakeUpInternal(eventTime, uid);} finally {Binder.restoreCallingIdentity(ident);}}//...}//...private void wakeUpInternal(long eventTime, int uid) {synchronized (mLock) {if (wakeUpNoUpdateLocked(eventTime, uid)) {updatePowerStateLocked();}}}//...private boolean wakeUpNoUpdateLocked(long eventTime, int uid) {if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE|| !mBootCompleted || !mSystemReady) {return false;}Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");try {switch (mWakefulness) {case WAKEFULNESS_ASLEEP:Slog.i(TAG, "Waking up from sleep (uid " + uid +")...");break;case WAKEFULNESS_DREAMING:Slog.i(TAG, "Waking up from dream (uid " + uid +")...");break;case WAKEFULNESS_DOZING:Slog.i(TAG, "Waking up from dozing (uid " + uid +")...");break;}mLastWakeTime = eventTime;setWakefulnessLocked(WAKEFULNESS_AWAKE, 0);userActivityNoUpdateLocked(eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);} finally {Trace.traceEnd(Trace.TRACE_TAG_POWER);}return true;}//...private void setWakefulnessLocked(int wakefulness, int reason) {if (mWakefulness != wakefulness) {finishWakefulnessChangeLocked();mWakefulness = wakefulness;mWakefulnessChanging = true;mDirty |= DIRTY_WAKEFULNESS;mNotifier.onWakefulnessChangeStarted(wakefulness, reason);}}//...
}
3 Notifier的处理
Notifier的处理包含2个层面,一个是发送SCREEN_ON的广播,通知其他子系统亮屏的消息。一个是通过PhoneWindowManager的处理来逐层执行对应回调onScreenTurnedOn方法。
3.1 从Notifier最终发送SCREEN_ON广播
针对发送广播的逻辑处理流程,代码逻辑流程如下:
final class Notifier {private static final String TAG = "PowerManagerNotifier";private static final boolean DEBUG = false;//...public void onWakefulnessChangeStarted(int wakefulness, int reason) {final boolean interactive = PowerManagerInternal.isInteractive(wakefulness);if (interactive) {handleWakefulnessChange(wakefulness, interactive, reason);} else {mLastReason = reason;}// Start input as soon as we start waking up or going to sleep.mInputManagerInternal.setInteractive(interactive);}//...private void handleWakefulnessChange(final int wakefulness, boolean interactive,final int reason) {//...// Handle changes in the overall interactive state.boolean interactiveChanged = false;synchronized (mLock) {// Broadcast interactive state changes.if (interactive) {// Waking up...interactiveChanged = (mActualInteractiveState != INTERACTIVE_STATE_AWAKE);if (interactiveChanged) {mActualInteractiveState = INTERACTIVE_STATE_AWAKE;mPendingWakeUpBroadcast = true;mHandler.post(new Runnable() {@Overridepublic void run() {EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, 0, 0, 0);mPolicy.wakingUp();}});updatePendingBroadcastLocked();}} else {//...}}//...}//...private void updatePendingBroadcastLocked() {if (!mBroadcastInProgress&& mActualInteractiveState != INTERACTIVE_STATE_UNKNOWN&& (mPendingWakeUpBroadcast || mPendingGoToSleepBroadcast|| mActualInteractiveState != mBroadcastedInteractiveState)) {mBroadcastInProgress = true;mSuspendBlocker.acquire();Message msg = mHandler.obtainMessage(MSG_BROADCAST);msg.setAsynchronous(true);mHandler.sendMessage(msg);}}//...private final class NotifierHandler extends Handler {public NotifierHandler(Looper looper) {super(looper, null, true /*async*/);}@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case MSG_BROADCAST:sendNextBroadcast();break;//...}}}//当设备从睡眠状态唤醒时,会发送 ACTION_SCREEN_ON 广播;当设备准备进入睡眠状态时,会发送 ACTION_SCREEN_OFF 广播。private void sendNextBroadcast() {final int powerState;synchronized (mLock) {//mBroadcastedInteractiveState相关处理//...mBroadcastStartTime = SystemClock.uptimeMillis();powerState = mBroadcastedInteractiveState;}EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, 1);// 根据电源状态发送相应的广播if (powerState == INTERACTIVE_STATE_AWAKE) {sendWakeUpBroadcast(); //发送唤醒广播} else {sendGoToSleepBroadcast(); //发送睡眠广播}}//...private void sendWakeUpBroadcast() {if (ActivityManagerNative.isSystemReady()) {// 发送广播关键API,参数解读如下:// mScreenOnIntent 是一个 Intent,包含了唤醒屏幕的信息// UserHandle.ALL 表示这个广播会发送给所有用户// mWakeUpBroadcastDone 是一个 BroadcastReceiver,用于在广播完成后接收回调// mHandler 是一个 Handler,用于处理广播完成后的回调// 0 是一个 flags,表示广播的权限// 最后的 null, null 是额外的参数,这里没有使用mContext.sendOrderedBroadcastAsUser(mScreenOnIntent, UserHandle.ALL, null,mWakeUpBroadcastDone, mHandler, 0, null, null);} else {EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2, 1);sendNextBroadcast();}}//...
}
3.2 PhoneWindowManager.wakingUp方法逐层处理亮屏回调方法
这里主要是从到PhoneWindowManager的wakingUp(policy.wakingUp)方法,再到各层的onScreenTurnedOn方法的处理逻辑流程,从onWakefulnessChangeStarted处开始,代码实现如下:
//Notifier处理
final class Notifier {private static final String TAG = "PowerManagerNotifier";private static final boolean DEBUG = false;//...public void onWakefulnessChangeStarted(int wakefulness, int reason) {final boolean interactive = PowerManagerInternal.isInteractive(wakefulness);if (interactive) {handleWakefulnessChange(wakefulness, interactive, reason);} else {mLastReason = reason;}// Start input as soon as we start waking up or going to sleep.mInputManagerInternal.setInteractive(interactive);}//...private void handleWakefulnessChange(final int wakefulness, boolean interactive,final int reason) {//...// Handle changes in the overall interactive state.boolean interactiveChanged = false;synchronized (mLock) {// Broadcast interactive state changes.if (interactive) {// Waking up...interactiveChanged = (mActualInteractiveState != INTERACTIVE_STATE_AWAKE);if (interactiveChanged) {mActualInteractiveState = INTERACTIVE_STATE_AWAKE;mPendingWakeUpBroadcast = true;mHandler.post(new Runnable() {@Overridepublic void run() {EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, 0, 0, 0);mPolicy.wakingUp();//这里是处理的关键}});updatePendingBroadcastLocked();}} else {//...}}//...}//...
}
这里会调用到PhoneWindowManager的wakingUp方法。代码实现如下:
//phonewindowmanager@Overridepublic void wakingUp() {synchronized (mLock) {mAwake = true;mKeyguardDrawComplete = false;if (mKeyguardDelegate != null) {mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT, 1000);}updateWakeGestureListenerLp();updateOrientationListenerLp();updateLockScreenTimeout();}if (mKeyguardDelegate != null) {mKeyguardDelegate.onScreenTurnedOn(mKeyguardDelegateCallback);// ... eventually calls finishKeyguardDrawn} else {finishKeyguardDrawn();}}
这里会调用到KeyguardDelegate的onScreenTurnedOn方法。代码实现如下:
//KeyguardDelegatepublic void onScreenTurnedOn(final ShowListener showListener) {if (mKeyguardService != null) {mKeyguardService.onScreenTurnedOn(new KeyguardShowDelegate(showListener));} else {// try again when we establish a connectionSlog.w(TAG, "onScreenTurnedOn(): no keyguard service!");// This shouldn't happen, but if it does, show the scrim immediately and// invoke the listener's callback after the service actually connects.mShowListenerWhenConnect = showListener;showScrim();}mKeyguardState.screenIsOn = true;}
这里会调用到KeyguardServiceWrapper的onScreenTurnedOn方法。代码实现如下:
//wrapper@Override // Binder interfacepublic void onScreenTurnedOn(IKeyguardShowCallback result) {try {mService.onScreenTurnedOn(result);} catch (RemoteException e) {Slog.w(TAG , "Remote Exception", e);}}
这里会调用到KeyguardService的onScreenTurnedOn方法。代码实现如下:
//KeyguardService//binder@Override // Binder interfacepublic void onScreenTurnedOn(IKeyguardShowCallback callback) {checkPermission();mKeyguardViewMediator.onScreenTurnedOn(callback);}
这里会调用到KeyguardViewMediator的onScreenTurnedOn方法。这里才是真正的逻辑实现,代码实现如下:
//KeyguardViewMediator
public void onScreenTurnedOn(IKeyguardShowCallback callback) {synchronized (this) {// 将屏幕状态设置为开启mScreenOn = true;// 取消任何计划的延迟显示锁屏任务cancelDoKeyguardLaterLocked();// 如果提供了回调,通知屏幕已点亮if (callback != null) {notifyScreenOnLocked(callback);}}// 通知KeyguardUpdateMonitor屏幕已被点亮KeyguardUpdateMonitor.getInstance(mContext).dispatchScreenTurnedOn();// 可能发送一个用户存在的广播,表示用户已经与设备交互maybeSendUserPresentBroadcast();
}
这里总结下,onScreenTurnedOn关键逻辑解读如下:
- 当屏幕再次打开时,这个方法会被调用。
- 首先会调用 cancelDoKeyguardLaterLocked 方法,这个方法会取消任何之前计划的延迟显示锁屏任务。
- 如果提供了回调接口,会通过 notifyScreenOnLocked 方法通知系统屏幕已经打开。
- KeyguardUpdateMonitor 会分派屏幕已打开的事件。
- maybeSendUserPresentBroadcast 方法可能会发送一个用户存在的广播,这通常意味着设备已解锁。
3.3 cancelDoKeyguardLaterLocked的处理
cancelDoKeyguardLaterLocked的代码实现如下:
//KeyguardViewMediatorprivate void cancelDoKeyguardLaterLocked() {mDelayedShowingSequence++;}
注意,在灭屏处理的时候有可能会调用到doKeyguardLaterLocked方法,代码实现如下:
//KeyguardViewMediator// 在锁定屏幕之前给予一定延迟的方法private void doKeyguardLaterLocked() {final ContentResolver cr = mContext.getContentResolver();// 读取显示设置中的屏幕关闭超时时间long displayTimeout = Settings.System.getInt(cr, SCREEN_OFF_TIMEOUT,KEYGUARD_DISPLAY_TIMEOUT_DELAY_DEFAULT);// 读取安全设置中的锁屏超时时间final long lockAfterTimeout = Settings.Secure.getInt(cr,Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT,KEYGUARD_LOCK_AFTER_DELAY_DEFAULT);// 从设备策略管理器获取设备策略超时时间final long policyTimeout = mLockPatternUtils.getDevicePolicyManager().getMaximumTimeToLock(null, mLockPatternUtils.getCurrentUser());long timeout;if (policyTimeout > 0) {// 如果设备策略超时时间有效,则取屏幕关闭超时时间和设备策略超时时间的较小值// 但不超过锁屏超时时间displayTimeout = Math.max(displayTimeout, 0); // 忽略负值timeout = Math.min(policyTimeout - displayTimeout, lockAfterTimeout);} else {// 如果没有设备策略限制,则使用锁屏超时时间timeout = lockAfterTimeout;}if (timeout <= 0) {// 如果计算出的延迟时间小于等于0,立即锁定屏幕mSuppressNextLockSound = true; // 抑制锁屏声音doKeyguardLocked(null); // 立即执行锁屏} else {// 如果延迟时间大于0,则设置一个闹钟,在将来的某个时间点锁定屏幕long when = SystemClock.elapsedRealtime() + timeout; // 计算闹钟触发的时间Intent intent = new Intent(DELAYED_KEYGUARD_ACTION);intent.putExtra("seq", mDelayedShowingSequence);// 创建一个PendingIntent,当闹钟触发时,系统将通过这个PendingIntent发送一个广播PendingIntent sender = PendingIntent.getBroadcast(mContext,0, intent, PendingIntent.FLAG_CANCEL_CURRENT);mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, sender); // 设置闹钟}}
在这段代码逻辑的最后,会创建一个PendingIntent,当闹钟触发时,系统将通过这个PendingIntent发送一个广播DELAYED_KEYGUARD_ACTION。然后通过一个广播接收器来处理该广播消息,处理相关代码如下:
//KeyguardViewMediator//systemReady后开始执行private void setup() {//...注册接收DELAYED_KEYGUARD_ACTION广播消息的ReceivermContext.registerReceiver(mBroadcastReceiver, new IntentFilter(DELAYED_KEYGUARD_ACTION));//...}// 定义一个广播接收器,用于接收特定动作的广播private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {// 检查接收到的Intent是否是延迟锁屏的动作if (DELAYED_KEYGUARD_ACTION.equals(intent.getAction())) {// 从Intent中获取序列号final int sequence = intent.getIntExtra("seq", 0);synchronized (KeyguardViewMediator.this) {// 检查接收到的序列号是否与当前的延迟显示序列号相匹配if (mDelayedShowingSequence == sequence) {// 如果序列号匹配,表示该广播是有效的,需要显示锁屏// 标记不播放锁屏音效,因为这是自动锁屏,不是由用户直接触发的mSuppressNextLockSound = true;// 调用doKeyguardLocked方法显示锁屏doKeyguardLocked(null);}}}}};//...
在Android系统中,这里的BroadcastReceiver
是异步的,这意味着它可能会在任何时候接收到广播消息,而且接收顺序并不是完全可以预测的。有可能在屏幕关闭后,系统发送了延迟显示锁屏的广播,而这个广播在屏幕亮起并且onScreenTurnedOn
方法被调用之后才被接收到。这里是可能发生的情况解读如下:
-
屏幕关闭:
onScreenTurnedOff
被调用,可能会通过doKeyguardLaterLocked
方法发送一个延迟显示锁屏的广播。 -
延迟广播发送:系统安排了一个延迟任务,将在一定时间后发送
DELAYED_KEYGUARD_ACTION
的广播。 -
屏幕亮起:用户按下电源键或其他方式唤醒屏幕,
onScreenTurnedOn
被调用。 -
取消延迟任务:
onScreenTurnedOn
中调用cancelDoKeyguardLaterLocked
,这通常会增加mDelayedShowingSequence
的值,使得之前的延迟显示锁屏任务失效。 -
广播接收:如果在
onScreenTurnedOn
调用cancelDoKeyguardLaterLocked
之后,但锁屏显示之前,之前发送的DELAYED_KEYGUARD_ACTION
广播被接收,那么BroadcastReceiver
中的代码会检查序列号。 -
序列号检查:如果
mDelayedShowingSequence
的值没有变化,或者变化没有被正确地传递到BroadcastReceiver
,那么if (mDelayedShowingSequence == sequence)
的条件仍然成立,doKeyguardLocked(null)
会被调用,锁屏界面会显示。 -
锁屏显示:如果序列号匹配,即使
onScreenTurnedOn
已经调用,锁屏界面仍然会显示。
这个流程说明,尽管onScreenTurnedOn
方法被调用且可能取消了延迟显示锁屏的任务,但如果广播在取消之后才被接收,锁屏界面仍有可能显示。这就是为什么在实际设备上,您可能会遇到即使屏幕很快被点亮,锁屏界面仍然会显示的情况。
3.4 关于亮屏后锁屏处理的总结
如果在屏幕关闭时没有立即锁屏,然后在屏幕打开时执行 onScreenTurnedOn:
- mScreenOn 会被设置为 true,表示屏幕现在是开启状态。
- cancelDoKeyguardLaterLocked 会被调用,取消任何延迟显示锁屏的任务。
- 如果没有其他条件阻止锁屏显示(例如,用户正在解锁设备或设备已解锁),则锁屏界面通常会显示。
在 onScreenTurnedOn 方法中,没有直接调用 doKeyguardLocked方法来显示锁屏。但是,如果系统配置要求在屏幕打开时显示锁屏(例如,设备是安全的且用户没有在解锁过程中),则锁屏界面可能会通过其他机制显示。
总结来说,如果在屏幕关闭时没有锁屏,然后在屏幕打开时执行 onScreenTurnedOn 方法,并且没有其他条件阻止锁屏显示,那么锁屏界面应该会显示。这是为了保证设备的安全性,特别是在设备已经配置了安全措施(如PIN、密码、图案)的情况下。