How to set timer in android?

后端 未结 21 909
渐次进展
渐次进展 2020-11-22 00:51

Can someone give a simple example of updating a textfield every second or so?

I want to make a flying ball and need to calculate/update the ball coordinates every se

21条回答
  •  一向
    一向 (楼主)
    2020-11-22 01:28

    I'm surprised that there is no answer that would mention solution with RxJava2. It is really simple and provides an easy way to setup timer in Android.

    First you need to setup Gradle dependency, if you didn't do so already:

    implementation "io.reactivex.rxjava2:rxjava:2.x.y"
    

    (replace x and y with current version number)

    Since we have just a simple, NON-REPEATING TASK, we can use Completable object:

    Completable.timer(2, TimeUnit.SECONDS, Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(() -> {
                // Timer finished, do something...
            });
    

    For REPEATING TASK, you can use Observable in a similar way:

    Observable.interval(2, TimeUnit.SECONDS, Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(tick -> {
                // called every 2 seconds, do something...
            }, throwable -> {
                // handle error
            });
    

    Schedulers.computation() ensures that our timer is running on background thread and .observeOn(AndroidSchedulers.mainThread()) means code we run after timer finishes will be done on main thread.

    To avoid unwanted memory leaks, you should ensure to unsubscribe when Activity/Fragment is destroyed.

提交回复
热议问题