本文实例为大家分享了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();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持免费资源网。