0

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?

1 Answers1

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