本文主要是介绍android 多种形式定时轮训工具类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/*** 定时器轮训工具类*/
public class RxTimeUtils {private static Disposable mDisposable;/*** 轮训一次* milliseconds 毫秒* next回调方法*/public static void timer(long milliseconds, final IRxNext next) {Observable.timer(milliseconds, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {@Overridepublic void onSubscribe(Disposable d) {mDisposable = d;}@Overridepublic void onNext(Long aLong) {if (next != null) {next.doNext(aLong);}}@Overridepublic void onError(Throwable e) {cancel();}@Overridepublic void onComplete() {}});}/*** 一直执行轮训* milliseconds 毫秒* next回调方法*/public static void interval(long milliseconds, IRxNext next) {Observable.interval(milliseconds, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {@Overridepublic void onSubscribe(Disposable d) {mDisposable = d;}@Overridepublic void onNext(Long aLong) {if (next != null) {next.doNext(aLong);}}@Overridepublic void onError(Throwable e) {}@Overridepublic void onComplete() {}});}/*** 启动定时器* milliseconds//总时间*/public static void startTime(long milliseconds, IRxNext next) {Observable.interval(0, 1, TimeUnit.MILLISECONDS).take(milliseconds + 10)//设置总共发送的次数.map(new Function<Long, Long>() {@Overridepublic Long apply(Long aLong) throws Exception {//aLong从0开始return milliseconds - aLong;}}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {@Overridepublic void onSubscribe(Disposable d) {mDisposable = d;}@Overridepublic void onNext(Long value) {if (next != null) {next.doNext(value);}//Log.d("Timer",""+value);}@Overridepublic void onError(Throwable e) {cancel();}@Overridepublic void onComplete() {cancel();}});}public static CountDownTimer timer;/*** 第一个参数表示总时间,第二个参数表示间隔时间。* 意思就是每隔一秒会回调一次方法onTick,然后1秒之后会回调onFinish方法。*/public static void DownstartTime(int Totaltime, int IntervalTime, IRxTick next) {timer = new CountDownTimer(Totaltime, IntervalTime) {@Overridepublic void onTick(long aLong) {if (next != null) {next.doTick(aLong);}}@Overridepublic void onFinish() {if (next != null) {next.doFinish();}}};//启动倒计时timer.start();}/*关闭定时器*/public static void canceltiem() {if (timer != null) {timer.cancel();}}/*关闭rxjava*/public static void cancel() {if (mDisposable != null && !mDisposable.isDisposed()) {mDisposable.dispose();}}public interface IRxTick {void doTick(long number);void doFinish();}public interface IRxNext {void doNext(long number);}
}用法/*totaltime=60000总计时一分钟,intervaltime=1000间隔1秒执行一次dotick方法*/
RxTimeUtils.DownstartTime(60000, 1000, new RxTimeUtils.IRxTick() {@Overridepublic void doTick(long number) {//具体业务,如:走一个接口成功了直接RxTimeUtils.canceltiem();关掉定时器,只判断成功就可以,失败了接着轮训。Log.e("sssssssss", "开始轮训业务......" + number);}@Overridepublic void doFinish() {handler.post(new Runnable() {@Overridepublic void run() {Log.e("sssssssss", "轮训结束......");RxTimeUtils.canceltiem();}});}
});
这篇关于android 多种形式定时轮训工具类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!