在PowerManagerService中对各种状态进行判断后,将其数值封装进DisplayPowerRequest中传入DisplayPowerController中进一步处理。在亮屏过程中DisplayPowerController会根据传过来的数值来设置新的电源状态为亮屏,然后调用DisplayPowerState来对状态进行设置,在分析DisplayPowerState时会具体讲解。由于此时ColorFade level(就是在手机屏幕的一层surface,当level为0是为一层黑帧,level为1.0时为透明)的值为0,表示屏幕还没有绘制好,所以此时需要block screen直到window界面绘制完成。当需要亮屏时调用PhoneWindowManager的screenTurningOn函数,通知window屏幕就要点亮了。然后调用WMS中函数waitForAllWindowsDrawn函数等待将所有需要绘制的window绘制完成后回调回来,超时时间为1000ms。在WMS中获取需要绘制的window将其加入mWaitingForDrawn中等待绘制,通过检查mWaitingForDrawn是否为空来判断,window是否绘制完成。此时screenTurningOn函数就执行完了,剩下的就是等待windows绘制完成。
DisplayManagerService.java中的LocalService继承了DisplayManagerInternal.java, 所以就会调用LocalService的requestPowerState函数请求电源状态.
- private final class LocalService extends DisplayManagerInternal {
- @Override
- public void initPowerManagement(final DisplayPowerCallbacks callbacks, Handler handler,
- SensorManager sensorManager) { //初始化函数在PowerManagerService的systemReady函数中调用
- synchronized (mSyncRoot) {
- DisplayBlanker blanker = new DisplayBlanker() { //创建blanker对象
- @Override
- public void requestDisplayState(int state, int brightness) {
- // The order of operations is important for legacy reasons.
- if (state == Display.STATE_OFF) {
- requestGlobalDisplayStateInternal(state, brightness);
- }
- callbacks.onDisplayStateChange(state);
- if (state != Display.STATE_OFF) {
- requestGlobalDisplayStateInternal(state, brightness);
- }
- }
- };
- mDisplayPowerController = new DisplayPowerController( //创建DisplayPowerController对象
- mContext, callbacks, handler, sensorManager, blanker);
- }
- }
- @Override
- public boolean requestPowerState(DisplayPowerRequest request,
- boolean waitForNegativeProximity) {
- return mDisplayPowerController.requestPowerState(request,
- waitForNegativeProximity); //调用DisplayPowerController请求电源状态
- }
- //.....
在DisplayPowerController中通过Handler发送MSG_UPDATE_POWER_STATE消息调用updatePowerState来更新电源状态. updatePowerState也是一个非常核心的函数,在该函数中将PowerManagerService中传过来的参数获取出来根据policy获取设备的请求状态是ON, OFF还是DOZE, 应用距离传感器, 将最终的请求状态调用DisplayPowerState进行设置. 判断设备是否打开了自动亮度调节, 计算最终屏幕要达到的目标亮度并通过亮度渐变动画慢慢的点亮屏幕,最终变为高亮.
- private void updatePowerState() {
- // Update the power state request.
- final boolean mustNotify;
- boolean mustInitialize = false;
- boolean autoBrightnessAdjustmentChanged = false;
- synchronized (mLock) {
- mPendingUpdatePowerStateLocked = false;
- if (mPendingRequestLocked == null) {
- return; // wait until first actual power request
- }
- if (mPowerRequest == null) { //判断mPowerRequest是否为NULL,如果为空新创建一个, 否则直接将mPendingRequestLocked复制给他
- mPowerRequest = new DisplayPowerRequest(mPendingRequestLocked);
- mWaitingForNegativeProximity = mPendingWaitForNegativeProximityLocked;
- mPendingWaitForNegativeProximityLocked = false;
- mPendingRequestChangedLocked = false;
- mustInitialize = true;
- } else if (mPendingRequestChangedLocked) {
- autoBrightnessAdjustmentChanged = (mPowerRequest.screenAutoBrightnessAdjustment
- != mPendingRequestLocked.screenAutoBrightnessAdjustment);
- mPowerRequest.copyFrom(mPendingRequestLocked);
- mWaitingForNegativeProximity |= mPendingWaitForNegativeProximityLocked;
- mPendingWaitForNegativeProximityLocked = false;
- mPendingRequestChangedLocked = false;
- mDisplayReadyLocked = false;
- }
- mustNotify = !mDisplayReadyLocked;
- }
- // Initialize things the first time the power state is changed.
- if (mustInitialize) {
- initialize();//power state第一次发生变化时需要做一些初始化,如:创建DisplayPowerState, 亮灭屏动画,亮度渐变动画实例等
- }
- // Compute the basic display state using the policy.
- // We might override this below based on other factors.
- int state;
- int brightness = PowerManager.BRIGHTNESS_DEFAULT;//设置屏幕默认亮度
- boolean performScreenOffTransition = false;
- switch (mPowerRequest.policy) {
- case DisplayPowerRequest.POLICY_OFF: //设置设备状态为OFF
- state = Display.STATE_OFF;
- performScreenOffTransition = true; //灭屏有过渡动画
- break;
- case DisplayPowerRequest.POLICY_DOZE: //设置设备状态为DOZE
- if (mPowerRequest.dozeScreenState != Display.STATE_UNKNOWN) {
- state = mPowerRequest.dozeScreenState;
- } else {
- state = Display.STATE_DOZE;
- }
- if (!mAllowAutoBrightnessWhileDozingConfig) {
- brightness = mPowerRequest.dozeScreenBrightness;//如果在xml文件中配置了相关属性,就将dozeScreenBrightness赋给亮度值
- }
- break;
- case DisplayPowerRequest.POLICY_DIM:
- case DisplayPowerRequest.POLICY_BRIGHT:
- default:
- state = Display.STATE_ON;//如果policy为DIM, BRIGHT的话,设备状态都为ON
- break;
- }
- assert(state != Display.STATE_UNKNOWN);
- // Apply the proximity sensor.
- if (mProximitySensor != null) { //距离传感器相关处理
- if (mPowerRequest.useProximitySensor && state != Display.STATE_OFF) {
- setProximitySensorEnabled(true);
- if (!mScreenOffBecauseOfProximity
- && mProximity == PROXIMITY_POSITIVE) {
- mScreenOffBecauseOfProximity = true;
- sendOnProximityPositiveWithWakelock();
- }
- } else if (mWaitingForNegativeProximity
- && mScreenOffBecauseOfProximity
- && mProximity == PROXIMITY_POSITIVE
- && state != Display.STATE_OFF) {
- setProximitySensorEnabled(true);
- } else {
- setProximitySensorEnabled(false);
- mWaitingForNegativeProximity = false;
- }
- if (mScreenOffBecauseOfProximity
- && mProximity != PROXIMITY_POSITIVE) {
- mScreenOffBecauseOfProximity = false;
- sendOnProximityNegativeWithWakelock();
- }
- } else {
- mWaitingForNegativeProximity = false;
- }
- if (mScreenOffBecauseOfProximity) {
- state = Display.STATE_OFF;//如果因为距离传感器灭屏设置设备状态为OFF
- }
- // Animate the screen state change unless already animating.
- // The transition may be deferred, so after this point we will use the
- // actual state instead of the desired one.
- animateScreenStateChange(state, performScreenOffTransition);//处理屏幕状态改变
- state = mPowerState.getScreenState();//获取新的屏幕状态
- // Use zero brightness when screen is off.
- if (state == Display.STATE_OFF) {
- brightness = PowerManager.BRIGHTNESS_OFF; //如果新的状态是灭屏的话设置brightness为0
- }
- // Configure auto-brightness.
- boolean autoBrightnessEnabled = false;
- if (mAutomaticBrightnessController != null) {
- final boolean autoBrightnessEnabledInDoze = mAllowAutoBrightnessWhileDozingConfig
- && (state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND);
- autoBrightnessEnabled = mPowerRequest.useAutoBrightness
- && (state == Display.STATE_ON || autoBrightnessEnabledInDoze)
- && brightness < 0;
- final boolean userInitiatedChange = autoBrightnessAdjustmentChanged
- && mPowerRequest.brightnessSetByUser;
- mAutomaticBrightnessController.configure(autoBrightnessEnabled,
- mPowerRequest.screenAutoBrightnessAdjustment, state != Display.STATE_ON,
- userInitiatedChange, mPowerRequest.useTwilight);//配置控制自动亮度设置的对象
- }
- // Apply brightness boost.
- // We do this here after configuring auto-brightness so that we don't
- // disable the light sensor during this temporary state. That way when
- // boost ends we will be able to resume normal auto-brightness behavior
- // without any delay.
- if (mPowerRequest.boostScreenBrightness
- && brightness != PowerManager.BRIGHTNESS_OFF) {
- brightness = PowerManager.BRIGHTNESS_ON;
- }
- // Apply auto-brightness.
- boolean slowChange = false;
- if (brightness < 0) {
- if (autoBrightnessEnabled) {
- brightness = mAutomaticBrightnessController.getAutomaticScreenBrightness();//获取自动亮度值
- }
- if (brightness >= 0) {
- // Use current auto-brightness value and slowly adjust to changes.
- brightness = clampScreenBrightness(brightness);//保证亮度值的有效性,不能在0~255之外
- if (mAppliedAutoBrightness && !autoBrightnessAdjustmentChanged) {
- slowChange = true; // slowly adapt to auto-brightness
- }
- mAppliedAutoBrightness = true;//使用了自动亮度
- } else {
- mAppliedAutoBrightness = false;//没有使用自动亮度
- }
- } else {
- mAppliedAutoBrightness = false;
- }
- // Use default brightness when dozing unless overridden.
- if (brightness < 0 && (state == Display.STATE_DOZE
- || state == Display.STATE_DOZE_SUSPEND)) {
- brightness = mScreenBrightnessDozeConfig;
- }
- // Apply manual brightness.
- // Use the current brightness setting from the request, which is expected
- // provide a nominal default value for the case where auto-brightness
- // is not ready yet.
- if (brightness < 0) {
- brightness = clampScreenBrightness(mPowerRequest.screenBrightness);//如果亮度值小于0的话,就是用setting中设置的亮度值
- }
- // Apply dimming by at least some minimum amount when user activity
- // timeout is about to expire.
- if (mPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
- if (brightness > mScreenBrightnessRangeMinimum) {
- brightness = Math.max(Math.min(brightness - SCREEN_DIM_MINIMUM_REDUCTION,
- mScreenBrightnessDimConfig), mScreenBrightnessRangeMinimum);
- }
- if (!mAppliedDimming) {
- slowChange = false;
- }
- mAppliedDimming = true;
- } else if (mAppliedDimming) {
- slowChange = false;
- mAppliedDimming = false;
- }
- // If low power mode is enabled, cut the brightness level by half
- // as long as it is above the minimum threshold.
- if (mPowerRequest.lowPowerMode) {
- if (brightness > mScreenBrightnessRangeMinimum) {
- brightness = Math.max(brightness / 2, mScreenBrightnessRangeMinimum);//低电模式, 亮度是目标亮度的1/2
- }
- if (!mAppliedLowPower) {
- slowChange = false;
- }
- mAppliedLowPower = true;
- } else if (mAppliedLowPower) {
- slowChange = false;
- mAppliedLowPower = false;
- }
- // Animate the screen brightness when the screen is on or dozing.
- // Skip the animation when the screen is off or suspended.
- if (!mPendingScreenOff) {
- if (state == Display.STATE_ON || state == Display.STATE_DOZE) {
- animateScreenBrightness(brightness,
- slowChange ? BRIGHTNESS_RAMP_RATE_SLOW : mBrightnessRampRateFast);//使用亮度渐变动画设置亮度, 渐变速度依赖于rate
- } else {
- animateScreenBrightness(brightness, 0);//动画速率为0, 没有动画
- }
- }
- //..........
- }
根据上面代码分析在updatePowerState中主要做的事情主要有两件事:
1.调用animateScreenStateChange函数处理屏幕状态变化
2.调用animateScreenBrightness函数设置屏幕亮度
下面将详细讲解这两件事情:
animateScreenStateChange函数处理屏幕状态变化
- private void animateScreenStateChange(int target, boolean performScreenOffTransition) {
- // If there is already an animation in progress, don't interfere with it.
- if (mColorFadeOnAnimator.isStarted()
- || mColorFadeOffAnimator.isStarted()) {
- if (target != Display.STATE_ON) {
- return; //如果此时有亮灭屏动画, 并且目标状态不是ON,就返回.
- }
- // If display state changed to on, proceed and stop the color fade and turn screen on.
- mPendingScreenOff = false;
- }
- // If we were in the process of turning off the screen but didn't quite
- // finish. Then finish up now to prevent a jarring transition back
- // to screen on if we skipped blocking screen on as usual.
- if (mPendingScreenOff && target != Display.STATE_OFF) {
- setScreenState(Display.STATE_OFF);
- mPendingScreenOff = false;
- mPowerState.dismissColorFadeResources();
- }
- if (target == Display.STATE_ON) { //亮屏
- // Want screen on. The contents of the screen may not yet
- // be visible if the color fade has not been dismissed because
- // its last frame of animation is solid black.
- if (!setScreenState(Display.STATE_ON)) { //设置屏幕状态,如果返回false就blocked亮屏, 不能往下执行
- return; // screen on blocked
- }
- if (USE_COLOR_FADE_ON_ANIMATION && mPowerRequest.isBrightOrDim()) {
- // Perform screen on animation.
- if (mPowerState.getColorFadeLevel() == 1.0f) { //执行亮屏动画, 将Color Fade level渐变为1.0f
- mPowerState.dismissColorFade();
- } else if (mPowerState.prepareColorFade(mContext,
- mColorFadeFadesConfig ?
- ColorFade.MODE_FADE :
- ColorFade.MODE_WARM_UP)) {
- mColorFadeOnAnimator.start();
- } else {
- mColorFadeOnAnimator.end();
- }
- } else {
- // Skip screen on animation.
- mPowerState.setColorFadeLevel(1.0f); //跳过亮屏, 直接设置Color Fade level为1.0f
- mPowerState.dismissColorFade();
- }
- //...........
- } else {
- // Want screen off. //灭屏
- mPendingScreenOff = true;
- if (mPowerState.getColorFadeLevel() == 0.0f) {
- // Turn the screen off.
- // A black surface is already hiding the contents of the screen.
- setScreenState(Display.STATE_OFF); //如果Color Fade level为0.0f, 设置屏幕状态为OFF
- mPendingScreenOff = false;
- mPowerState.dismissColorFadeResources();
- } else if (performScreenOffTransition //performScreenOffTransition为true, 有灭屏过渡动画
- && mPowerState.prepareColorFade(mContext,
- mColorFadeFadesConfig ?
- ColorFade.MODE_FADE : ColorFade.MODE_COOL_DOWN)
- && mPowerState.getScreenState() != Display.STATE_OFF) {
- // Perform the screen off animation.
- mColorFadeOffAnimator.start(); //灭屏动画,Color fade leve慢慢将1.0变为0.0f
- } else {
- // Skip the screen off animation and add a black surface to hide the
- // contents of the screen.
- mColorFadeOffAnimator.end(); //跳过灭屏动画
- }
- }
- }
在上面函数中主要就是调用setScreenState设置屏幕状态, 只有设置好状态并且setScreenState返回true,之后才会判断是否有亮度渐变动画将Color Fade Level设置为1.0f. 否则一直会阻塞在setScreenState函数上.
- private boolean setScreenState(int state) {
- if (mPowerState.getScreenState() != state) {
- final boolean wasOn = (mPowerState.getScreenState() != Display.STATE_OFF);
- mPowerState.setScreenState(state); //调用DisplayPowerState设置屏幕状态
- // Tell battery stats about the transition.
- try {
- mBatteryStats.noteScreenState(state);
- } catch (RemoteException ex) {
- // same process
- }
- }
- // Tell the window manager policy when the screen is turned off or on unless it's due
- // to the proximity sensor. We temporarily block turning the screen on until the
- // window manager is ready by leaving a black surface covering the screen.
- // This surface is essentially the final state of the color fade animation and
- // it is only removed once the window manager tells us that the activity has
- // finished drawing underneath.
- final boolean isOff = (state == Display.STATE_OFF); //是否是灭屏状态
- if (isOff && mReportedScreenStateToPolicy != REPORTED_TO_POLICY_SCREEN_OFF
- && !mScreenOffBecauseOfProximity) {
- mReportedScreenStateToPolicy = REPORTED_TO_POLICY_SCREEN_OFF;
- unblockScreenOn();
- mWindowManagerPolicy.screenTurnedOff();
- PMSFactory.getInstance().createExtraDisplayPowerState(mContext).setButtonOn(false);
- } else if (!isOff && mReportedScreenStateToPolicy == REPORTED_TO_POLICY_SCREEN_OFF) {
- mReportedScreenStateToPolicy = REPORTED_TO_POLICY_SCREEN_TURNING_ON;
- if (mPowerState.getColorFadeLevel() == 0.0f) { //亮屏处理, 此时Colorfade level为0.0f 为true
- blockScreenOn(); //block亮屏, 创建一个mPendingScreenOnUnblocker对象
- } else {
- unblockScreenOn(); //将创建的mPendingScreenOnUnblocker对象销毁,设置NULL
- }
- mWindowManagerPolicy.screenTurningOn(mPendingScreenOnUnblocker); //调用PhoneWindowManager进行处理
- if (PMSFactory.getInstance().createExtraDisplayPowerController(mContext).getButtonTimeout() != -2){
- PMSFactory.getInstance().createExtraDisplayPowerState(mContext).setButtonOn(true);
- }
- }
- // Return true if the screen isn't blocked.
- return mPendingScreenOnUnblocker == null; //blockScreenOn时创建一个mPendingScreenOnUnblocker对象,所以返回false, block亮屏
- }
- private void blockScreenOn() {
- if (mPendingScreenOnUnblocker == null) {
- Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, SCREEN_ON_BLOCKED_TRACE_NAME, 0);
- mPendingScreenOnUnblocker = new ScreenOnUnblocker();
- mScreenOnBlockStartRealTime = SystemClock.elapsedRealtime(); //开始blocked亮屏的时间
- Slog.i(TAG, "Blocking screen on until initial contents have been drawn.");
- }
- }
- private void unblockScreenOn() {
- if (mPendingScreenOnUnblocker != null) {
- mPendingScreenOnUnblocker = null;
- long delay = SystemClock.elapsedRealtime() - mScreenOnBlockStartRealTime;
- Slog.i(TAG, "Unblocked screen on after " + delay + " ms"); //输出log,一共block亮屏多长时间
- Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, SCREEN_ON_BLOCKED_TRACE_NAME, 0);
- }
- }
在setScreenState函数中主要做了两件事情:
1.调用DisplayPowerState对屏幕状态进行设置
2.通知PhoneWindowManager对keyguard和windows进行绘制.
设置屏幕状态
当设置屏幕状态时,如果新状态与之前的状态不同时就会将新的状态值记录在成员变量mScreenState中,这样可以让其它类来获取当前的屏幕状态。之后在一个Runnable对象的run函数中根据屏幕状态与ColorFade level来进行获取屏幕亮度,此时是亮屏操作但是windows尚未绘制完成level仍然是0.0,此时获取的亮度值为0,由此可知,只要windows绘制不完成亮度值会一直为0,即屏幕不会亮。
- private final Runnable mScreenUpdateRunnable = new Runnable() {
- @Override
- public void run() {
- mScreenUpdatePending = false;
- int brightness = mScreenState != Display.STATE_OFF
- && mColorFadeLevel > 0f ? mScreenBrightness : 0; //根据屏幕状态设置亮度值, 亮屏时如果color Fade Level为0.0f, brightness一直为0,不会亮屏
- if (mPhotonicModulator.setState(mScreenState, brightness)) {
- if (DEBUG) {
- Slog.d(TAG, "Screen ready");
- }
- mScreenReady = true;
- invokeCleanListenerIfNeeded();
- } else {
- if (DEBUG) {
- Slog.d(TAG, "Screen not ready");
- }
- }
- }
- };
- public void run() {
- for (;;) {
- // Get pending change.
- final int state;
- final boolean stateChanged;
- final int backlight;
- final boolean backlightChanged;
- synchronized (mLock) {
- state = mPendingState;
- stateChanged = (state != mActualState);
- backlight = mPendingBacklight;
- backlightChanged = (backlight != mActualBacklight);
- if (!stateChanged) { //判断状态是否变化
- // State changed applied, notify outer class.
- postScreenUpdateThreadSafe();
- mStateChangeInProgress = false;
- }
- if (!backlightChanged) {
- mBacklightChangeInProgress = false;
- }
- if (!stateChanged && !backlightChanged) { //如果亮度,状态都没有改变线程将wait
- try {
- mLock.wait();
- } catch (InterruptedException ex) { }
- continue;
- }
- mActualState = state; //获取确实的状态.亮度
- mActualBacklight = backlight;
- }
- // Apply pending change.
- if (DEBUG) {
- Slog.d(TAG, "Updating screen state: state="
- + Display.stateToString(state) + ", backlight=" + backlight);
- }
- mBlanker.requestDisplayState(state, backlight); //mBlanker为DisplayManagerService中创建的对象,前面有提到.
- }
- }
在DisplayManagerSerice中的LocalService初始化函数initPowerManagement中创建的mBlanker, 所以就调用他的requestDisplayState函数
- DisplayBlanker blanker = new DisplayBlanker() {
- @Override
- public void requestDisplayState(int state, int brightness) {
- // The order of operations is important for legacy reasons.
- if (state == Display.STATE_OFF) {
- requestGlobalDisplayStateInternal(state, brightness); //灭屏先调用该函数
- }
- callbacks.onDisplayStateChange(state); //callbacks为PowerManagerService中对象
- if (state != Display.STATE_OFF) {
- requestGlobalDisplayStateInternal(state, brightness); //亮屏调用该处函数
- }
- }
- };
在此处先讲解回调PowerManagerService的onDisplayStateChange函数做了那些事情,耗时点在什么地方. 在该函数中会首先获取一个mLock的锁,这把锁是不是很熟悉,我们在前面讲绘制windows流程的时候window与power交互时需要获取mLock,如果该锁被别的线程持有,window绘制流程就会阻塞。而根据上面流程可以看出,请求设备状态是在绘制window之前发生的,所以调用函数onDisplayStateChange没有结束的话,该锁就一直被持有,导致window绘制流程不能及时返回。
- public void onDisplayStateChange(int state) {
- // This method is only needed to support legacy display blanking behavior
- // where the display's power state is coupled to suspend or to the power HAL.
- // The order of operations matters here.
- synchronized (mLock) { //获取mLock锁
- if (mDisplayState != state) {
- mDisplayState = state;
- if (state == Display.STATE_OFF) { //灭屏
- if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
- setHalInteractiveModeLocked(false);
- }
- if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
- setHalAutoSuspendModeLocked(true);
- }
- } else { //亮屏
- if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
- setHalAutoSuspendModeLocked(false); //设置自动suspend模式
- }
- if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
- setHalInteractiveModeLocked(true); //设置hal交互模式
- }
- }
- }
- }
- }
- private void setHalAutoSuspendModeLocked(boolean enable) {
- if (enable != mHalAutoSuspendModeEnabled) {
- if (DEBUG) {
- Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
- }
- mHalAutoSuspendModeEnabled = enable;
- Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
- try {
- nativeSetAutoSuspend(enable); //调用JNI设置
- } finally {
- Trace.traceEnd(Trace.TRACE_TAG_POWER);
- }
- }
- }
- static void nativeSetAutoSuspend(JNIEnv* /* env */, jclass /* clazz */, jboolean enable) {
- if (enable) {
- ALOGD_IF_SLOW(100, "Excessive delay in autosuspend_enable() while turning screen off"); //灭屏执行超过100ms,会输出log
- autosuspend_enable();
- } else {
- ALOGD_IF_SLOW(100, "Excessive delay in autosuspend_disable() while turning screen on"); //亮屏执行该函数超过100ms, 会输出该行log
- autosuspend_disable();
- }
- }
而在亮屏时调用autosuspend_disable()是往/sys/power/state写 on(亮屏)的函数。在往节点写入状态后,调用late_resume将LCD resume,关于late_resume 阶段 “sprdfb_dispc_resume”函数执行时间可能由于手机硬件信息的不同,导致执行时间相差较大。
上面执行完之后,现在重新回到DMS中继续向下进行执行。
在DMS中通过变量mGlobalDisplayState进行记录当前的设备状态,如果设备状态发生改变时就会重新记录,之后更新设备状态将device对应的Runnable放入队列。然后就会将Runnable从队列中取出执行run函数。根据dumpsys信息可以知道,设备信息中只有一个设备“内置屏幕”,并且对应的Adapter为LocalDisplayAdapter,所以就会调用LocalDisplayAdapter中的run函数。在run函数中会调用SurfaceControl中的setDisplayPowerMode函数处理。最终到JNI中,此处也有可能发生超时,也可从输出log中看出。
- static void nativeSetDisplayPowerMode(JNIEnv* env, jclass clazz, jobject tokenObj, jint mode) {
- sp<IBinder> token(ibinderForJavaObject(env, tokenObj));
- if (token == NULL) return;
- ALOGD_IF_SLOW(100, "Excessive delay in setPowerMode()");
- SurfaceComposerClient::setDisplayPowerMode(token, mode);
- }
- void SurfaceComposerClient::setDisplayPowerMode(const sp<IBinder>& token,
- int mode) {
- ComposerService::getComposerService()->setPowerMode(token, mode);
- }
绘制keyguard与windows
在DisplayPowerController中调用screenTurningOn函数到PhoneWindowManager中.将mPendingScreenOnUnblocker对象传过来方便完成绘制后回调回来.
- // Called on the DisplayManager's DisplayPowerController thread.
- @Override
- public void screenTurningOn(final ScreenOnListener screenOnListener) {
- if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turning on...");
- updateScreenOffSleepToken(false);
- synchronized (mLock) {
- mScreenOnEarly = true;
- mScreenOnFully = false;
- mKeyguardDrawComplete = false;
- mWindowManagerDrawComplete = false;
- mScreenOnListener = screenOnListener;
- if (mKeyguardDelegate != null) {
- mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
- mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT, 1000); //发送超时消息, 1000ms keyguard还没有绘制完,就继续向下执行
- mKeyguardDelegate.onScreenTurningOn(mKeyguardDrawnCallback); //调用keyguard中函数, 绘制完成后回调mKeyguardDrawnCallback
- } else {
- if (DEBUG_WAKEUP) Slog.d(TAG,
- "null mKeyguardDelegate: setting mKeyguardDrawComplete.");
- finishKeyguardDrawn(); //如果没有keyguard就直接结束绘制
- }
- }
- }
- final DrawnListener mKeyguardDrawnCallback = new DrawnListener() {
- @Override
- public void onDrawn() { //绘制完成调用onDrawn函数
- if (DEBUG_WAKEUP) Slog.d(TAG, "mKeyguardDelegate.ShowListener.onDrawn.");
- mHandler.sendEmptyMessage(MSG_KEYGUARD_DRAWN_COMPLETE); //发送MSG_KEYGUARD_DRAWN_COMPLETE消息
- }
- };
- private class PolicyHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_KEYGUARD_DRAWN_COMPLETE:
- if (DEBUG_WAKEUP) Slog.w(TAG, "Setting mKeyguardDrawComplete");
- finishKeyguardDrawn(); //keyguard绘制完成, 结束
- break;
- case MSG_KEYGUARD_DRAWN_TIMEOUT:
- Slog.w(TAG, "Keyguard drawn timeout. Setting mKeyguardDrawComplete");
- finishKeyguardDrawn(); //keyguard绘制超时, 结束
- break;
- }
- }
- }
- /** Amount of time (in milliseconds) to wait for windows drawn before powering on. */
- static final int WAITING_FOR_DRAWN_TIMEOUT = 1000; //windows绘制超时时间1000ms
- private void finishKeyguardDrawn() {
- synchronized (mLock) {
- if (!mScreenOnEarly || mKeyguardDrawComplete) {
- return; // We are not awake yet or we have already informed of this event.
- }
- mKeyguardDrawComplete = true;
- if (mKeyguardDelegate != null) {
- mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT); //移除keyguard超时的message
- }
- mWindowManagerDrawComplete = false;
- }
- // ... eventually calls finishWindowsDrawn which will finalize our screen turn on
- // as well as enabling the orientation change logic/sensor.
- mWindowManagerInternal.waitForAllWindowsDrawn(mWindowManagerDrawCallback,
- WAITING_FOR_DRAWN_TIMEOUT); //windows绘制完成后回调mWindowManagerDrawCallback
- }
- @Override
- public void waitForAllWindowsDrawn(Runnable callback, long timeout) {
- boolean allWindowsDrawn = false;
- synchronized (mWindowMap) {
- mWaitingForDrawnCallback = callback;
- final WindowList windows = getDefaultWindowListLocked(); //获取windows列表
- for (int winNdx = windows.size() - 1; winNdx >= 0; --winNdx) {
- final WindowState win = windows.get(winNdx);
- final boolean isForceHiding = mPolicy.isForceHiding(win.mAttrs);
- if (win.isVisibleLw()
- && (win.mAppToken != null || isForceHiding)) {
- win.mWinAnimator.mDrawState = DRAW_PENDING;
- // Force add to mResizingWindows.
- win.mLastContentInsets.set(-1, -1, -1, -1);
- mWaitingForDrawn.add(win); //将所要绘制的windows加入mWaitingForDrawn中
- // No need to wait for the windows below Keyguard.
- if (isForceHiding) {
- break;
- }
- }
- }
- mWindowPlacerLocked.requestTraversal();
- mH.removeMessages(H.WAITING_FOR_DRAWN_TIMEOUT); //先将绘制windows超时的message移除, 以便重新计时
- if (mWaitingForDrawn.isEmpty()) {
- allWindowsDrawn = true;
- } else {
- mH.sendEmptyMessageDelayed(H.WAITING_FOR_DRAWN_TIMEOUT, timeout); //发送绘制超时的延迟消息
- checkDrawnWindowsLocked(); //检查windows是否绘制完成
- }
- }
- if (allWindowsDrawn) {
- callback.run(); //如果所有windows都绘制完成了就调用回调接口, 回到PhoneWindowManager中
- }
- }
- void checkDrawnWindowsLocked() {
- if (mWaitingForDrawn.isEmpty() || mWaitingForDrawnCallback == null) {
- return; //如果没有要绘制的windows或者没有回调接口就直接返回了
- }
- for (int j = mWaitingForDrawn.size() - 1; j >= 0; j--) { //遍历要绘制的windows
- WindowState win = mWaitingForDrawn.get(j);
- if (DEBUG_SCREEN_ON) Slog.i(TAG_WM, "Waiting for drawn " + win +
- ": removed=" + win.mRemoved + " visible=" + win.isVisibleLw() +
- " mHasSurface=" + win.mHasSurface +
- " drawState=" + win.mWinAnimator.mDrawState);
- if (win.mRemoved || !win.mHasSurface || !win.mPolicyVisibility) {
- // Window has been removed or hidden; no draw will now happen, so stop waiting.
- if (DEBUG_SCREEN_ON) Slog.w(TAG_WM, "Aborted waiting for drawn: " + win);
- mWaitingForDrawn.remove(win); //如果window已经被移除或者隐藏 就不需要绘制了, 直接从等待列表中移除
- } else if (win.hasDrawnLw()) {
- // Window is now drawn (and shown).
- if (DEBUG_SCREEN_ON) Slog.d(TAG_WM, "Window drawn win=" + win);
- mWaitingForDrawn.remove(win); //如果window已经绘制完成,也从等待列表中移除
- }
- }
- if (mWaitingForDrawn.isEmpty()) { //如果等待列表为空
- if (DEBUG_SCREEN_ON) Slog.d(TAG_WM, "All windows drawn!");
- mH.removeMessages(H.WAITING_FOR_DRAWN_TIMEOUT); //移除超时消息
- mH.sendEmptyMessage(H.ALL_WINDOWS_DRAWN); //发送ALL_WINDOWS_DRAWN消息
- }
- }
Windows的绘制在ViewRootImpl的draw函数中,其中ViewRoot的draw是通过vsync进行同步绘制。在绘制完成之后就会调用到WMS中DO_TRAVERSAL流程进行调用函数checkDrawnWindowsLocked判断每个window是否绘制完成。绘制完成后会发起ALL_WINDOWS_DRAWN的Message,回调回PhoneWindowManager。由于在调用函数performLayoutAndPlaceSurfacesLockedInner过程中需要与Power中的一些函数进行交互,而在Power中函数执行需要获得mLock锁,如果该锁被别的线程所持有就会发生阻塞,就不会及时返回发出window绘制完成的信号,在该流程中具体mLock还会被那些线程获取, 在讲解设置设置状态时讲解过可能被power中线程获取.
当window绘制完成后通过接口回调到PhoneWindowManager中,发送Window准备好的Message进行结束window绘制,将变量mWindowManagerDrawComplete置为true。最后回到DPC中。
- case ALL_WINDOWS_DRAWN: { //绘制windows完成
- Runnable callback;
- synchronized (mWindowMap) {
- callback = mWaitingForDrawnCallback;
- mWaitingForDrawnCallback = null;
- }
- if (callback != null) {
- callback.run(); //回调回PhoneWindowManager
- }
- }
- case WAITING_FOR_DRAWN_TIMEOUT: { //绘制Windows超时
- Runnable callback = null;
- synchronized (mWindowMap) {
- Slog.w(TAG_WM, "Timeout waiting for drawn: undrawn=" + mWaitingForDrawn); //输出超时log信息
- mWaitingForDrawn.clear(); //将等待绘制列表清空
- callback = mWaitingForDrawnCallback;
- mWaitingForDrawnCallback = null;
- }
- if (callback != null) {
- callback.run(); //回调回PhoneWindowManager
- }
- break;
- }
- final Runnable mWindowManagerDrawCallback = new Runnable() {
- @Override
- public void run() {
- if (DEBUG_WAKEUP) Slog.i(TAG, "All windows ready for display!");
- mHandler.sendEmptyMessage(MSG_WINDOW_MANAGER_DRAWN_COMPLETE); //发送Handler消息
- }
- };
- private class PolicyHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- //........
- case MSG_WINDOW_MANAGER_DRAWN_COMPLETE:
- if (DEBUG_WAKEUP) Slog.w(TAG, "Setting mWindowManagerDrawComplete");
- finishWindowsDrawn(); //结束windows绘制
- break;
- //.......
- }
- }
- }
- private void finishWindowsDrawn() {
- synchronized (mLock) {
- if (!mScreenOnEarly || mWindowManagerDrawComplete) {
- return; // Screen is not turned on or we did already handle this case earlier.
- }
- mWindowManagerDrawComplete = true; //设置windows绘制完成为true
- }
- finishScreenTurningOn(); //调用screenTurningOn就要结束了
- }
- private void finishScreenTurningOn() {
- synchronized (mLock) {
- // We have just finished drawing screen content. Since the orientation listener
- // gets only installed when all windows are drawn, we try to install it again.
- updateOrientationListenerLp(); //更新转向监听器
- }
- final ScreenOnListener listener;
- final boolean enableScreen;
- synchronized (mLock) {
- if (DEBUG_WAKEUP) Slog.d(TAG,
- "finishScreenTurningOn: mAwake=" + mAwake
- + ", mScreenOnEarly=" + mScreenOnEarly
- + ", mScreenOnFully=" + mScreenOnFully
- + ", mKeyguardDrawComplete=" + mKeyguardDrawComplete
- + ", mWindowManagerDrawComplete=" + mWindowManagerDrawComplete);
- if (mScreenOnFully || !mScreenOnEarly || !mWindowManagerDrawComplete
- || (mAwake && !mKeyguardDrawComplete)) {
- return; // spurious or not ready yet
- }
- if (DEBUG_WAKEUP) Slog.i(TAG, "Finished screen turning on...");
- listener = mScreenOnListener;
- mScreenOnListener = null;
- mScreenOnFully = true;
- // Remember the first time we draw the keyguard so we know when we're done with
- // the main part of booting and can enable the screen and hide boot messages.
- if (!mKeyguardDrawnOnce && mAwake) {
- mKeyguardDrawnOnce = true;
- enableScreen = true;
- if (mBootMessageNeedsHiding) {
- mBootMessageNeedsHiding = false;
- hideBootMessages();
- }
- } else {
- enableScreen = false;
- }
- }
- if (listener != null) {
- listener.onScreenOn(); //回调回DisplayPowerController的onScreenOn函数
- }
- if (enableScreen) {
- try {
- mWindowManager.enableScreenIfNeeded();
- } catch (RemoteException unhandled) {
- }
- }
- }
Windows绘制完成回调回来之后,此时就不用block screen了,将mPendingScreenOnUnblocker置为空,并计算screen一共block了多少毫秒。之后进行更新power state,由于之前调用DisplayPS设置过状态为ON,现在状态没有发生改变,故不用进行设置直接返回,由于window已经绘制完成mPendingScreenOnUnblocker为空,故返回true。如果没有亮屏动画直接将ColorFade level设置为1.0,如果有亮屏动画的话会有ColorFade level会从0.0逐渐变为1.0。
- private final class ScreenOnUnblocker implements WindowManagerPolicy.ScreenOnListener {
- @Override
- public void onScreenOn() {
- Message msg = mHandler.obtainMessage(MSG_SCREEN_ON_UNBLOCKED, this);
- msg.setAsynchronous(true);
- mHandler.sendMessage(msg); //发送unblock的消息
- }
- }
- private final class DisplayControllerHandler extends Handler {
- public DisplayControllerHandler(Looper looper) {
- super(looper, null, true /*async*/);
- }
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_UPDATE_POWER_STATE:
- updatePowerState();
- break;
- case MSG_PROXIMITY_SENSOR_DEBOUNCED:
- debounceProximitySensor();
- break;
- case MSG_SCREEN_ON_UNBLOCKED: //Handler收到unblock的消息后
- if (mPendingScreenOnUnblocker == msg.obj) {
- unblockScreenOn(); //将mPendingScreenOnUnblocker赋值NULL,并且输出unblock的时间, 之前有讲解
- updatePowerState(); //重新更新power 状态. setPowerState返回true, 继续设置Color Fade Level为1.0f
- }
- break;
- }
- }
- }
之后就是通过animateScreenBrightness函数设置屏幕亮度.
进而点亮屏幕, 在后文中讲解.
在PowerManagerService中对各种状态进行判断后,将其数值封装进DisplayPowerRequest中传入DisplayPowerController中进一步处理。在亮屏过程中DisplayPowerController会根据传过来的数值来设置新的电源状态为亮屏,然后调用DisplayPowerState来对状态进行设置,在分析DisplayPowerState时会具体讲解。由于此时ColorFade level(就是在手机屏幕的一层surface,当level为0是为一层黑帧,level为1.0时为透明)的值为0,表示屏幕还没有绘制好,所以此时需要block screen直到window界面绘制完成。当需要亮屏时调用PhoneWindowManager的screenTurningOn函数,通知window屏幕就要点亮了。然后调用WMS中函数waitForAllWindowsDrawn函数等待将所有需要绘制的window绘制完成后回调回来,超时时间为1000ms。在WMS中获取需要绘制的window将其加入mWaitingForDrawn中等待绘制,通过检查mWaitingForDrawn是否为空来判断,window是否绘制完成。此时screenTurningOn函数就执行完了,剩下的就是等待windows绘制完成。
DisplayManagerService.java中的LocalService继承了DisplayManagerInternal.java, 所以就会调用LocalService的requestPowerState函数请求电源状态.
- private final class LocalService extends DisplayManagerInternal {
- @Override
- public void initPowerManagement(final DisplayPowerCallbacks callbacks, Handler handler,
- SensorManager sensorManager) { //初始化函数在PowerManagerService的systemReady函数中调用
- synchronized (mSyncRoot) {
- DisplayBlanker blanker = new DisplayBlanker() { //创建blanker对象
- @Override
- public void requestDisplayState(int state, int brightness) {
- // The order of operations is important for legacy reasons.
- if (state == Display.STATE_OFF) {
- requestGlobalDisplayStateInternal(state, brightness);
- }
- callbacks.onDisplayStateChange(state);
- if (state != Display.STATE_OFF) {
- requestGlobalDisplayStateInternal(state, brightness);
- }
- }
- };
- mDisplayPowerController = new DisplayPowerController( //创建DisplayPowerController对象
- mContext, callbacks, handler, sensorManager, blanker);
- }
- }
- @Override
- public boolean requestPowerState(DisplayPowerRequest request,
- boolean waitForNegativeProximity) {
- return mDisplayPowerController.requestPowerState(request,
- waitForNegativeProximity); //调用DisplayPowerController请求电源状态
- }
- //.....
在DisplayPowerController中通过Handler发送MSG_UPDATE_POWER_STATE消息调用updatePowerState来更新电源状态. updatePowerState也是一个非常核心的函数,在该函数中将PowerManagerService中传过来的参数获取出来根据policy获取设备的请求状态是ON, OFF还是DOZE, 应用距离传感器, 将最终的请求状态调用DisplayPowerState进行设置. 判断设备是否打开了自动亮度调节, 计算最终屏幕要达到的目标亮度并通过亮度渐变动画慢慢的点亮屏幕,最终变为高亮.
- private void updatePowerState() {
- // Update the power state request.
- final boolean mustNotify;
- boolean mustInitialize = false;
- boolean autoBrightnessAdjustmentChanged = false;
- synchronized (mLock) {
- mPendingUpdatePowerStateLocked = false;
- if (mPendingRequestLocked == null) {
- return; // wait until first actual power request
- }
- if (mPowerRequest == null) { //判断mPowerRequest是否为NULL,如果为空新创建一个, 否则直接将mPendingRequestLocked复制给他
- mPowerRequest = new DisplayPowerRequest(mPendingRequestLocked);
- mWaitingForNegativeProximity = mPendingWaitForNegativeProximityLocked;
- mPendingWaitForNegativeProximityLocked = false;
- mPendingRequestChangedLocked = false;
- mustInitialize = true;
- } else if (mPendingRequestChangedLocked) {
- autoBrightnessAdjustmentChanged = (mPowerRequest.screenAutoBrightnessAdjustment
- != mPendingRequestLocked.screenAutoBrightnessAdjustment);
- mPowerRequest.copyFrom(mPendingRequestLocked);
- mWaitingForNegativeProximity |= mPendingWaitForNegativeProximityLocked;
- mPendingWaitForNegativeProximityLocked = false;
- mPendingRequestChangedLocked = false;
- mDisplayReadyLocked = false;
- }
- mustNotify = !mDisplayReadyLocked;
- }
- // Initialize things the first time the power state is changed.
- if (mustInitialize) {
- initialize();//power state第一次发生变化时需要做一些初始化,如:创建DisplayPowerState, 亮灭屏动画,亮度渐变动画实例等
- }
- // Compute the basic display state using the policy.
- // We might override this below based on other factors.
- int state;
- int brightness = PowerManager.BRIGHTNESS_DEFAULT;//设置屏幕默认亮度
- boolean performScreenOffTransition = false;
- switch (mPowerRequest.policy) {
- case DisplayPowerRequest.POLICY_OFF: //设置设备状态为OFF
- state = Display.STATE_OFF;
- performScreenOffTransition = true; //灭屏有过渡动画
- break;
- case DisplayPowerRequest.POLICY_DOZE: //设置设备状态为DOZE
- if (mPowerRequest.dozeScreenState != Display.STATE_UNKNOWN) {
- state = mPowerRequest.dozeScreenState;
- } else {
- state = Display.STATE_DOZE;
- }
- if (!mAllowAutoBrightnessWhileDozingConfig) {
- brightness = mPowerRequest.dozeScreenBrightness;//如果在xml文件中配置了相关属性,就将dozeScreenBrightness赋给亮度值
- }
- break;
- case DisplayPowerRequest.POLICY_DIM:
- case DisplayPowerRequest.POLICY_BRIGHT:
- default:
- state = Display.STATE_ON;//如果policy为DIM, BRIGHT的话,设备状态都为ON
- break;
- }
- assert(state != Display.STATE_UNKNOWN);
- // Apply the proximity sensor.
- if (mProximitySensor != null) { //距离传感器相关处理
- if (mPowerRequest.useProximitySensor && state != Display.STATE_OFF) {
- setProximitySensorEnabled(true);
- if (!mScreenOffBecauseOfProximity
- && mProximity == PROXIMITY_POSITIVE) {
- mScreenOffBecauseOfProximity = true;
- sendOnProximityPositiveWithWakelock();
- }
- } else if (mWaitingForNegativeProximity
- && mScreenOffBecauseOfProximity
- && mProximity == PROXIMITY_POSITIVE
- && state != Display.STATE_OFF) {
- setProximitySensorEnabled(true);
- } else {
- setProximitySensorEnabled(false);
- mWaitingForNegativeProximity = false;
- }
- if (mScreenOffBecauseOfProximity
- && mProximity != PROXIMITY_POSITIVE) {
- mScreenOffBecauseOfProximity = false;
- sendOnProximityNegativeWithWakelock();
- }
- } else {
- mWaitingForNegativeProximity = false;
- }
- if (mScreenOffBecauseOfProximity) {
- state = Display.STATE_OFF;//如果因为距离传感器灭屏设置设备状态为OFF
- }
- // Animate the screen state change unless already animating.
- // The transition may be deferred, so after this point we will use the
- // actual state instead of the desired one.
- animateScreenStateChange(state, performScreenOffTransition);//处理屏幕状态改变
- state = mPowerState.getScreenState();//获取新的屏幕状态
- // Use zero brightness when screen is off.
- if (state == Display.STATE_OFF) {
- brightness = PowerManager.BRIGHTNESS_OFF; //如果新的状态是灭屏的话设置brightness为0
- }
- // Configure auto-brightness.
- boolean autoBrightnessEnabled = false;
- if (mAutomaticBrightnessController != null) {
- final boolean autoBrightnessEnabledInDoze = mAllowAutoBrightnessWhileDozingConfig
- && (state == Display.STATE_DOZE || state == Display.STATE_DOZE_SUSPEND);
- autoBrightnessEnabled = mPowerRequest.useAutoBrightness
- && (state == Display.STATE_ON || autoBrightnessEnabledInDoze)
- && brightness < 0;
- final boolean userInitiatedChange = autoBrightnessAdjustmentChanged
- && mPowerRequest.brightnessSetByUser;
- mAutomaticBrightnessController.configure(autoBrightnessEnabled,
- mPowerRequest.screenAutoBrightnessAdjustment, state != Display.STATE_ON,
- userInitiatedChange, mPowerRequest.useTwilight);//配置控制自动亮度设置的对象
- }
- // Apply brightness boost.
- // We do this here after configuring auto-brightness so that we don't
- // disable the light sensor during this temporary state. That way when
- // boost ends we will be able to resume normal auto-brightness behavior
- // without any delay.
- if (mPowerRequest.boostScreenBrightness
- && brightness != PowerManager.BRIGHTNESS_OFF) {
- brightness = PowerManager.BRIGHTNESS_ON;
- }
- // Apply auto-brightness.
- boolean slowChange = false;
- if (brightness < 0) {
- if (autoBrightnessEnabled) {
- brightness = mAutomaticBrightnessController.getAutomaticScreenBrightness();//获取自动亮度值
- }
- if (brightness >= 0) {
- // Use current auto-brightness value and slowly adjust to changes.
- brightness = clampScreenBrightness(brightness);//保证亮度值的有效性,不能在0~255之外
- if (mAppliedAutoBrightness && !autoBrightnessAdjustmentChanged) {
- slowChange = true; // slowly adapt to auto-brightness
- }
- mAppliedAutoBrightness = true;//使用了自动亮度
- } else {
- mAppliedAutoBrightness = false;//没有使用自动亮度
- }
- } else {
- mAppliedAutoBrightness = false;
- }
- // Use default brightness when dozing unless overridden.
- if (brightness < 0 && (state == Display.STATE_DOZE
- || state == Display.STATE_DOZE_SUSPEND)) {
- brightness = mScreenBrightnessDozeConfig;
- }
- // Apply manual brightness.
- // Use the current brightness setting from the request, which is expected
- // provide a nominal default value for the case where auto-brightness
- // is not ready yet.
- if (brightness < 0) {
- brightness = clampScreenBrightness(mPowerRequest.screenBrightness);//如果亮度值小于0的话,就是用setting中设置的亮度值
- }
- // Apply dimming by at least some minimum amount when user activity
- // timeout is about to expire.
- if (mPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
- if (brightness > mScreenBrightnessRangeMinimum) {
- brightness = Math.max(Math.min(brightness - SCREEN_DIM_MINIMUM_REDUCTION,
- mScreenBrightnessDimConfig), mScreenBrightnessRangeMinimum);
- }
- if (!mAppliedDimming) {
- slowChange = false;
- }
- mAppliedDimming = true;
- } else if (mAppliedDimming) {
- slowChange = false;
- mAppliedDimming = false;
- }
- // If low power mode is enabled, cut the brightness level by half
- // as long as it is above the minimum threshold.
- if (mPowerRequest.lowPowerMode) {
- if (brightness > mScreenBrightnessRangeMinimum) {
- brightness = Math.max(brightness / 2, mScreenBrightnessRangeMinimum);//低电模式, 亮度是目标亮度的1/2
- }
- if (!mAppliedLowPower) {
- slowChange = false;
- }
- mAppliedLowPower = true;
- } else if (mAppliedLowPower) {
- slowChange = false;
- mAppliedLowPower = false;
- }
- // Animate the screen brightness when the screen is on or dozing.
- // Skip the animation when the screen is off or suspended.
- if (!mPendingScreenOff) {
- if (state == Display.STATE_ON || state == Display.STATE_DOZE) {
- animateScreenBrightness(brightness,
- slowChange ? BRIGHTNESS_RAMP_RATE_SLOW : mBrightnessRampRateFast);//使用亮度渐变动画设置亮度, 渐变速度依赖于rate
- } else {
- animateScreenBrightness(brightness, 0);//动画速率为0, 没有动画
- }
- }
- //..........
- }
根据上面代码分析在updatePowerState中主要做的事情主要有两件事:
1.调用animateScreenStateChange函数处理屏幕状态变化
2.调用animateScreenBrightness函数设置屏幕亮度
下面将详细讲解这两件事情:
animateScreenStateChange函数处理屏幕状态变化
- private void animateScreenStateChange(int target, boolean performScreenOffTransition) {
- // If there is already an animation in progress, don't interfere with it.
- if (mColorFadeOnAnimator.isStarted()
- || mColorFadeOffAnimator.isStarted()) {
- if (target != Display.STATE_ON) {
- return; //如果此时有亮灭屏动画, 并且目标状态不是ON,就返回.
- }
- // If display state changed to on, proceed and stop the color fade and turn screen on.
- mPendingScreenOff = false;
- }
- // If we were in the process of turning off the screen but didn't quite
- // finish. Then finish up now to prevent a jarring transition back
- // to screen on if we skipped blocking screen on as usual.
- if (mPendingScreenOff && target != Display.STATE_OFF) {
- setScreenState(Display.STATE_OFF);
- mPendingScreenOff = false;
- mPowerState.dismissColorFadeResources();
- }
- if (target == Display.STATE_ON) { //亮屏
- // Want screen on. The contents of the screen may not yet
- // be visible if the color fade has not been dismissed because
- // its last frame of animation is solid black.
- if (!setScreenState(Display.STATE_ON)) { //设置屏幕状态,如果返回false就blocked亮屏, 不能往下执行
- return; // screen on blocked
- }
- if (USE_COLOR_FADE_ON_ANIMATION && mPowerRequest.isBrightOrDim()) {
- // Perform screen on animation.
- if (mPowerState.getColorFadeLevel() == 1.0f) { //执行亮屏动画, 将Color Fade level渐变为1.0f
- mPowerState.dismissColorFade();
- } else if (mPowerState.prepareColorFade(mContext,
- mColorFadeFadesConfig ?
- ColorFade.MODE_FADE :
- ColorFade.MODE_WARM_UP)) {
- mColorFadeOnAnimator.start();
- } else {
- mColorFadeOnAnimator.end();
- }
- } else {
- // Skip screen on animation.
- mPowerState.setColorFadeLevel(1.0f); //跳过亮屏, 直接设置Color Fade level为1.0f
- mPowerState.dismissColorFade();
- }
- //...........
- } else {
- // Want screen off. //灭屏
- mPendingScreenOff = true;
- if (mPowerState.getColorFadeLevel() == 0.0f) {
- // Turn the screen off.
- // A black surface is already hiding the contents of the screen.
- setScreenState(Display.STATE_OFF); //如果Color Fade level为0.0f, 设置屏幕状态为OFF
- mPendingScreenOff = false;
- mPowerState.dismissColorFadeResources();
- } else if (performScreenOffTransition //performScreenOffTransition为true, 有灭屏过渡动画
- && mPowerState.prepareColorFade(mContext,
- mColorFadeFadesConfig ?
- ColorFade.MODE_FADE : ColorFade.MODE_COOL_DOWN)
- && mPowerState.getScreenState() != Display.STATE_OFF) {
- // Perform the screen off animation.
- mColorFadeOffAnimator.start(); //灭屏动画,Color fade leve慢慢将1.0变为0.0f
- } else {
- // Skip the screen off animation and add a black surface to hide the
- // contents of the screen.
- mColorFadeOffAnimator.end(); //跳过灭屏动画
- }
- }
- }
在上面函数中主要就是调用setScreenState设置屏幕状态, 只有设置好状态并且setScreenState返回true,之后才会判断是否有亮度渐变动画将Color Fade Level设置为1.0f. 否则一直会阻塞在setScreenState函数上.
- private boolean setScreenState(int state) {
- if (mPowerState.getScreenState() != state) {
- final boolean wasOn = (mPowerState.getScreenState() != Display.STATE_OFF);
- mPowerState.setScreenState(state); //调用DisplayPowerState设置屏幕状态
- // Tell battery stats about the transition.
- try {
- mBatteryStats.noteScreenState(state);
- } catch (RemoteException ex) {
- // same process
- }
- }
- // Tell the window manager policy when the screen is turned off or on unless it's due
- // to the proximity sensor. We temporarily block turning the screen on until the
- // window manager is ready by leaving a black surface covering the screen.
- // This surface is essentially the final state of the color fade animation and
- // it is only removed once the window manager tells us that the activity has
- // finished drawing underneath.
- final boolean isOff = (state == Display.STATE_OFF); //是否是灭屏状态
- if (isOff && mReportedScreenStateToPolicy != REPORTED_TO_POLICY_SCREEN_OFF
- && !mScreenOffBecauseOfProximity) {
- mReportedScreenStateToPolicy = REPORTED_TO_POLICY_SCREEN_OFF;
- unblockScreenOn();
- mWindowManagerPolicy.screenTurnedOff();
- PMSFactory.getInstance().createExtraDisplayPowerState(mContext).setButtonOn(false);
- } else if (!isOff && mReportedScreenStateToPolicy == REPORTED_TO_POLICY_SCREEN_OFF) {
- mReportedScreenStateToPolicy = REPORTED_TO_POLICY_SCREEN_TURNING_ON;
- if (mPowerState.getColorFadeLevel() == 0.0f) { //亮屏处理, 此时Colorfade level为0.0f 为true
- blockScreenOn(); //block亮屏, 创建一个mPendingScreenOnUnblocker对象
- } else {
- unblockScreenOn(); //将创建的mPendingScreenOnUnblocker对象销毁,设置NULL
- }
- mWindowManagerPolicy.screenTurningOn(mPendingScreenOnUnblocker); //调用PhoneWindowManager进行处理
- if (PMSFactory.getInstance().createExtraDisplayPowerController(mContext).getButtonTimeout() != -2){
- PMSFactory.getInstance().createExtraDisplayPowerState(mContext).setButtonOn(true);
- }
- }
- // Return true if the screen isn't blocked.
- return mPendingScreenOnUnblocker == null; //blockScreenOn时创建一个mPendingScreenOnUnblocker对象,所以返回false, block亮屏
- }
- private void blockScreenOn() {
- if (mPendingScreenOnUnblocker == null) {
- Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, SCREEN_ON_BLOCKED_TRACE_NAME, 0);
- mPendingScreenOnUnblocker = new ScreenOnUnblocker();
- mScreenOnBlockStartRealTime = SystemClock.elapsedRealtime(); //开始blocked亮屏的时间
- Slog.i(TAG, "Blocking screen on until initial contents have been drawn.");
- }
- }
- private void unblockScreenOn() {
- if (mPendingScreenOnUnblocker != null) {
- mPendingScreenOnUnblocker = null;
- long delay = SystemClock.elapsedRealtime() - mScreenOnBlockStartRealTime;
- Slog.i(TAG, "Unblocked screen on after " + delay + " ms"); //输出log,一共block亮屏多长时间
- Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, SCREEN_ON_BLOCKED_TRACE_NAME, 0);
- }
- }
在setScreenState函数中主要做了两件事情:
1.调用DisplayPowerState对屏幕状态进行设置
2.通知PhoneWindowManager对keyguard和windows进行绘制.
设置屏幕状态
当设置屏幕状态时,如果新状态与之前的状态不同时就会将新的状态值记录在成员变量mScreenState中,这样可以让其它类来获取当前的屏幕状态。之后在一个Runnable对象的run函数中根据屏幕状态与ColorFade level来进行获取屏幕亮度,此时是亮屏操作但是windows尚未绘制完成level仍然是0.0,此时获取的亮度值为0,由此可知,只要windows绘制不完成亮度值会一直为0,即屏幕不会亮。
- private final Runnable mScreenUpdateRunnable = new Runnable() {
- @Override
- public void run() {
- mScreenUpdatePending = false;
- int brightness = mScreenState != Display.STATE_OFF
- && mColorFadeLevel > 0f ? mScreenBrightness : 0; //根据屏幕状态设置亮度值, 亮屏时如果color Fade Level为0.0f, brightness一直为0,不会亮屏
- if (mPhotonicModulator.setState(mScreenState, brightness)) {
- if (DEBUG) {
- Slog.d(TAG, "Screen ready");
- }
- mScreenReady = true;
- invokeCleanListenerIfNeeded();
- } else {
- if (DEBUG) {
- Slog.d(TAG, "Screen not ready");
- }
- }
- }
- };
- public void run() {
- for (;;) {
- // Get pending change.
- final int state;
- final boolean stateChanged;
- final int backlight;
- final boolean backlightChanged;
- synchronized (mLock) {
- state = mPendingState;
- stateChanged = (state != mActualState);
- backlight = mPendingBacklight;
- backlightChanged = (backlight != mActualBacklight);
- if (!stateChanged) { //判断状态是否变化
- // State changed applied, notify outer class.
- postScreenUpdateThreadSafe();
- mStateChangeInProgress = false;
- }
- if (!backlightChanged) {
- mBacklightChangeInProgress = false;
- }
- if (!stateChanged && !backlightChanged) { //如果亮度,状态都没有改变线程将wait
- try {
- mLock.wait();
- } catch (InterruptedException ex) { }
- continue;
- }
- mActualState = state; //获取确实的状态.亮度
- mActualBacklight = backlight;
- }
- // Apply pending change.
- if (DEBUG) {
- Slog.d(TAG, "Updating screen state: state="
- + Display.stateToString(state) + ", backlight=" + backlight);
- }
- mBlanker.requestDisplayState(state, backlight); //mBlanker为DisplayManagerService中创建的对象,前面有提到.
- }
- }
在DisplayManagerSerice中的LocalService初始化函数initPowerManagement中创建的mBlanker, 所以就调用他的requestDisplayState函数
- DisplayBlanker blanker = new DisplayBlanker() {
- @Override
- public void requestDisplayState(int state, int brightness) {
- // The order of operations is important for legacy reasons.
- if (state == Display.STATE_OFF) {
- requestGlobalDisplayStateInternal(state, brightness); //灭屏先调用该函数
- }
- callbacks.onDisplayStateChange(state); //callbacks为PowerManagerService中对象
- if (state != Display.STATE_OFF) {
- requestGlobalDisplayStateInternal(state, brightness); //亮屏调用该处函数
- }
- }
- };
在此处先讲解回调PowerManagerService的onDisplayStateChange函数做了那些事情,耗时点在什么地方. 在该函数中会首先获取一个mLock的锁,这把锁是不是很熟悉,我们在前面讲绘制windows流程的时候window与power交互时需要获取mLock,如果该锁被别的线程持有,window绘制流程就会阻塞。而根据上面流程可以看出,请求设备状态是在绘制window之前发生的,所以调用函数onDisplayStateChange没有结束的话,该锁就一直被持有,导致window绘制流程不能及时返回。
- public void onDisplayStateChange(int state) {
- // This method is only needed to support legacy display blanking behavior
- // where the display's power state is coupled to suspend or to the power HAL.
- // The order of operations matters here.
- synchronized (mLock) { //获取mLock锁
- if (mDisplayState != state) {
- mDisplayState = state;
- if (state == Display.STATE_OFF) { //灭屏
- if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
- setHalInteractiveModeLocked(false);
- }
- if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
- setHalAutoSuspendModeLocked(true);
- }
- } else { //亮屏
- if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
- setHalAutoSuspendModeLocked(false); //设置自动suspend模式
- }
- if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
- setHalInteractiveModeLocked(true); //设置hal交互模式
- }
- }
- }
- }
- }
- private void setHalAutoSuspendModeLocked(boolean enable) {
- if (enable != mHalAutoSuspendModeEnabled) {
- if (DEBUG) {
- Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
- }
- mHalAutoSuspendModeEnabled = enable;
- Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
- try {
- nativeSetAutoSuspend(enable); //调用JNI设置
- } finally {
- Trace.traceEnd(Trace.TRACE_TAG_POWER);
- }
- }
- }
- static void nativeSetAutoSuspend(JNIEnv* /* env */, jclass /* clazz */, jboolean enable) {
- if (enable) {
- ALOGD_IF_SLOW(100, "Excessive delay in autosuspend_enable() while turning screen off"); //灭屏执行超过100ms,会输出log
- autosuspend_enable();
- } else {
- ALOGD_IF_SLOW(100, "Excessive delay in autosuspend_disable() while turning screen on"); //亮屏执行该函数超过100ms, 会输出该行log
- autosuspend_disable();
- }
- }
而在亮屏时调用autosuspend_disable()是往/sys/power/state写 on(亮屏)的函数。在往节点写入状态后,调用late_resume将LCD resume,关于late_resume 阶段 “sprdfb_dispc_resume”函数执行时间可能由于手机硬件信息的不同,导致执行时间相差较大。
上面执行完之后,现在重新回到DMS中继续向下进行执行。
在DMS中通过变量mGlobalDisplayState进行记录当前的设备状态,如果设备状态发生改变时就会重新记录,之后更新设备状态将device对应的Runnable放入队列。然后就会将Runnable从队列中取出执行run函数。根据dumpsys信息可以知道,设备信息中只有一个设备“内置屏幕”,并且对应的Adapter为LocalDisplayAdapter,所以就会调用LocalDisplayAdapter中的run函数。在run函数中会调用SurfaceControl中的setDisplayPowerMode函数处理。最终到JNI中,此处也有可能发生超时,也可从输出log中看出。
- static void nativeSetDisplayPowerMode(JNIEnv* env, jclass clazz, jobject tokenObj, jint mode) {
- sp<IBinder> token(ibinderForJavaObject(env, tokenObj));
- if (token == NULL) return;
- ALOGD_IF_SLOW(100, "Excessive delay in setPowerMode()");
- SurfaceComposerClient::setDisplayPowerMode(token, mode);
- }
- void SurfaceComposerClient::setDisplayPowerMode(const sp<IBinder>& token,
- int mode) {
- ComposerService::getComposerService()->setPowerMode(token, mode);
- }
绘制keyguard与windows
在DisplayPowerController中调用screenTurningOn函数到PhoneWindowManager中.将mPendingScreenOnUnblocker对象传过来方便完成绘制后回调回来.
- // Called on the DisplayManager's DisplayPowerController thread.
- @Override
- public void screenTurningOn(final ScreenOnListener screenOnListener) {
- if (DEBUG_WAKEUP) Slog.i(TAG, "Screen turning on...");
- updateScreenOffSleepToken(false);
- synchronized (mLock) {
- mScreenOnEarly = true;
- mScreenOnFully = false;
- mKeyguardDrawComplete = false;
- mWindowManagerDrawComplete = false;
- mScreenOnListener = screenOnListener;
- if (mKeyguardDelegate != null) {
- mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT);
- mHandler.sendEmptyMessageDelayed(MSG_KEYGUARD_DRAWN_TIMEOUT, 1000); //发送超时消息, 1000ms keyguard还没有绘制完,就继续向下执行
- mKeyguardDelegate.onScreenTurningOn(mKeyguardDrawnCallback); //调用keyguard中函数, 绘制完成后回调mKeyguardDrawnCallback
- } else {
- if (DEBUG_WAKEUP) Slog.d(TAG,
- "null mKeyguardDelegate: setting mKeyguardDrawComplete.");
- finishKeyguardDrawn(); //如果没有keyguard就直接结束绘制
- }
- }
- }
- final DrawnListener mKeyguardDrawnCallback = new DrawnListener() {
- @Override
- public void onDrawn() { //绘制完成调用onDrawn函数
- if (DEBUG_WAKEUP) Slog.d(TAG, "mKeyguardDelegate.ShowListener.onDrawn.");
- mHandler.sendEmptyMessage(MSG_KEYGUARD_DRAWN_COMPLETE); //发送MSG_KEYGUARD_DRAWN_COMPLETE消息
- }
- };
- private class PolicyHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_KEYGUARD_DRAWN_COMPLETE:
- if (DEBUG_WAKEUP) Slog.w(TAG, "Setting mKeyguardDrawComplete");
- finishKeyguardDrawn(); //keyguard绘制完成, 结束
- break;
- case MSG_KEYGUARD_DRAWN_TIMEOUT:
- Slog.w(TAG, "Keyguard drawn timeout. Setting mKeyguardDrawComplete");
- finishKeyguardDrawn(); //keyguard绘制超时, 结束
- break;
- }
- }
- }
- /** Amount of time (in milliseconds) to wait for windows drawn before powering on. */
- static final int WAITING_FOR_DRAWN_TIMEOUT = 1000; //windows绘制超时时间1000ms
- private void finishKeyguardDrawn() {
- synchronized (mLock) {
- if (!mScreenOnEarly || mKeyguardDrawComplete) {
- return; // We are not awake yet or we have already informed of this event.
- }
- mKeyguardDrawComplete = true;
- if (mKeyguardDelegate != null) {
- mHandler.removeMessages(MSG_KEYGUARD_DRAWN_TIMEOUT); //移除keyguard超时的message
- }
- mWindowManagerDrawComplete = false;
- }
- // ... eventually calls finishWindowsDrawn which will finalize our screen turn on
- // as well as enabling the orientation change logic/sensor.
- mWindowManagerInternal.waitForAllWindowsDrawn(mWindowManagerDrawCallback,
- WAITING_FOR_DRAWN_TIMEOUT); //windows绘制完成后回调mWindowManagerDrawCallback
- }
- @Override
- public void waitForAllWindowsDrawn(Runnable callback, long timeout) {
- boolean allWindowsDrawn = false;
- synchronized (mWindowMap) {
- mWaitingForDrawnCallback = callback;
- final WindowList windows = getDefaultWindowListLocked(); //获取windows列表
- for (int winNdx = windows.size() - 1; winNdx >= 0; --winNdx) {
- final WindowState win = windows.get(winNdx);
- final boolean isForceHiding = mPolicy.isForceHiding(win.mAttrs);
- if (win.isVisibleLw()
- && (win.mAppToken != null || isForceHiding)) {
- win.mWinAnimator.mDrawState = DRAW_PENDING;
- // Force add to mResizingWindows.
- win.mLastContentInsets.set(-1, -1, -1, -1);
- mWaitingForDrawn.add(win); //将所要绘制的windows加入mWaitingForDrawn中
- // No need to wait for the windows below Keyguard.
- if (isForceHiding) {
- break;
- }
- }
- }
- mWindowPlacerLocked.requestTraversal();
- mH.removeMessages(H.WAITING_FOR_DRAWN_TIMEOUT); //先将绘制windows超时的message移除, 以便重新计时
- if (mWaitingForDrawn.isEmpty()) {
- allWindowsDrawn = true;
- } else {
- mH.sendEmptyMessageDelayed(H.WAITING_FOR_DRAWN_TIMEOUT, timeout); //发送绘制超时的延迟消息
- checkDrawnWindowsLocked(); //检查windows是否绘制完成
- }
- }
- if (allWindowsDrawn) {
- callback.run(); //如果所有windows都绘制完成了就调用回调接口, 回到PhoneWindowManager中
- }
- }
- void checkDrawnWindowsLocked() {
- if (mWaitingForDrawn.isEmpty() || mWaitingForDrawnCallback == null) {
- return; //如果没有要绘制的windows或者没有回调接口就直接返回了
- }
- for (int j = mWaitingForDrawn.size() - 1; j >= 0; j--) { //遍历要绘制的windows
- WindowState win = mWaitingForDrawn.get(j);
- if (DEBUG_SCREEN_ON) Slog.i(TAG_WM, "Waiting for drawn " + win +
- ": removed=" + win.mRemoved + " visible=" + win.isVisibleLw() +
- " mHasSurface=" + win.mHasSurface +
- " drawState=" + win.mWinAnimator.mDrawState);
- if (win.mRemoved || !win.mHasSurface || !win.mPolicyVisibility) {
- // Window has been removed or hidden; no draw will now happen, so stop waiting.
- if (DEBUG_SCREEN_ON) Slog.w(TAG_WM, "Aborted waiting for drawn: " + win);
- mWaitingForDrawn.remove(win); //如果window已经被移除或者隐藏 就不需要绘制了, 直接从等待列表中移除
- } else if (win.hasDrawnLw()) {
- // Window is now drawn (and shown).
- if (DEBUG_SCREEN_ON) Slog.d(TAG_WM, "Window drawn win=" + win);
- mWaitingForDrawn.remove(win); //如果window已经绘制完成,也从等待列表中移除
- }
- }
- if (mWaitingForDrawn.isEmpty()) { //如果等待列表为空
- if (DEBUG_SCREEN_ON) Slog.d(TAG_WM, "All windows drawn!");
- mH.removeMessages(H.WAITING_FOR_DRAWN_TIMEOUT); //移除超时消息
- mH.sendEmptyMessage(H.ALL_WINDOWS_DRAWN); //发送ALL_WINDOWS_DRAWN消息
- }
- }
Windows的绘制在ViewRootImpl的draw函数中,其中ViewRoot的draw是通过vsync进行同步绘制。在绘制完成之后就会调用到WMS中DO_TRAVERSAL流程进行调用函数checkDrawnWindowsLocked判断每个window是否绘制完成。绘制完成后会发起ALL_WINDOWS_DRAWN的Message,回调回PhoneWindowManager。由于在调用函数performLayoutAndPlaceSurfacesLockedInner过程中需要与Power中的一些函数进行交互,而在Power中函数执行需要获得mLock锁,如果该锁被别的线程所持有就会发生阻塞,就不会及时返回发出window绘制完成的信号,在该流程中具体mLock还会被那些线程获取, 在讲解设置设置状态时讲解过可能被power中线程获取.
当window绘制完成后通过接口回调到PhoneWindowManager中,发送Window准备好的Message进行结束window绘制,将变量mWindowManagerDrawComplete置为true。最后回到DPC中。
- case ALL_WINDOWS_DRAWN: { //绘制windows完成
- Runnable callback;
- synchronized (mWindowMap) {
- callback = mWaitingForDrawnCallback;
- mWaitingForDrawnCallback = null;
- }
- if (callback != null) {
- callback.run(); //回调回PhoneWindowManager
- }
- }
- case WAITING_FOR_DRAWN_TIMEOUT: { //绘制Windows超时
- Runnable callback = null;
- synchronized (mWindowMap) {
- Slog.w(TAG_WM, "Timeout waiting for drawn: undrawn=" + mWaitingForDrawn); //输出超时log信息
- mWaitingForDrawn.clear(); //将等待绘制列表清空
- callback = mWaitingForDrawnCallback;
- mWaitingForDrawnCallback = null;
- }
- if (callback != null) {
- callback.run(); //回调回PhoneWindowManager
- }
- break;
- }
- final Runnable mWindowManagerDrawCallback = new Runnable() {
- @Override
- public void run() {
- if (DEBUG_WAKEUP) Slog.i(TAG, "All windows ready for display!");
- mHandler.sendEmptyMessage(MSG_WINDOW_MANAGER_DRAWN_COMPLETE); //发送Handler消息
- }
- };
- private class PolicyHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- //........
- case MSG_WINDOW_MANAGER_DRAWN_COMPLETE:
- if (DEBUG_WAKEUP) Slog.w(TAG, "Setting mWindowManagerDrawComplete");
- finishWindowsDrawn(); //结束windows绘制
- break;
- //.......
- }
- }
- }
- private void finishWindowsDrawn() {
- synchronized (mLock) {
- if (!mScreenOnEarly || mWindowManagerDrawComplete) {
- return; // Screen is not turned on or we did already handle this case earlier.
- }
- mWindowManagerDrawComplete = true; //设置windows绘制完成为true
- }
- finishScreenTurningOn(); //调用screenTurningOn就要结束了
- }
- private void finishScreenTurningOn() {
- synchronized (mLock) {
- // We have just finished drawing screen content. Since the orientation listener
- // gets only installed when all windows are drawn, we try to install it again.
- updateOrientationListenerLp(); //更新转向监听器
- }
- final ScreenOnListener listener;
- final boolean enableScreen;
- synchronized (mLock) {
- if (DEBUG_WAKEUP) Slog.d(TAG,
- "finishScreenTurningOn: mAwake=" + mAwake
- + ", mScreenOnEarly=" + mScreenOnEarly
- + ", mScreenOnFully=" + mScreenOnFully
- + ", mKeyguardDrawComplete=" + mKeyguardDrawComplete
- + ", mWindowManagerDrawComplete=" + mWindowManagerDrawComplete);
- if (mScreenOnFully || !mScreenOnEarly || !mWindowManagerDrawComplete
- || (mAwake && !mKeyguardDrawComplete)) {
- return; // spurious or not ready yet
- }
- if (DEBUG_WAKEUP) Slog.i(TAG, "Finished screen turning on...");
- listener = mScreenOnListener;
- mScreenOnListener = null;
- mScreenOnFully = true;
- // Remember the first time we draw the keyguard so we know when we're done with
- // the main part of booting and can enable the screen and hide boot messages.
- if (!mKeyguardDrawnOnce && mAwake) {
- mKeyguardDrawnOnce = true;
- enableScreen = true;
- if (mBootMessageNeedsHiding) {
- mBootMessageNeedsHiding = false;
- hideBootMessages();
- }
- } else {
- enableScreen = false;
- }
- }
- if (listener != null) {
- listener.onScreenOn(); //回调回DisplayPowerController的onScreenOn函数
- }
- if (enableScreen) {
- try {
- mWindowManager.enableScreenIfNeeded();
- } catch (RemoteException unhandled) {
- }
- }
- }
Windows绘制完成回调回来之后,此时就不用block screen了,将mPendingScreenOnUnblocker置为空,并计算screen一共block了多少毫秒。之后进行更新power state,由于之前调用DisplayPS设置过状态为ON,现在状态没有发生改变,故不用进行设置直接返回,由于window已经绘制完成mPendingScreenOnUnblocker为空,故返回true。如果没有亮屏动画直接将ColorFade level设置为1.0,如果有亮屏动画的话会有ColorFade level会从0.0逐渐变为1.0。
- private final class ScreenOnUnblocker implements WindowManagerPolicy.ScreenOnListener {
- @Override
- public void onScreenOn() {
- Message msg = mHandler.obtainMessage(MSG_SCREEN_ON_UNBLOCKED, this);
- msg.setAsynchronous(true);
- mHandler.sendMessage(msg); //发送unblock的消息
- }
- }
- private final class DisplayControllerHandler extends Handler {
- public DisplayControllerHandler(Looper looper) {
- super(looper, null, true /*async*/);
- }
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_UPDATE_POWER_STATE:
- updatePowerState();
- break;
- case MSG_PROXIMITY_SENSOR_DEBOUNCED:
- debounceProximitySensor();
- break;
- case MSG_SCREEN_ON_UNBLOCKED: //Handler收到unblock的消息后
- if (mPendingScreenOnUnblocker == msg.obj) {
- unblockScreenOn(); //将mPendingScreenOnUnblocker赋值NULL,并且输出unblock的时间, 之前有讲解
- updatePowerState(); //重新更新power 状态. setPowerState返回true, 继续设置Color Fade Level为1.0f
- }
- break;
- }
- }
- }
之后就是通过animateScreenBrightness函数设置屏幕亮度.
进而点亮屏幕, 在后文中讲解.