电源管理类(PowerManager)以及唤醒屏幕锁的简单介绍

2019-07-14 01:33发布

android.os.PowerManager
电源管理类

Device battery life will be significantly affected by the use of this API.
这个API直接影响了手机电池的寿命以及使用率。因为我们可以通过这个类来很好地控制电源的使用情况,怎样才能更加地省电,除了使用者的习惯之外,应用程序的性能也很重要,这就要靠这个API在程序代码中是如何实现的了。
 
//通过这句代码来获取这个类的一个实例
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//获得一个PowerManager.WakeLock对象,并且设置屏幕状态 
 
 PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag"); 设置屏幕状态需要用到这些flags,他们相对应的CPU,Screen,Keyboard的状态在下图中都可以看出来                                                                             图一 //申请WakeLock,
 wl.acquire();
   ..screen will stay on during this section..
将wakeLock release()之后,屏幕就会一直stay on
 wl.release();
 注意:如果你不是必须需要的时候就不要acquire()了,但是记住申请了之后,最后一定要release()。一般都是这样写的:  @Override
 public void onResume() {
  super.onResume();   wakeLock.acquire();
 }  @Override
 public void onPause() {
  super.onPause();   wakeLock.release();
 }   可以多个flags组合使用,他们值影响屏幕的状态,但是如何和PARTIAL_WAKE_LOCK组合的话,将没有效果。
Any application using a WakeLock must request the android.permission.WAKE_LOCK permission in an element of the application's manifest.   记录WakeLock的用法
主要是唤醒屏幕锁的意思,控制屏幕的背光,例如进入某个程序界面长时间不操作的话,这个就会帮助你是屏幕亮度变暗直至关闭,
这样做的好处很明显是为了节省手机电量,所以他属于电源管理类。
Do not acquire WakeLocks unless you really need them, use the minimum levels possible, and be sure to release it as soon as you can.
存在这个API
 android.os.PowerManager.WakeLock Call release when you are done and don't need the lock anymore. 用到这个必须要在Manifest.xml中申请权限
Any application using a WakeLock must request the android.permission.WAKE_LOCK permission in an element of the application's manifest. public PowerManager.WakeLock newWakeLock (int flags, String tag) Get a wake lock at the level of the flags parameter. Call acquire() on the object to acquire the wake lock, and release() when you are done. 首先要获取POWER_SERVICE的服务,可以控制屏幕自动背光和关闭,也可以是屏幕处于一直打开的状态,你使用 FLAG_KEEP_SCREEN_ON就可以了。这个一般在照相机的应用上用的比较多。
PowerManager pm = (PowerManager)mContext.getSystemService(
                                          Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(
                                      PowerManager.SCREEN_DIM_WAKE_LOCK
                                      | PowerManager.ON_AFTER_RELEASE,
                                      TAG);
wl.acquire();
 // ...
wl.release();
 
If using this to keep the screen on, you should strongly consider using FLAG_KEEP_SCREEN_ON instead. This window flag will be correctly managed by the platform as the user moves between applications and doesn't require a special permission. 注意:用到WakeLock必须要在AndroidManifest.xml中获取权限