3

In one of my android applications, I need to run a task for every minute. It should run even if the app closes and when device is in Idle state also.

  1. I have tried handler, it is working fine when device is active, but not working when device is in idle state.
  2. I have tried workmanager(one time and repeated ) as well. Document says this works even when the device is in Idle mode, but this is stops working after 3/4 repeats.Workmanager is inconsitent, its working sometimes and not working most of the cases till i reboot device.

Can anyone suggest better way to handle the situation?

Thanks bhuvana

angrybird
  • 45
  • 1
  • 6

1 Answers1

4

Work manager can only work within 15 minutes of interval, if you do not define a longer time. To run something every minute, you need a Foreground Service with a sticky notification in it. There is no other way to run something every minute.

To start a foreground service, create a service as usual, and in its onStartCommand, call startForeground and from the method, return START_STICKY. These should achieve what you need.

Edit: Sample code for handler thread (this is Java btw, should be similar on Xamarin):

private HandlerThread handlerThread;
private Handler backgroundHandler;

@Override
public int onStartCommand (params){

    // Start the foreground service immediately.
    startForeground((int) System.currentTimeMillis(), getNotification());

    handlerThread = new HandlerThread("MyLocationThread");
    handlerThread.setDaemon(true);
    handlerThread.start();
    handler = new Handler(handlerThread.getLooper())

    // Every other call is up to you. You can update the location, 
    // do whatever you want after this part.

    // Sample code (which should call handler.postDelayed()
    // in the function as well to create the repetitive task.)
    handler.postDelayed(() => myFuncToUpdateLocation(), 60000);

    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    handlerThread.quit();
}
Furkan Yurdakul
  • 2,801
  • 1
  • 15
  • 37
  • What shall I do in foreground service? repeated handler to repeat for every minute? Periodic workrequest works for 15 mintues. But I was trying oneTimeRequest with continous looping. val work = OneTimeWorkRequestBuilder().setConstraints(constraints) .setInitialDelay(interval, TimeUnit.SECONDS).addTag("jobTag") .build() And when it comes to worker, scheduling the same wokre again. – angrybird Nov 26 '19 at 05:54
  • That's up to you. As long as you have a sticky notification, the system will preserve your service as much as possible. You can use a thread, a handler, a thread pool etc. it depends on what you want to achieve. If you want to post a location to the server, I'd say create a **HandlerThread** and attach a looper in it. Editing the code for some info. – Furkan Yurdakul Nov 26 '19 at 05:57