PowerManagerService深入分析

PowerManagerService提供Android系统的电源管理服务,主要功能是控制系统的待机状态,控制显示屏的开关和亮度调节等。

PowerManagerService在systemserver中创建,加入到serviceManager中:

  1. mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);  
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);

先从构造函数分析,代码如下:

   

  1. public PowerManagerService(Context context) {  
  2.        super(context);  
  3.        mContext = context;  
  4.   //创建处理消息的线程  
  5.        mHandlerThread = new ServiceThread(TAG,  
  6.                Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);  
  7.        mHandlerThread.start();  
  8.  //创建Handler,注意mHandlerThread.getLooper(),每一个线程都只有一个looper,这样消息的处理会放在这个线程中  
  9.        mHandler = new PowerManagerHandler(mHandlerThread.getLooper());  
  10.   
  11.        synchronized (mLock) {  
  12.            mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks");  
  13.            mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display");  
  14.   //防止cpu进入睡眠状态  
  15.            mDisplaySuspendBlocker.acquire();  
  16.            mHoldingDisplaySuspendBlocker = true;  
  17.            mHalAutoSuspendModeEnabled = false;  
  18.            mHalInteractiveModeEnabled = true;  
  19.   //当前系统状态正常运行状态  
  20.            mWakefulness = WAKEFULNESS_AWAKE;  
  21.   
  22.            nativeInit();  
  23.            nativeSetAutoSuspend(false);  
  24.            nativeSetInteractive(true);  
  25.        }  
  26.    }  
 public PowerManagerService(Context context) {
        super(context);
        mContext = context;
   //创建处理消息的线程
        mHandlerThread = new ServiceThread(TAG,
                Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
        mHandlerThread.start();
  //创建Handler,注意mHandlerThread.getLooper(),每一个线程都只有一个looper,这样消息的处理会放在这个线程中
        mHandler = new PowerManagerHandler(mHandlerThread.getLooper());

        synchronized (mLock) {
            mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks");
            mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display");
   //防止cpu进入睡眠状态
            mDisplaySuspendBlocker.acquire();
            mHoldingDisplaySuspendBlocker = true;
            mHalAutoSuspendModeEnabled = false;
            mHalInteractiveModeEnabled = true;
   //当前系统状态正常运行状态
            mWakefulness = WAKEFULNESS_AWAKE;

            nativeInit();
            nativeSetAutoSuspend(false);
            nativeSetInteractive(true);
        }
    }

构造函数比较简单,创建了一个接受消息处理的线程,cpu持锁不让手机睡眠,以及一些变量的初始化。

SystemServer创建完PowerManagerService后,继续调用SystemReady方法,再做一些初始化的工作,代码如下:

  1. public void systemReady(IAppOpsService appOps) {  
  2.         synchronized (mLock) {  
  3.             mSystemReady = true;  
  4.             mAppOps = appOps;  
  5.             //android5.0后的新方法,localService可以直接取,在4.4中这样service是在init中传对象进来的  
  6.             mDreamManager = getLocalService(DreamManagerInternal.class);  
  7.             mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);  
  8.             mPolicy = getLocalService(WindowManagerPolicy.class);  
  9.             mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);  
  10.   
  11.             PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);  
  12.             //获取缺省、最大、最小屏幕亮度  
  13.             mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();  
  14.             mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();  
  15.             mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();  
  16.             //创建sensorManager和sersorservice交互  
  17.             SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());  
  18.   
  19.             // The notifier runs on the system server's main looper so as not to interfere  
  20.             // with the animations and other critical functions of the power manager.  
  21.             mBatteryStats = BatteryStatsService.getService();  
  22.             mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats,  
  23.                     mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"),  
  24.                     mPolicy);  
  25.             //创建检测无线充电的对象  
  26.             mWirelessChargerDetector = new WirelessChargerDetector(sensorManager,  
  27.                     createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"),  
  28.                     mHandler);  
  29.             mSettingsObserver = new SettingsObserver(mHandler);  
  30.   
  31.             mLightsManager = getLocalService(LightsManager.class);  
  32.             mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);  
  33.   
  34.             // Initialize display power management.  
  35.             mDisplayManagerInternal.initPowerManagement(  
  36.                     mDisplayPowerCallbacks, mHandler, sensorManager);  
  37.   
  38.             // Register for broadcasts from other components of the system.  
  39.             //监听其他模块的广播  
  40.             IntentFilter filter = new IntentFilter();  
  41.             filter.addAction(Intent.ACTION_BATTERY_CHANGED);  
  42.             filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);  
  43.             mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);  
  44.   
  45.             filter = new IntentFilter();  
  46.             filter.addAction(Intent.ACTION_DREAMING_STARTED);  
  47.             filter.addAction(Intent.ACTION_DREAMING_STOPPED);  
  48.             mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);  
  49.   
  50.             filter = new IntentFilter();  
  51.             filter.addAction(Intent.ACTION_USER_SWITCHED);  
  52.             mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);  
  53.   
  54.             filter = new IntentFilter();  
  55.             filter.addAction(Intent.ACTION_DOCK_EVENT);  
  56.             mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);  
  57.   
  58.             // Register for settings changes.  
  59.             final ContentResolver resolver = mContext.getContentResolver();  
  60.             resolver.registerContentObserver(Settings.Secure.getUriFor(  
  61.                     Settings.Secure.SCREENSAVER_ENABLED),  
  62.                     false, mSettingsObserver, UserHandle.USER_ALL);  
  63.             resolver.registerContentObserver(Settings.Secure.getUriFor(  
  64.                     Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),  
  65.                     false, mSettingsObserver, UserHandle.USER_ALL);  
  66.             resolver.registerContentObserver(Settings.Secure.getUriFor(  
  67.                     Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),  
  68.                     false, mSettingsObserver, UserHandle.USER_ALL);  
  69.             resolver.registerContentObserver(Settings.System.getUriFor(  
  70.                     Settings.System.SCREEN_OFF_TIMEOUT),  
  71.                     false, mSettingsObserver, UserHandle.USER_ALL);  
  72.             resolver.registerContentObserver(Settings.Secure.getUriFor(  
  73.                     Settings.Secure.SLEEP_TIMEOUT),  
  74.                     false, mSettingsObserver, UserHandle.USER_ALL);  
  75.             resolver.registerContentObserver(Settings.Global.getUriFor(  
  76.                     Settings.Global.STAY_ON_WHILE_PLUGGED_IN),  
  77.                     false, mSettingsObserver, UserHandle.USER_ALL);  
  78.             resolver.registerContentObserver(Settings.System.getUriFor(  
  79.                     Settings.System.SCREEN_BRIGHTNESS),  
  80.                     false, mSettingsObserver, UserHandle.USER_ALL);  
  81.             resolver.registerContentObserver(Settings.System.getUriFor(  
  82.                     Settings.System.SCREEN_BRIGHTNESS_MODE),  
  83.                     false, mSettingsObserver, UserHandle.USER_ALL);  
  84.             resolver.registerContentObserver(Settings.System.getUriFor(  
  85.                     Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),  
  86.                     false, mSettingsObserver, UserHandle.USER_ALL);  
  87.             resolver.registerContentObserver(Settings.Global.getUriFor(  
  88.                     Settings.Global.LOW_POWER_MODE),  
  89.                     false, mSettingsObserver, UserHandle.USER_ALL);  
  90.             resolver.registerContentObserver(Settings.Global.getUriFor(  
  91.                     Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL),  
  92.                     false, mSettingsObserver, UserHandle.USER_ALL);  
  93.             resolver.registerContentObserver(Settings.Global.getUriFor(  
  94.                     Settings.Global.THEATER_MODE_ON),  
  95.                     false, mSettingsObserver, UserHandle.USER_ALL);  
  96.             // Go.  
  97.             readConfigurationLocked();  
  98.             updateSettingsLocked();  
  99.             mDirty |= DIRTY_BATTERY_STATE;  
  100.             updatePowerStateLocked();  
  101.         }  
  102.     }  
