欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android實(shí)現(xiàn)輪詢的三種方式

 更新時(shí)間:2020年06月19日 10:51:55   作者:snow_lyGirl  
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)輪詢的三種方式,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了Android實(shí)現(xiàn)輪詢的方式,供大家參考,具體內(nèi)容如下

1.通過rxjava實(shí)現(xiàn)(代碼中使用了Lambda表達(dá)式)

private static final int PERIOD = 10 * 1000;
private static final int DELAY = 100;
private Disposable mDisposable;
/**
 * 定時(shí)循環(huán)任務(wù)
 */
private void timeLoop() {
  mDisposable = Observable.interval(DELAY, PERIOD, TimeUnit.MILLISECONDS)
      .map((aLong -> aLong + 1))
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(aLong -> getUnreadCount());//getUnreadCount()執(zhí)行的任務(wù)
}
//關(guān)閉定時(shí)任務(wù)
if (mDisposable != null) mDisposable.dispose();

2.通過Handler實(shí)現(xiàn)

private Handler mHandler = new Handler(Looper.getMainLooper()); // 全局變量
private Runnable mTimeCounterRunnable = new Runnable() {
  @Override
  public void run() {//在此添加需輪尋的接口
getUnreadCount();//getUnreadCount()執(zhí)行的任務(wù)
    mHandler.postDelayed(this, 20 * 1000);
  }
};
//關(guān)閉定時(shí)任務(wù)
mHandler.removeCallbacks(mTimeCounterRunnable);

3.使用Java的Timer和TimerTask實(shí)現(xiàn)

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);
}
//關(guān)閉定時(shí)任務(wù)
if (mTimer != null) mTimer.cancel();

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論