Android Timer & Delay Methods

In Android, there are several commonly used timer and delay methods.

  1. Handler延迟执行的方法:使用Handler类的postDelayed()方法来实现延时操作。例如:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // 延时执行的代码
    }
}, delayMillis);
  1. CountDownTimer: Utilize the CountDownTimer class to achieve timed execution. For example:
CountDownTimer countDownTimer = new CountDownTimer(millisInFuture, countDownInterval) {
    @Override
    public void onTick(long millisUntilFinished) {
        // 定时执行的代码
    }

    @Override
    public void onFinish() {
        // 定时完成后执行的代码
    }
};
countDownTimer.start();
  1. Using the Timer class to achieve timed execution. For example:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        // 定时执行的代码
    }
}, delayMillis, periodMillis);
  1. ScheduledThreadPoolExecutor timer: utilizes the ScheduledThreadPoolExecutor class for scheduled execution. For example:
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.schedule(new Runnable() {
    @Override
    public void run() {
        // 定时执行的代码
    }
}, delayMillis, TimeUnit.MILLISECONDS);

The above are several commonly used timers and delay methods in Android, developers can choose the appropriate method based on their own needs to achieve timing and delay operations.

bannerAds