public void systemReady(IAppOpsService appOps) {
        synchronized (mLock) {
            mSystemReady = true;
            mAppOps = appOps;
            //android5.0后的新方法,localService可以直接取,在4.4中这样service是在init中传对象进来的
            mDreamManager = getLocalService(DreamManagerInternal.class);
            mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
            mPolicy = getLocalService(WindowManagerPolicy.class);
            mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);

            PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
            //获取缺省、最大、最小屏幕亮度
            mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
            mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
            mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
            //创建sensorManager和sersorservice交互
            SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());

            // The notifier runs on the system server's main looper so as not to interfere
            // with the animations and other critical functions of the power manager.
            mBatteryStats = BatteryStatsService.getService();
            mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats,
                    mAppOps, createSuspendBlockerLocked("PowerManagerService.Broadcasts"),
                    mPolicy);
            //创建检测无线充电的对象
            mWirelessChargerDetector = new WirelessChargerDetector(sensorManager,
                    createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"),
                    mHandler);
            mSettingsObserver = new SettingsObserver(mHandler);

            mLightsManager = getLocalService(LightsManager.class);
            mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);

            // Initialize display power management.
            mDisplayManagerInternal.initPowerManagement(
                    mDisplayPowerCallbacks, mHandler, sensorManager);

            // Register for broadcasts from other components of the system.
            //监听其他模块的广播
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_BATTERY_CHANGED);
            filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
            mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);

            filter = new IntentFilter();
            filter.addAction(Intent.ACTION_DREAMING_STARTED);
            filter.addAction(Intent.ACTION_DREAMING_STOPPED);
            mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);

            filter = new IntentFilter();
            filter.addAction(Intent.ACTION_USER_SWITCHED);
            mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);

            filter = new IntentFilter();
            filter.addAction(Intent.ACTION_DOCK_EVENT);
            mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);

            // Register for settings changes.
            final ContentResolver resolver = mContext.getContentResolver();
            resolver.registerContentObserver(Settings.Secure.getUriFor(
                    Settings.Secure.SCREENSAVER_ENABLED),
                    false, mSettingsObserver, UserHandle.USER_ALL);
            resolver.registerContentObserver(Settings.Secure.getUriFor(
                    Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
                    false, mSettingsObserver, UserHandle.USER_ALL);
            resolver.registerContentObserver(Settings.Secure.getUriFor(
                    Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
                    false, mSettingsObserver, UserHandle.USER_ALL);
            resolver.registerContentObserver(Settings.System.getUriFor(
                    Settings.System.SCREEN_OFF_TIMEOUT),
                    false, mSettingsObserver, UserHandle.USER_ALL);
            resolver.registerContentObserver(Settings.Secure.getUriFor(
                    Settings.Secure.SLEEP_TIMEOUT),
                    false, mSettingsObserver, UserHandle.USER_ALL);
            resolver.registerContentObserver(Settings.Global.getUriFor(
                    Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
                    false, mSettingsObserver, UserHandle.USER_ALL);
            resolver.registerContentObserver(Settings.System.getUriFor(
                    Settings.System.SCREEN_BRIGHTNESS),
                    false, mSettingsObserver, UserHandle.USER_ALL);
            resolver.registerContentObserver(Settings.System.getUriFor(
                    Settings.System.SCREEN_BRIGHTNESS_MODE),
                    false, mSettingsObserver, UserHandle.USER_ALL);
            resolver.registerContentObserver(Settings.System.getUriFor(
                    Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),
                    false, mSettingsObserver, UserHandle.USER_ALL);
            resolver.registerContentObserver(Settings.Global.getUriFor(
                    Settings.Global.LOW_POWER_MODE),
                    false, mSettingsObserver, UserHandle.USER_ALL);
            resolver.registerContentObserver(Settings.Global.getUriFor(
                    Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL),
                    false, mSettingsObserver, UserHandle.USER_ALL);
            resolver.registerContentObserver(Settings.Global.getUriFor(
                    Settings.Global.THEATER_MODE_ON),
                    false, mSettingsObserver, UserHandle.USER_ALL);
            // Go.
            readConfigurationLocked();
            updateSettingsLocked();
            mDirty |= DIRTY_BATTERY_STATE;
            updatePowerStateLocked();
        }
    }


从在android5.1.1中,service一般都会继承一个虚类SystemService,在其中定义了两个接口onStart和onBootPhase,分别是PowerManagerService启动的时候会调用,而onBootPhase会在系统启动的各个阶段来调用,下面我们分别来看看在powerManagerService中这两个函数的实现:

  1. @Override  
  2. public void onStart() {  
  3.     publishBinderService(Context.POWER_SERVICE, new BinderService());  
  4.     publishLocalService(PowerManagerInternal.classnew LocalService());  
  5.   
  6.     Watchdog.getInstance().addMonitor(this);  
  7.     Watchdog.getInstance().addThread(mHandler);  
  8. }  
    @Override
    public void onStart() {
        publishBinderService(Context.POWER_SERVICE, new BinderService());
        publishLocalService(PowerManagerInternal.class, new LocalService());

        Watchdog.getInstance().addMonitor(this);
        Watchdog.getInstance().addThread(mHandler);
    }

在onstart函数中,必须把一些接口publish,像在之前Binder的接口,都是通过PowerManagerService extends IPowerManager.Stub形式在PowerManagerService中实现接口

而在android5.1.1中都是通过方式重新定义一个类,然后把这个类publish出去。

  1. private final class BinderService extends IPowerManager.Stub {  
  2.     @Override // Binder call  
  3.     public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,  
  4.             String packageName, int uid) {  
  5.         if (uid < 0) {  
  6.             uid = Binder.getCallingUid();  
  7.         }  
  8.         acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);  
  9.     }  
  10.   
  11.     @Override // Binder call  
  12.     public void powerHint(int hintId, int data) {  
  13.         if (!mSystemReady) {  
  14.             // Service not ready yet, so who the heck cares about power hints, bah.  
  15.             return;  
  16.         }  
  17.         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);  
  18.         powerHintInternal(hintId, data);  
  19.     }  
  20.   
  21.     @Override // Binder call  
  22.     public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,  
  23.             WorkSource ws, String historyTag) {  
    private final class BinderService extends IPowerManager.Stub {
        @Override // Binder call
        public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
                String packageName, int uid) {
            if (uid < 0) {
                uid = Binder.getCallingUid();
            }
            acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
        }

        @Override // Binder call
        public void powerHint(int hintId, int data) {
            if (!mSystemReady) {
                // Service not ready yet, so who the heck cares about power hints, bah.
                return;
            }
            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
            powerHintInternal(hintId, data);
        }

        @Override // Binder call
        public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
                WorkSource ws, String historyTag) {
  1. 。。。。。。。。。。。。。。  
。。。。。。。。。。。。。。
而localservice都是一些本地的服务,不是通过Binder实现的。

    我们接下来从,powerManager中的wakeLock说起,在powerManager中调用newWakeLock接口会生成一个WakeLock对象,而调用器acqure方法,最终会调用PowerManagerService中的acquireWakeLock方法

而具体的WakeLock有几种如下:

PARTIAL_WAKE_LOCK:只保持CPU运行,屏幕和键盘光关闭。

FULL_WAKE_LOCK:都不关闭

SCREEN_BRIGHT_WAKE_LOCK:屏幕背光不关闭,键盘光关闭

SCREEN_DIM_WAKE_LOCK:屏幕背光不关闭,键盘光关闭。但是屏幕背光可以变暗

PROXIMITY_SCREEN_OFF_WAKE_LOCK当持有这种类型wakelock,当距离传感器被遮挡,屏幕将被关闭。打电话时用这个功能

在PowerManagerService中的acquieWakeLock先要检查权限然后调用acquireWakeLockInternal接口,代码如下:

  1. private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,  
  2.           WorkSource ws, String historyTag, int uid, int pid) {  
  3.       synchronized (mLock) {  
  4.           WakeLock wakeLock;  
  5.           //查找wakelock  
  6.           int index = findWakeLockIndexLocked(lock);  
  7.           boolean notifyAcquire;  
  8.           if (index >= 0) {查找到  
  9.               wakeLock = mWakeLocks.get(index);  
  10.               if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {属性不一样,更新  
  11.                   // Update existing wake lock.  This shouldn't happen but is harmless.  
  12.                   notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,  
  13.                           uid, pid, ws, historyTag);  
  14.                   wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);  
  15.               }  
  16.               notifyAcquire = false;  
  17.           } else {没找到,重新建立,添加  
  18.               wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid);  
  19.               try {  
  20.                   lock.linkToDeath(wakeLock, 0);  
  21.               } catch (RemoteException ex) {  
  22.                   throw new IllegalArgumentException("Wake lock is already dead.");  
  23.               }  
  24.               mWakeLocks.add(wakeLock);  
  25.               notifyAcquire = true;  
  26.           }  
  27.           //看是否需要点亮屏幕  
  28.           applyWakeLockFlagsOnAcquireLocked(wakeLock, uid);  
  29.           //整个PowermanagerService用来记录各个状态变化的一个标志位  
  30.           mDirty |= DIRTY_WAKE_LOCKS;  
  31.           //更新各个状态  
  32.           updatePowerStateLocked();  
  33.           if (notifyAcquire) {  
  34.               // This needs to be done last so we are sure we have acquired the  
  35.               // kernel wake lock.  Otherwise we have a race where the system may  
  36.               // go to sleep between the time we start the accounting in battery  
  37.               // stats and when we actually get around to telling the kernel to  
  38.               // stay awake.  
  39.               notifyWakeLockAcquiredLocked(wakeLock);  
  40.           }  
  41.       }  
  42.   }  
  private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
            WorkSource ws, String historyTag, int uid, int pid) {
        synchronized (mLock) {
            WakeLock wakeLock;
            //查找wakelock
            int index = findWakeLockIndexLocked(lock);
            boolean notifyAcquire;
            if (index >= 0) {查找到
                wakeLock = mWakeLocks.get(index);
                if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {属性不一样,更新
                    // Update existing wake lock.  This shouldn't happen but is harmless.
                    notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
                            uid, pid, ws, historyTag);
                    wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);
                }
                notifyAcquire = false;
            } else {没找到,重新建立,添加
                wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid);
                try {
                    lock.linkToDeath(wakeLock, 0);
                } catch (RemoteException ex) {
                    throw new IllegalArgumentException("Wake lock is already dead.");
                }
                mWakeLocks.add(wakeLock);
                notifyAcquire = true;
            }
            //看是否需要点亮屏幕
            applyWakeLockFlagsOnAcquireLocked(wakeLock, uid);
            //整个PowermanagerService用来记录各个状态变化的一个标志位
            mDirty |= DIRTY_WAKE_LOCKS;
            //更新各个状态
            updatePowerStateLocked();
            if (notifyAcquire) {
                // This needs to be done last so we are sure we have acquired the
                // kernel wake lock.  Otherwise we have a race where the system may
                // go to sleep between the time we start the accounting in battery
                // stats and when we actually get around to telling the kernel to
                // stay awake.
                notifyWakeLockAcquiredLocked(wakeLock);
            }
        }
    }

