Recently, the app needs to turn on and off the Do Not Disturb mode at regular intervals. This requires real-time monitoring of the system time to complete, so how to achieve it?
As for how to monitor in real time? Let's take a closer look at the operation
first import dependencies
implementation "io.reactivex.rxjava2:rxjava:2.2.6"
implementation "io.reactivex.rxjava2:rxandroid:2.1.0"
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0"
The following is the key code, don't blink
Observable.interval(1, TimeUnit.SECONDS)//时间间隔是 1 秒
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread())
.subscribe(aLong -> {
try {//捕获异常 然后做实际操作(这里是举例获取系统时间并实时更新)
String time = new SimpleDateFormat("HH:mm:ss").format(new Date(System.currentTimeMillis()));
textView.setText(time);
} catch (Exception e) {
e.printStackTrace();
}
});
Finish!
Does it feel like it's over before it even started? That's right, it's that fast. What our code wants is to realize the requirements, concise and to the point