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.
Any application using a WakeLock must request the android.permission.WAKE_LOCK
permission in an <uses-permission>
element of the application's manifest.
当调用 public void acquire(long timeout), 如果后面再调用release,可能会报运行时异常,因为电源锁内部的计数器小于0了。
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag"); wl.acquire(); ..screen will stay on during this section.. wl.release();
Flag Value | CPU | Screen | Keyboard |
---|---|---|---|
PARTIAL_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 |
*If you hold a partial wakelock, the CPU will continue to run, irrespective of any timers and even after the user presses the power button. In all other wakelocks, the CPU will run, but the user can still put the device to sleep using the power button.
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
.
Flag Value | Description |
---|---|
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. |
屏幕常亮:在activity的onCreate函数中:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
判断屏幕是暗还是亮:
public boolean isScreenOn ()
Returns whether the screen is currently on. The screen could be bright or dim.
重启
public void reboot (String reason)
Reboot the device. Will not return if the reboot is successful. Requires the REBOOT
permission.
public void goToSleep (long time)
Force the device to go to sleep. Overrides all the wake locks that are held.
Parameters
timeis used to order this correctly with the wake lock calls. The time should be in the SystemClock.uptimeMillis()
time base.