To prolong the battery life, the Android device dims the screen after some time, then turns off the screen display and finally stops the CPU. Wakelock is a power management system service feature that applications can use to control the power state of a device.
The Wakelock can be used to keep the CPU running, avoid darkening and turning off the screen, and avoid the keyboard backlight off.
Note:
creating and using wake Lock can have a significant impact on battery power consumption by the application. Therefore, it is better to only
It is really necessary to use wake Lock, and the less time you use them, the better you can release them whenever possible.
Screen wake lock is typically used to prevent the screen from darkening while the user is viewing the screen but rarely interacting with the screen (for example, playing a video).
The CPU Wake lock is used to prevent the device from entering hibernation until an operation is performed. This is often the case when the service starts from within the intent sink, because the intent sink may receive the intent during device hibernation. It is worth noting that in this case, the system will use the CPU Wake Lock in the entire onreceive handler of the broadcast receiver.
Note:
If you start a service or broadcast an intent in the OnReceive handler of the broadcast receiver, it is possible that the service
Before starting, the wake Lock used will be released. To ensure that the service is able to execute, a separate wake Lock needs to be placed.
To create a wake Lock, you need to call the Power Manager's Newwakelock and specify one of the Wakelock types:
* Full_wake_lock Keep the screen fully lit, the keyboard backlight is lit and the CPU is running.
* Screen_bright_wake_lock Keep screen allbright and CPU running.
* Screen_dim_wake_lock Keep the screen open (but darken it) and run the CPU.
* Partial_wake_lock keeps the CPU running.
[Java]View PlainCopy
- PowerManager pm = (powermanager) getsystemservice (Context.power_service);
- WakeLock WakeLock = Pm.newwakelock (Powermanager.partial_wake_lock, "Mywakelock");
After you create wake lock, you can get it by calling acquire. You can optionally specify a time-out value to ensure that wake Lock is maintained for as long as possible. When you use Wake Lock for an action and the action completes, you need to call release to let the system manage the power state. The following program shows a typical usage pattern for creating, acquiring, and releasing Wake Lock.
[Java]View PlainCopy
- PowerManager pm = (powermanager) getsystemservice (Context.power_service);
- WakeLock WakeLock = Pm.newwakelock (Powermanager.partial_wake_lock, "Mywakelock");
- Wakelock.acquire ();
- /** do things requiring the CPU stay active */
- Wakelock.release ();
Permissions Required:<uses-permission android:name= "Android.permission.WAKE_LOCK"/>
Android using Wake Lock