整个PowermanagerService都是靠一个mDirty的各个标志位来记录各个状态的变化,随后会调用一个updatePowerStateLocked来更新各个状态。

同样解锁会调用到releaseWakeLockInternal,代码如下:

  1.  private void releaseWakeLockInternal(IBinder lock, int flags) {  
  2.         synchronized (mLock) {  
  3.             int index = findWakeLockIndexLocked(lock);  
  4.             if (index < 0) {//没有找到退出  
  5.                 if (DEBUG_SPEW) {  
  6.                     Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)  
  7.                             + " [not found], flags=0x" + Integer.toHexString(flags));  
  8.                 }  
  9.                 return;  
  10.             }  
  11.   
  12.             WakeLock wakeLock = mWakeLocks.get(index);  
  13.             if (DEBUG_SPEW) {  
  14.                 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)  
  15.                         + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));  
  16.             }  
  17.   
  18.             if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {  
  19.                 mRequestWaitForNegativeProximity = true;  
  20.             }  
  21.             //去除wakelock  
  22.             wakeLock.mLock.unlinkToDeath(wakeLock, 0);  
  23.             removeWakeLockLocked(wakeLock, index);  
  24.         }  
  25.     }  
  26.   
  27. PowerManagerService中最终各个接口都会调一个函数updatePowerStateLocked,主要用来更新power的各个状态  
  28.   
  29. private void updatePowerStateLocked() {  
  30.         if (!mSystemReady || mDirty == 0) {各个状态没有变化  
  31.             return;  
  32.         }  
  33.         if (!Thread.holdsLock(mLock)) {  
  34.             Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");  
  35.         }  
  36.   
  37.         Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");  
  38.         try {  
  39.             // Phase 0: Basic state updates.  
  40.             //更新充电的各个状态(是否充电、电池电量、充电方式、是否低电量),以及更新低功耗模式(android5.0增加的)  
  41.             updateIsPoweredLocked(mDirty);  
  42.             //更新mStayOn状态,为true,屏幕常亮  
  43.             updateStayOnLocked(mDirty);  
  44.             //更新屏幕是否最亮的状态是否持续  
  45.             updateScreenBrightnessBoostLocked(mDirty);  
  46.   
  47.             // Phase 1: Update wakefulness.  
  48.             // Loop because the wake lock and user activity computations are influenced  
  49.             // by changes in wakefulness.  
  50.             final long now = SystemClock.uptimeMillis();  
  51.             int dirtyPhase2 = 0;  
  52.             for (;;) {  
  53.                 int dirtyPhase1 = mDirty;  
  54.                 dirtyPhase2 |= dirtyPhase1;  
  55.                 mDirty = 0;  
  56.                 //更新mWakeLockSummary的状态  
  57.                 updateWakeLockSummaryLocked(dirtyPhase1);  
  58.                 //更新mUserActivitySummary状态  
  59.                 updateUserActivitySummaryLocked(now, dirtyPhase1);  
  60.                 if (!updateWakefulnessLocked(dirtyPhase1)) {  
  61.                     break;  
  62.                 }  
  63.             }  
  64.   
  65.             // Phase 2: Update display power state.  
  66.             boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);//更新display状态,在displaypowercontrol中会控制亮度,灭屏等  
  67.   
  68.             // Phase 3: Update dream state (depends on display ready signal).  
  69.             //更新梦的状态,用dreammanager控制梦,powermanagerservice中记录mWakefulness  
  70.             updateDreamLocked(dirtyPhase2, displayBecameReady);  
  71.   
  72.             // Phase 4: Send notifications, if needed.  
  73.             if (mDisplayReady) {  
  74.                 finishWakefulnessChangeLocked();  
  75.             }  
  76.   
  77.             // Phase 5: Update suspend blocker.  
  78.             // Because we might release the last suspend blocker here, we need to make sure  
  79.             // we finished everything else first!  
  80.             //更新睡眠锁,以及是否持锁和释放锁  
  81.             updateSuspendBlockerLocked();  
  82.         } finally {  
  83.             Trace.traceEnd(Trace.TRACE_TAG_POWER);  
  84.         }  
  85.     }  
 private void releaseWakeLockInternal(IBinder lock, int flags) {
        synchronized (mLock) {
            int index = findWakeLockIndexLocked(lock);
            if (index < 0) {//没有找到退出
                if (DEBUG_SPEW) {
                    Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
                            + " [not found], flags=0x" + Integer.toHexString(flags));
                }
                return;
            }

            WakeLock wakeLock = mWakeLocks.get(index);
            if (DEBUG_SPEW) {
                Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
                        + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
            }

            if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
                mRequestWaitForNegativeProximity = true;
            }
            //去除wakelock
            wakeLock.mLock.unlinkToDeath(wakeLock, 0);
            removeWakeLockLocked(wakeLock, index);
        }
    }

