Start a Project

Using WAKE_LOCK to keep device awake.

The android devices falls asleep after the inactivity for a certain amount of time by the user. Its done to save the power of the device. When device go to sleep its CPU also stops working. But sometimes there is a important background task going on in the app so in that case the app must keep the device awake.

It can be done by using WAKE_LOCK permission. Wake lock is a PowerManager system service feature that allow your application to control power state of the device.

Firstly add the permission in your manifest file

Now set the wake lock

Its always recommended to lose control of wake lock as soon as your task is done because it have negative impact on battery. So to loose the control just release the wake lock like

If you want to use wake lock on a broadcast reciever as in case of notifications, the you can use WakefulBroadcastReciever and implement your reciever

And you can release the lock using

But remember to use these when you have no alternative and the background task is a high priority task because as I mentioned it had bad impact on battery and thats why its usage should be minimized.

Exit mobile version