Search code examples
androidandroid-intentandroid-servicewakelockpowermanager

Will wakelock + handler allow the device to stay awake?


I am currently working on an app that starts an activity every 30 minutes using a Handler & WakeLock. But I was wondering as to the reliability of this method. I did check this post, but it doesn't seem to answer my question. Here is the code I'm using to keep my service alive and running:

    @Override
public int onStartCommand(Intent intent, int flags, int startId) {
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MyWakelockTag");
    wakeLock.acquire();
    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Intent sendMessage = new Intent();
            sendMessage.setAction(LAWAY);
            sendMessage.setClass(LAWAYService.this, LReceiver.class);
            sendBroadcast(sendMessage);
        }
    };
    handler.postDelayed(runnable, DURATION);
    return START_STICKY;
}

How reliable is this? I'm using this in conjunction with a WakefulBroadcastReceiver. Till now it is working with the three devices that I've tested with including Samsung Galaxy Note 5, Google Pixel XL and Nexus 6P.

I have found this is draining a great amount of battery. Is there a greener solution?


Solution

  • This method will not work reliable starting with Android 6.0 (API 23) due to Doze mode. When the device is idle and in Doze, wake locks are ignored. Starting with API 26 this gets even more restrictive and background services are not allowed to run freely.

    It's generally a bad idea to wake up often, unless the user is actively using your app and is aware of the operation (hence the new background limits.) Look into using the JobScheduler to deal with routine background tasks (though the will also have limits in Doze mode.)