PowerManagerService中最终各个接口都会调一个函数updatePowerStateLocked,主要用来更新power的各个状态

private void updatePowerStateLocked() {
        if (!mSystemReady || mDirty == 0) {各个状态没有变化
            return;
        }
        if (!Thread.holdsLock(mLock)) {
            Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
        }

        Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
        try {
            // Phase 0: Basic state updates.
            //更新充电的各个状态(是否充电、电池电量、充电方式、是否低电量),以及更新低功耗模式(android5.0增加的)
            updateIsPoweredLocked(mDirty);
            //更新mStayOn状态,为true,屏幕常亮
            updateStayOnLocked(mDirty);
            //更新屏幕是否最亮的状态是否持续
            updateScreenBrightnessBoostLocked(mDirty);

            // Phase 1: Update wakefulness.
            // Loop because the wake lock and user activity computations are influenced
            // by changes in wakefulness.
            final long now = SystemClock.uptimeMillis();
            int dirtyPhase2 = 0;
            for (;;) {
                int dirtyPhase1 = mDirty;
                dirtyPhase2 |= dirtyPhase1;
                mDirty = 0;
                //更新mWakeLockSummary的状态
                updateWakeLockSummaryLocked(dirtyPhase1);
                //更新mUserActivitySummary状态
                updateUserActivitySummaryLocked(now, dirtyPhase1);
                if (!updateWakefulnessLocked(dirtyPhase1)) {
                    break;
                }
            }

            // Phase 2: Update display power state.
            boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);//更新display状态,在displaypowercontrol中会控制亮度,灭屏等

            // Phase 3: Update dream state (depends on display ready signal).
            //更新梦的状态,用dreammanager控制梦,powermanagerservice中记录mWakefulness
            updateDreamLocked(dirtyPhase2, displayBecameReady);

            // Phase 4: Send notifications, if needed.
            if (mDisplayReady) {
                finishWakefulnessChangeLocked();
            }

            // Phase 5: Update suspend blocker.
            // Because we might release the last suspend blocker here, we need to make sure
            // we finished everything else first!
            //更新睡眠锁,以及是否持锁和释放锁
            updateSuspendBlockerLocked();
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_POWER);
        }
    }


