SoFunction
Updated on 2025-04-11

Three ways to implement polling on Android

This article shares the method of Android polling for your reference. The specific content is as follows

1. Implemented through rxjava (Lambda expression is used in the code)

private static final int PERIOD = 10 * 1000;
private static final int DELAY = 100;
private Disposable mDisposable;
/**
  * Timed loop task
  */
private void timeLoop() {
  mDisposable = (DELAY, PERIOD, )
      .map((aLong -> aLong + 1))
      .subscribeOn(())
      .observeOn(())
      .subscribe(aLong -> getUnreadCount());//Tasks executed by getUnreadCount()}
//Close the timing taskif (mDisposable != null) ();

2. Implemented through Handler

private Handler mHandler = new Handler(()); // Global variablesprivate Runnable mTimeCounterRunnable = new Runnable() {
  @Override
  public void run() {//Add to add the interface to be searched heregetUnreadCount();//Tasks executed by getUnreadCount()    (this, 20 * 1000);
  }
};
//Close the timing task(mTimeCounterRunnable);

3. Timer and TimerTask implementation using Java

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() {
      //Add a poll here    }
  };
  (mTimerTask,DELAY,PERIOD);
}
//Close the timing taskif (mTimer != null) ();

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.