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
1 |
<uses-permission android:name="android.permission.WAKE_LOCK" /> |
Now set the wake lock
1 2 3 4 |
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag"); wakeLock.acquire(); |
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
1 |
wakelock.release(); |
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
1 2 3 4 5 6 7 |
public class MyReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // anything you want to do on Recieve. } } |
And you can release the lock using
1 |
MyReceiver.completeWakefulIntent(intent); |
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.