updateIsPoweredLocked、updateStayOnLocked、updateScreenBrightnessBoostLocked、updateWakeLockSummaryLocked、updateUserActivitySummaryLocked都是比较简单、在上面的函数注释中都有介绍。下面我们先看下updateWakefulnessLocked函数,代码如下:
  1. private boolean updateWakefulnessLocked(int dirty) {  
  2.     boolean changed = false;  
  3.     if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED  
  4.             | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE  
  5.             | DIRTY_DOCK_STATE)) != 0) {  
  6.         //当前状态是醒着,并且准备开始睡眠了  
  7.         if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {  
  8.             if (DEBUG_SPEW) {  
  9.                 Slog.d(TAG, "updateWakefulnessLocked: Bed time...");  
  10.             }  
  11.             final long time = SystemClock.uptimeMillis();  
  12.             //是应该开始做梦,还是先睡眠  
  13.             if (shouldNapAtBedTimeLocked()) {  
  14.                 //当前状态设置为睡眠状态  
  15.                 changed = napNoUpdateLocked(time, Process.SYSTEM_UID);  
  16.             } else {  
  17.                 //当前状态设置为假寐状态  
  18.                 changed = goToSleepNoUpdateLocked(time,  
  19.                         PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);  
  20.             }  
  21.         }  
  22.     }  
  23.     return changed;  
  24. }  
    private boolean updateWakefulnessLocked(int dirty) {
        boolean changed = false;
        if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
                | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
                | DIRTY_DOCK_STATE)) != 0) {
            //当前状态是醒着,并且准备开始睡眠了
            if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
                if (DEBUG_SPEW) {
                    Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
                }
                final long time = SystemClock.uptimeMillis();
                //是应该开始做梦,还是先睡眠
                if (shouldNapAtBedTimeLocked()) {
                    //当前状态设置为睡眠状态
                    changed = napNoUpdateLocked(time, Process.SYSTEM_UID);
                } else {
                    //当前状态设置为假寐状态
                    changed = goToSleepNoUpdateLocked(time,
                            PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
                }
            }
        }
        return changed;
    }
  1. private boolean isBeingKeptAwakeLocked() {  
  2.     return mStayOn  
  3.             || mProximityPositive//距离传感器  
  4.             || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0//wakelock锁  
  5.             || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT  
  6.                     | USER_ACTIVITY_SCREEN_DIM)) != 0//用户行为、和用户点击屏幕、自动灭屏时间等有关  
  7.             || mScreenBrightnessBoostInProgress;\\是否要保持处于最亮状态  
  8. }  
  9.   
  10.   
  11. private boolean isItBedTimeYetLocked() {  
  12. //当启动完成、并且设备不必保持唤醒状态是的时候返回true  
  13.     return mBootCompleted && !isBeingKeptAwakeLocked();  
  14. }  
    private boolean isBeingKeptAwakeLocked() {
        return mStayOn
                || mProximityPositive//距离传感器
                || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0//wakelock锁
                || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
                        | USER_ACTIVITY_SCREEN_DIM)) != 0//用户行为、和用户点击屏幕、自动灭屏时间等有关
                || mScreenBrightnessBoostInProgress;\\是否要保持处于最亮状态
    }
    
    
    private boolean isItBedTimeYetLocked() {
    //当启动完成、并且设备不必保持唤醒状态是的时候返回true
        return mBootCompleted && !isBeingKeptAwakeLocked();
    }

