Android close dialog after 5 seconds?

后端 未结 8 829
北海茫月
北海茫月 2020-12-05 02:00

I\'m working on an accesibility app. When the user wants to leave the app I show a dialog where he has to confirm he wants to leave, if he doesn\'t confirm after 5 seconds t

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 02:51

    Late, but I thought this might be useful for anyone using RxJava in their application.

    RxJava comes with an operator called .timer() which will create an Observable which will fire onNext() only once after a given duration of time and then call onComplete(). This is very useful and avoids having to create a Handler or Runnable.

    More information on this operator can be found in the ReactiveX Documentation

    // Wait afterDelay milliseconds before triggering call
    Subscription subscription = Observable
            .timer(5000, TimeUnit.MILLISECONDS) // 5000ms = 5s
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1() {
                @Override
                public void call(Long aLong) {
                    // Remove your AlertDialog here
                }
            });
    

    You can cancel behavior triggered by the timer by unsubscribing from the observable on a button click. So if the user manually closes the alert, call subscription.unsubscribe() and it has the effect of canceling the timer.

提交回复
热议问题