0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • And please, I don't want any `TimerTask` business - it's not really efficient on Android. And I **do know that handlers are used for short tasks, but what else can be the option in this case**? –  Dec 21 '17 at 05:56
  • why do you have a service, and why do you need a wakelock – Tim Dec 21 '17 at 11:46
  • To start activities periodically? @TimCastelijns –  Dec 21 '17 at 11:49
  • maybe if you ask a clear question. You don't need a wakelock to start an activity and I also don't get why you have a service for periodical tasks – Tim Dec 21 '17 at 11:52
  • use jobscheduler – Tim Dec 21 '17 at 12:20

2 Answers2

0

Yes it will. If you want to use wakefulBroadcast, you must use Service via startWakefulService() and after finishing your job you must release wakelock. https://developer.android.com/training/scheduling/wakelock.html But the most effective way is using JobScheduler with JobServices for starting your activity.

no_fate
  • 1,625
  • 14
  • 22
0

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.)

Larry Schiefer
  • 15,687
  • 2
  • 27
  • 33