updateDreamLocked函数通过发送消息,最终会调用handleSandman:

  1. private void handleSandman() { // runs on handler thread  
  2.     // Handle preconditions.  
  3.     final boolean startDreaming;  
  4.     final int wakefulness;  
  5.     synchronized (mLock) {  
  6.         mSandmanScheduled = false;  
  7.         wakefulness = mWakefulness;  
  8.         if (mSandmanSummoned && mDisplayReady) {  
  9.             startDreaming = canDreamLocked() || canDozeLocked();  
  10.             mSandmanSummoned = false;  
  11.         } else {  
  12.             startDreaming = false;  
  13.         }  
  14.     }  
  15.   
  16.     // Start dreaming if needed.  
  17.     // We only control the dream on the handler thread, so we don't need to worry about  
  18.     // concurrent attempts to start or stop the dream.  
  19.     final boolean isDreaming;  
  20.     if (mDreamManager != null) {  
  21.         // Restart the dream whenever the sandman is summoned.  
  22.         if (startDreaming) {  
  23.             mDreamManager.stopDream(false /*immediate*/);  
  24.             mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);  
  25.         }  
  26.         isDreaming = mDreamManager.isDreaming();  
  27.     } else {  
  28.         isDreaming = false;  
  29.     }  
  30.   
  31.     // Update dream state.  
  32.     synchronized (mLock) {  
  33.         // Remember the initial battery level when the dream started.  
  34.         if (startDreaming && isDreaming) {  
  35.             mBatteryLevelWhenDreamStarted = mBatteryLevel;  
  36.             if (wakefulness == WAKEFULNESS_DOZING) {  
  37.                 Slog.i(TAG, "Dozing...");  
  38.             } else {  
  39.                 Slog.i(TAG, "Dreaming...");  
  40.             }  
  41.         }  
  42.   
  43.         // If preconditions changed, wait for the next iteration to determine  
  44.         // whether the dream should continue (or be restarted).  
  45.         if (mSandmanSummoned || mWakefulness != wakefulness) {  
  46.             return// wait for next cycle  
  47.         }  
  48.   
  49.         // Determine whether the dream should continue.  
  50.         if (wakefulness == WAKEFULNESS_DREAMING) {  
  51.             if (isDreaming && canDreamLocked()) {  
  52.                 //在做梦中  
  53.                 if (mDreamsBatteryLevelDrainCutoffConfig >= 0  
  54.                         && mBatteryLevel < mBatteryLevelWhenDreamStarted  
  55.                                 - mDreamsBatteryLevelDrainCutoffConfig  
  56.                         && !isBeingKeptAwakeLocked()) {  
  57.                     // If the user activity timeout expired and the battery appears  
  58.                     // to be draining faster than it is charging then stop dreaming  
  59.                     // and go to sleep.  
  60.                     Slog.i(TAG, "Stopping dream because the battery appears to "  
  61.                             + "be draining faster than it is charging.  "  
  62.                             + "Battery level when dream started: "  
  63.                             + mBatteryLevelWhenDreamStarted + "%.  "  
  64.                             + "Battery level now: " + mBatteryLevel + "%.");  
  65.                 } else {  
  66.                     //继续做梦  
  67.                     return// continue dreaming  
  68.                 }  
  69.             }  
  70.   
  71.             // Dream has ended or will be stopped.  Update the power state.  
  72.             //结束做梦,要么唤醒、要么继续goToSleep  
  73.             if (isItBedTimeYetLocked()) {  
  74.                 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),  
  75.                         PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);  
  76.                 updatePowerStateLocked();  
  77.             } else {  
  78.                 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);  
  79.                 updatePowerStateLocked();  
  80.             }  
  81.         } else if (wakefulness == WAKEFULNESS_DOZING) {  
  82.             if (isDreaming) {  
  83.                 return// continue dozing  
  84.             }  
  85.             //直接睡眠,跳过做梦  
  86.             // Doze has ended or will be stopped.  Update the power state.  
  87.             reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);  
  88.             updatePowerStateLocked();  
  89.         }  
  90.     }  
  91.   
  92.     // Stop dream.能走到这说明,肯定结束做梦  
  93.     if (isDreaming) {  
  94.         mDreamManager.stopDream(false /*immediate*/);  
  95.     }  
  96. }  
    private void handleSandman() { // runs on handler thread
        // Handle preconditions.
        final boolean startDreaming;
        final int wakefulness;
        synchronized (mLock) {
            mSandmanScheduled = false;
            wakefulness = mWakefulness;
            if (mSandmanSummoned && mDisplayReady) {
                startDreaming = canDreamLocked() || canDozeLocked();
                mSandmanSummoned = false;
            } else {
                startDreaming = false;
            }
        }

        // Start dreaming if needed.
        // We only control the dream on the handler thread, so we don't need to worry about
        // concurrent attempts to start or stop the dream.
        final boolean isDreaming;
        if (mDreamManager != null) {
            // Restart the dream whenever the sandman is summoned.
            if (startDreaming) {
                mDreamManager.stopDream(false /*immediate*/);
                mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
            }
            isDreaming = mDreamManager.isDreaming();
        } else {
            isDreaming = false;
        }

        // Update dream state.
        synchronized (mLock) {
            // Remember the initial battery level when the dream started.
            if (startDreaming && isDreaming) {
                mBatteryLevelWhenDreamStarted = mBatteryLevel;
                if (wakefulness == WAKEFULNESS_DOZING) {
                    Slog.i(TAG, "Dozing...");
                } else {
                    Slog.i(TAG, "Dreaming...");
                }
            }

            // If preconditions changed, wait for the next iteration to determine
            // whether the dream should continue (or be restarted).
            if (mSandmanSummoned || mWakefulness != wakefulness) {
                return; // wait for next cycle
            }

            // Determine whether the dream should continue.
            if (wakefulness == WAKEFULNESS_DREAMING) {
                if (isDreaming && canDreamLocked()) {
                    //在做梦中
                    if (mDreamsBatteryLevelDrainCutoffConfig >= 0
                            && mBatteryLevel < mBatteryLevelWhenDreamStarted
                                    - mDreamsBatteryLevelDrainCutoffConfig
                            && !isBeingKeptAwakeLocked()) {
                        // If the user activity timeout expired and the battery appears
                        // to be draining faster than it is charging then stop dreaming
                        // and go to sleep.
                        Slog.i(TAG, "Stopping dream because the battery appears to "
                                + "be draining faster than it is charging.  "
                                + "Battery level when dream started: "
                                + mBatteryLevelWhenDreamStarted + "%.  "
                                + "Battery level now: " + mBatteryLevel + "%.");
                    } else {
                        //继续做梦
                        return; // continue dreaming
                    }
                }

                // Dream has ended or will be stopped.  Update the power state.
                //结束做梦,要么唤醒、要么继续goToSleep
                if (isItBedTimeYetLocked()) {
                    goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
                            PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
                    updatePowerStateLocked();
                } else {
                    wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
                    updatePowerStateLocked();
                }
            } else if (wakefulness == WAKEFULNESS_DOZING) {
                if (isDreaming) {
                    return; // continue dozing
                }
                //直接睡眠,跳过做梦
                // Doze has ended or will be stopped.  Update the power state.
                reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
                updatePowerStateLocked();
            }
        }

        // Stop dream.能走到这说明,肯定结束做梦
        if (isDreaming) {
            mDreamManager.stopDream(false /*immediate*/);
        }
    }
