2

I'm working on an app where I have to read data from multiple sensors and send it to a remote server every 15 minutes. This has to be done when the app is closed/killed as well and I also have to be sure it always executes. I also want to be sure it happens (almost) exactly every 15 minutes (+-1 minute difference is the upper limit).

At this point, I've found 3 options: using Workmanager, Alarmmanager or using a foreground service. Following the documentation, Workmanager seems the way to go for background tasks, however, after having done some reading, Alarmmanager seems to be a safer choice (Workmanager sometimes has troubles with doze mode, and the timing isn't exact because it uses a flex period of at least 5 minutes). And a foreground service is not really allowed for this kind of task (it's not really long running, it's just a periodic task) and is being limited in newer Android versions. Do you think it would be a good idea to use an Alarmmanger for this task, or should I use something else? Thanks!

lamelizard
  • 21
  • 1
  • 3

1 Answers1

3

TODO Background scheduling.. You can use this method todo your stuff..

KOTLIN;

val service = Executors.newSingleThreadScheduledExecutor()
        val handler = Handler(Looper.getMainLooper())
        service.scheduleAtFixedRate({
            handler.run {
                // Do your stuff here, It gets loop every 15 Minutes
            }
        }, 0, 15, TimeUnit.MINUTES);

JAVA;

  ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        Handler handler = new Handler(Looper.getMainLooper());

        service.scheduleAtFixedRate(() -> {
            handler.post(() -> {
                // Do your stuff here, It gets loop every 15 Minutes
            });
        }, 0, 15, TimeUnit.MINUTES);
Anubis94
  • 149
  • 2
  • 7
  • Is this method still run every 15 minutes although the app / activity is closed / killed ? – Plugie Jan 23 '23 at 02:27
  • @Plugie YEP! It's not a foreground or background service. it's just a simple code snippet to schedule some jobs. If you want to run scheduled foreground/background service you can use Work Manager Api! - Thanks. – Anubis94 Jan 23 '23 at 19:54