Android - loop part of the code every 5 seconds

后端 未结 4 2003
醉酒成梦
醉酒成梦 2020-11-30 06:51

I would like to start repeating two lines of code every 5 seconds when I press the button START and end it, when I press the button STOP. I was trynig with a TimerTask and H

4条回答
  •  温柔的废话
    2020-11-30 07:41

    You can use CountDownTimer as the following method:

    private CountDownTimer timer;
    
    timer = new CountDownTimer(5000, 20) {
    
        @Override
        public void onTick(long millisUntilFinished) {
    
        }
    
        @Override
        public void onFinish() {
            try{
                yourMethod();
            }catch(Exception e){
                Log.e("Error", "Error: " + e.toString());
            }
        }
    }.start();
    

    And then to call the timer again:

    public void yourMethod(){
        //do what you want
        timer.start();
    }
    

    To cancel the timer, you can call timer.cancel();

    Hope it helps!

提交回复
热议问题