updateSuspendBlockerLocked函数是是否要Cpu持锁。

  1. private void updateSuspendBlockerLocked() {  
  2.     final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);//是否要cpu持锁  
  3.     final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();//是否display要持锁  
  4.     final boolean autoSuspend = !needDisplaySuspendBlocker;  
  5.     final boolean interactive = mDisplayPowerRequest.isBrightOrDim();  
  6.   
  7.     // Disable auto-suspend if needed.  
  8.     // FIXME We should consider just leaving auto-suspend enabled forever since  
  9.     // we already hold the necessary wakelocks.  
  10.     if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {  
  11.         setHalAutoSuspendModeLocked(false);  
  12.     }  
  13.   
  14.     // First acquire suspend blockers if needed.  
  15.     if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {  
  16.         mWakeLockSuspendBlocker.acquire();  
  17.         mHoldingWakeLockSuspendBlocker = true;  
  18.     }  
  19.     if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {  
  20.         mDisplaySuspendBlocker.acquire();  
  21.         mHoldingDisplaySuspendBlocker = true;  
  22.     }  
  23.   
  24.     // Inform the power HAL about interactive mode.  
  25.     // Although we could set interactive strictly based on the wakefulness  
  26.     // as reported by isInteractive(), it is actually more desirable to track  
  27.     // the display policy state instead so that the interactive state observed  
  28.     // by the HAL more accurately tracks transitions between AWAKE and DOZING.  
  29.     // Refer to getDesiredScreenPolicyLocked() for details.  
  30.     if (mDecoupleHalInteractiveModeFromDisplayConfig) {  
  31.         // When becoming non-interactive, we want to defer sending this signal  
  32.         // until the display is actually ready so that all transitions have  
  33.         // completed.  This is probably a good sign that things have gotten  
  34.         // too tangled over here...  
  35.         if (interactive || mDisplayReady) {//当屏幕亮着|| 当屏幕暗着,displayPowerControl准备好了,进入该条件设置  
  36.             setHalInteractiveModeLocked(interactive);  
  37.         }  
  38.     }  
  39.   
  40.     // Then release suspend blockers if needed.  
  41.     if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {  
  42.         mWakeLockSuspendBlocker.release();  
  43.         mHoldingWakeLockSuspendBlocker = false;  
  44.     }  
  45.     if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {  
  46.         mDisplaySuspendBlocker.release();  
  47.         mHoldingDisplaySuspendBlocker = false;  
  48.     }  
  49.   
  50.     // Enable auto-suspend if needed.  
  51.     if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {  
  52.         setHalAutoSuspendModeLocked(true);  
  53.     }  
  54. }  
    private void updateSuspendBlockerLocked() {
        final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);//是否要cpu持锁
        final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();//是否display要持锁
        final boolean autoSuspend = !needDisplaySuspendBlocker;
        final boolean interactive = mDisplayPowerRequest.isBrightOrDim();

        // Disable auto-suspend if needed.
        // FIXME We should consider just leaving auto-suspend enabled forever since
        // we already hold the necessary wakelocks.
        if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
            setHalAutoSuspendModeLocked(false);
        }

        // First acquire suspend blockers if needed.
        if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
            mWakeLockSuspendBlocker.acquire();
            mHoldingWakeLockSuspendBlocker = true;
        }
        if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
            mDisplaySuspendBlocker.acquire();
            mHoldingDisplaySuspendBlocker = true;
        }

        // Inform the power HAL about interactive mode.
        // Although we could set interactive strictly based on the wakefulness
        // as reported by isInteractive(), it is actually more desirable to track
        // the display policy state instead so that the interactive state observed
        // by the HAL more accurately tracks transitions between AWAKE and DOZING.
        // Refer to getDesiredScreenPolicyLocked() for details.
        if (mDecoupleHalInteractiveModeFromDisplayConfig) {
            // When becoming non-interactive, we want to defer sending this signal
            // until the display is actually ready so that all transitions have
            // completed.  This is probably a good sign that things have gotten
            // too tangled over here...
            if (interactive || mDisplayReady) {//当屏幕亮着|| 当屏幕暗着,displayPowerControl准备好了,进入该条件设置
                setHalInteractiveModeLocked(interactive);
            }
        }

        // Then release suspend blockers if needed.
        if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
            mWakeLockSuspendBlocker.release();
            mHoldingWakeLockSuspendBlocker = false;
        }
        if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
            mDisplaySuspendBlocker.release();
            mHoldingDisplaySuspendBlocker = false;
        }

        // Enable auto-suspend if needed.
        if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
            setHalAutoSuspendModeLocked(true);
        }
    }

