Android PowerManager类 控制设备电源状态 保持屏幕常亮
This class gives you control of the power state of the device.
Device battery life will be significantly affected by the use of this API. 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.
You can obtain an instance of this class by calling Context.getSystemService()
.
The primary API you'll use is newWakeLock()
. This will create a PowerManager.WakeLock
object. You can then use methods on this object to control the power state of the device.
这个类可以让你有控制设备电源状态的权限。使用此API将会明显的影响设备的电池寿命。不要使用WakeLocks除非你真的需要它们,尽可能使用最低的权限级别,并且确保不用时及时释放锁。
可以通过调用 Context.getSystemService()获得PowerManager类的实例
你将使用newWakeLock(), 创建一个 PowerManager.WakeLock 对象,然后就可以调用方法控制设备电源状态了。
下边表格是一些设定的标识,用于标识不同的状态,他们是互斥的,所以你只可以使用其中一个。
Flag ValueCPUScreenKeyboardPARTIAL_WAKE_LOCK
On*
Off
Off
SCREEN_DIM_WAKE_LOCK
On
Dim
Off
SCREEN_BRIGHT_WAKE_LOCK
On
Bright
Off
FULL_WAKE_LOCK
On
Bright
Bright
In addition, you can add two more flags, which affect behavior of the screen only. These flags have no effect when combined with a PARTIAL_WAKE_LOCK
.
此外你还可以增加两个标识,但是这个两个标识仅影响屏幕的行为。由上表可知,对PARTIAL_WAKE_LOCK 无效。
ACQUIRE_CAUSES_WAKEUP
Normal wake locks don't actually turn on the illumination. Instead, they cause the illumination to remain on once it turns on (e.g. from user activity). This flag will force the screen and/or keyboard to turn on immediately, when the WakeLock is acquired. A typical use would be for notifications which are important for the user to see immediately.
ON_AFTER_RELEASE
If this flag is set, the user activity timer will be reset when the WakeLock is released, causing the illumination to remain on a bit longer. This can be used to reduce flicker if you are cycling between wake lock conditions.
代码如下:
private static final Object sWakeLockSync = new Object(); private static final String TAG = "MainActivity"; private static PowerManager.WakeLock sWakeLock; @Override protected void onResume() { super.onResume(); synchronized (sWakeLockSync) { PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE); sWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE, TAG);
//得到锁 sWakeLock.acquire(); } } @Override protected void onPause() { super.onPause(); synchronized (sWakeLockSync) { if(sWakeLock != null){
//释放锁 sWakeLock.release(); } } }
使用同步锁,且在 onResume() 方法中创建锁,onPause()方法中释放锁,巧妙的利用了Activity的生命周期来控制锁的使用和释放。
使得acquire()和release()成对出现。
需要在AndroidiManfest.xml中配置权限
<uses-permission android:name="android.permission.WAKE_LOCK"/>
这样就可以保持在当前的Activity中保持常亮状态了。
如果其他Activity也需要常亮可以写一个这样的Activity类,然后让其他需要常亮的Activity继承即可。