I am trying to run a countdown timer in a fragment. I have been able to achieve this but I can't seem to run it in background. How would I do this? Using a service requires onStart and onStop but these methods don't apply to fragments. What do I do?
Asked
Active
Viewed 515 times
0
-
look at this answer there should be few examples: https://stackoverflow.com/a/10032406/8187578 – Kebab Krabby Aug 16 '18 at 11:09
-
What I need is not there – Android Programming Tutorials Aug 16 '18 at 11:14
-
The timer should run in the background even if the app is closed or destroyed – Android Programming Tutorials Aug 16 '18 at 11:15
1 Answers
0
In you need the countdown only when UI is visible you could use RxJava for example.
Disposable timer = Observable.interval(1, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.computation())
.subscribe(aLong -> {
// tick;
});
Don't forget to dispose
when timer is not use anymore
if (timer.isDisposed()) timer.dispose();
Or you can use Observable.intervalRange(...)
to fire event specific number of times.
Or check this topic Run loop every second java to understand the Thread
implementation in details.

dilix
- 3,761
- 3
- 31
- 55