下来介绍下powermanager中其他的接口,
1、gotosleep,让设备睡眠,按power键会调用这个函数
  1. private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {  
  2.        synchronized (mLock) {  
  3.            //返回true,才更新状态  
  4.            if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {  
  5.                updatePowerStateLocked();  
  6.            }  
  7.        }  
  8.    }  
  9.   
  10.    @SuppressWarnings("deprecation")  
  11.    private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {  
  12.        if (DEBUG_SPEW) {  
  13.            Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime  
  14.                    + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);  
  15.        }  
  16.   
  17.        if (eventTime < mLastWakeTime  
  18.                || mWakefulness == WAKEFULNESS_ASLEEP  
  19.                || mWakefulness == WAKEFULNESS_DOZING  
  20.                || !mBootCompleted || !mSystemReady) {  
  21.            return false;  
  22.        }  
  23.   
  24.        Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");  
  25.        try {  
  26.            switch (reason) {//说明原因  
  27.                case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN:  
  28.                    Slog.i(TAG, "Going to sleep due to device administration policy "  
  29.                            + "(uid " + uid +")...");  
  30.                    break;  
  31. 。。。。。。。。。。。。  
  32.            }  
  33.   
  34.            mLastSleepTime = eventTime;  
  35.            mSandmanSummoned = true;  
  36.            setWakefulnessLocked(WAKEFULNESS_DOZING, reason);  
  37.   
  38.            // Report the number of wake locks that will be cleared by going to sleep.  
  39.            //统计wakelock的数量  
  40.            int numWakeLocksCleared = 0;  
  41.            final int numWakeLocks = mWakeLocks.size();  
  42.            for (int i = 0; i < numWakeLocks; i++) {  
  43.                final WakeLock wakeLock = mWakeLocks.get(i);  
  44.                switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {  
  45.                    case PowerManager.FULL_WAKE_LOCK:  
  46.                    case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:  
  47.                    case PowerManager.SCREEN_DIM_WAKE_LOCK:  
  48.                        numWakeLocksCleared += 1;  
  49.                        break;  
  50.                }  
  51.            }  
  52.            EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared);  
  53.   
  54.            // Skip dozing if requested.  
  55.            //直接进入睡眠  
  56.            if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {  
  57.                reallyGoToSleepNoUpdateLocked(eventTime, uid);  
  58.            }  
  59.        } finally {  
  60.            Trace.traceEnd(Trace.TRACE_TAG_POWER);  
  61.        }  
  62.        return true;  
  63.    }  
 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {
        synchronized (mLock) {
            //返回true,才更新状态
            if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {
                updatePowerStateLocked();
            }
        }
    }

    @SuppressWarnings("deprecation")
    private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {
        if (DEBUG_SPEW) {
            Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime
                    + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);
        }

        if (eventTime < mLastWakeTime
                || mWakefulness == WAKEFULNESS_ASLEEP
                || mWakefulness == WAKEFULNESS_DOZING
                || !mBootCompleted || !mSystemReady) {
            return false;
        }

        Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");
        try {
            switch (reason) {//说明原因
                case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN:
                    Slog.i(TAG, "Going to sleep due to device administration policy "
                            + "(uid " + uid +")...");
                    break;
。。。。。。。。。。。。。
            }

            mLastSleepTime = eventTime;
            mSandmanSummoned = true;
            setWakefulnessLocked(WAKEFULNESS_DOZING, reason);

            // Report the number of wake locks that will be cleared by going to sleep.
            //统计wakelock的数量
            int numWakeLocksCleared = 0;
            final int numWakeLocks = mWakeLocks.size();
            for (int i = 0; i < numWakeLocks; i++) {
                final WakeLock wakeLock = mWakeLocks.get(i);
                switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
                    case PowerManager.FULL_WAKE_LOCK:
                    case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
                    case PowerManager.SCREEN_DIM_WAKE_LOCK:
                        numWakeLocksCleared += 1;
                        break;
                }
            }
            EventLog.writeEvent(EventLogTags.POWER_SLEEP_REQUESTED, numWakeLocksCleared);

            // Skip dozing if requested.
            //直接进入睡眠
            if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {
                reallyGoToSleepNoUpdateLocked(eventTime, uid);
            }
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_POWER);
        }
        return true;
    }
2、useractivity是当用户点击屏幕等行为,会重新计算自动灭屏的时间等,然后回去updatepowerstate
3、wakeup唤醒设备,与gotosleep对应。
4、nap,使设备处于一种假寐的状态
5、boostScreenBrightness,是屏幕达到最亮持续一段时间
这其中每个函数都会调用updatepowerstate





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值