0

I'm trying to delay the execution of a Runnable for a long delay (about a couple of hours).

Since the value I have to change affects only the UI, it is not necessary for the runnable to execute when the app gets killed. Using the AlarmManager or a Job will be inefficient because they will reopen the app if it is closed.

The perfect candidate for my use case would be a Handler, but unfortunately the Runnable doesn't get executed with such long delays.

I've also tried with Timer, ScheduledThreadPoolExecutor and other solutions which use Threads, with no luck.

Have you an idea on how can I achieve what I need?

Spotlight
  • 1,279
  • 1
  • 13
  • 28

2 Answers2

2

You should definitely look as AlarmManager or Executors. I like to use:

Executors.newSingleThreadScheduledExecutor()
.schedule(runnable, amount.toLong(), timeUnit)

Or use the JobScheduler:

JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
// You can then cancel the job in onStop():
scheduler.cancelAll(); // or a specific job

There you just check if your view is still alive.


And there is also the new WorkManager but I haven't played enough with it to recommend it: https://developer.android.com/reference/androidx/work/WorkManager

shkschneider
  • 17,833
  • 13
  • 59
  • 112
  • Executors uses Threads, so it has the same problems as Timer or ScheduledThreadPoolExecutor. JobScheduler and WorkManager open the app when is closed, and I don't want that behavior – Spotlight Aug 22 '18 at 16:59
  • "check if your view is still alive" like in https://stackoverflow.com/a/5446680/603270 – shkschneider Aug 23 '18 at 08:43
0

i did that once.. you can save the time in shared preference and when you open the app check every time if the time now is greater than the time you saved in 3 hours then execute your function..

hope it helps!!

R.F
  • 312
  • 1
  • 16
  • I need the Runnable to be executed only when the app is open. When the app closes I'm OK with the runnable never being executed – Spotlight Aug 22 '18 at 17:00