时间:2021-09-17 09:39:36 | 栏目:Android代码 | 点击:次
本文实例为大家分享了Android实现轮询的方式,供大家参考,具体内容如下
1.通过rxjava实现(代码中使用了Lambda表达式)
private static final int PERIOD = 10 * 1000; private static final int DELAY = 100; private Disposable mDisposable; /** * 定时循环任务 */ private void timeLoop() { mDisposable = Observable.interval(DELAY, PERIOD, TimeUnit.MILLISECONDS) .map((aLong -> aLong + 1)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(aLong -> getUnreadCount());//getUnreadCount()执行的任务 } //关闭定时任务 if (mDisposable != null) mDisposable.dispose();
2.通过Handler实现
private Handler mHandler = new Handler(Looper.getMainLooper()); // 全局变量 private Runnable mTimeCounterRunnable = new Runnable() { @Override public void run() {//在此添加需轮寻的接口 getUnreadCount();//getUnreadCount()执行的任务 mHandler.postDelayed(this, 20 * 1000); } }; //关闭定时任务 mHandler.removeCallbacks(mTimeCounterRunnable);
3.使用Java的Timer和TimerTask实现
private static final int PERIOD = 10 * 1000; private static final int DELAY = 100; private Timer mTimer; private TimerTask mTimerTask; private void timeLoop2(){ mTimer = new Timer(); mTimerTask = new TimerTask() { @Override public void run() { //在此添加轮询 } }; mTimer.schedule(mTimerTask,DELAY,PERIOD); } //关闭定时任务 if (mTimer != null) mTimer.cancel();