定时器不能重复 android 如何解决?

Timer can not be repeated on android How to fix?

我要Timer执行重复。 所以我试试这个来源

public static void init() {
    TimerTask timerTask = new TimerTask() {
       @Override
       public void run() {
           Looper.prepare();
           recordWork();
           Looper.loop();
       }
    };
    Timer timer = new Timer();
    timer.schedule(timerTask, 1000, 30000);
}

init() 单击录制按钮时调用。

为什么recordWork()只有一个execute? 这个timer不执行重复

如何解决这个问题?

谢谢。

使用函数 timer.scheduleAtFixedRate()X 秒执行一次计时器。

例如timer.scheduleAtFixedRate(timerTask, new Date(), 2000)现在启动定时器并每2秒执行一次。

像下面这样使用

  public static void init() {
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            Looper.prepare();
            recordWork();
            Looper.loop();
        }
    };
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(timerTask, 1000, 30000);
}

使用定时器作为全局变量。并取消它它的需要完成。

 if(timer != null) {
    timer.cancel();
    timer.purge();
    timer = null;
}

如果您仍然无法修复您的 Timertask。不妨试试 CountDownTimer https://developer.android.com/reference/android/os/CountDownTimer.html

public void startCountDown() {
    countDownTimer = new CountDownTimer(totalTimeinMillis,intervalBetweenCountdown) {

                @Override
                public void onTick(long millisUntilFinished) {
                    //execute repeating task here
                }

                @Override
                public void onFinish() {

                }
            };
        }

使用处理程序

Handler handler = new Handler();
int delay = 2000; //milliseconds

handler.postDelayed(new Runnable(){
    public void run(){
        recordWork();
        handler.postDelayed(this, delay);
    }
}, delay);