Three Ways of Polling in Android
- 2021-12-04 19:45:46
- OfStack
In this paper, we share the way of Android polling for your reference. The specific contents are as follows
1. Implementation via rxjava (Lambda expression used in code)
private static final int PERIOD = 10 * 1000;
private static final int DELAY = 100;
private Disposable mDisposable;
/**
* Timing cycle task
*/
private void timeLoop() {
mDisposable = Observable.interval(DELAY, PERIOD, TimeUnit.MILLISECONDS)
.map((aLong -> aLong + 1))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(aLong -> getUnreadCount());//getUnreadCount() Tasks performed
}
// Turn off timed tasks
if (mDisposable != null) mDisposable.dispose();
2. Implementation via Handler
private Handler mHandler = new Handler(Looper.getMainLooper()); // Global variable
private Runnable mTimeCounterRunnable = new Runnable() {
@Override
public void run() {// Add the interface to be rotated here
getUnreadCount();//getUnreadCount() Tasks performed
mHandler.postDelayed(this, 20 * 1000);
}
};
// Turn off timed tasks
mHandler.removeCallbacks(mTimeCounterRunnable);
3. Timer and TimerTask implementations 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 polling here
}
};
mTimer.schedule(mTimerTask,DELAY,PERIOD);
}
// Turn off timed tasks
if (mTimer != null) mTimer.cancel();