经常会遇到各种倒计时场景比如获取短信,需要进行倒计时,因此使用RxJava封装了一个计时器。
使用很简单
TimerUtils.startTimer(15, new TimerUtils.TimerListener() {
@Override
public void onLoading(int next) {
Log.d(TAG, "onLoading: next ======[" + next + "]");
}
@Override
public void onComplete() {
Log.d(TAG, "onComplete: 计时结束");
}
});
工具完整代码如下
依赖于RxJava框架所以最后需要在module的gradle加入依赖
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableObserver;
public class TimerUtils {
private static int temp;
//计时器
public static Disposable startTimer(int Countdown, @NotNull TimerListener timerListener) {
temp = Countdown;
return Observable.interval(1, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread()).takeWhile(aLong -> {
if (temp == 0 || temp == -1) {
return false;
} else {
return true;
}
})
.subscribeWith(new DisposableObserver<Long>() {
@Override
public void onNext(Long o) {
temp--;
if (temp == 0) {
timerListener.onComplete();
} else if (temp == -1) {
//不做任何事情
} else {
timerListener.onLoading(temp);
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
/*
*停止计时器,不做任何动作
*/
public static void stopTimer() {
temp = -1;
}
/**
* 停止计时器,并回调onComplete
*/
public static void completed() {
temp = 0;
}
public interface TimerListener {
void onLoading(int next);
void onComplete();
}
}
本文介绍了一款基于RxJava框架封装的倒计时工具,适用于短信获取等场景。工具提供简单易用的API,支持计时开始、停止及完成回调。代码中详细展示了如何在Android项目中引入依赖并使用该工具。
848

被折叠的 条评论
为什么被折叠?



