Android - loop part of the code every 5 seconds

后端 未结 4 2004
醉酒成梦
醉酒成梦 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:51

    Using a CountDownTimer as in one of the other answers is one way to do it. Another would be to use a Handler and the postDelayed method:

    private boolean started = false;
    private Handler handler = new Handler();
    
    private Runnable runnable = new Runnable() {        
        @Override
        public void run() {
            final Random random = new Random();
            int i = random.nextInt(2 - 0 + 1) + 0;
            random_note.setImageResource(image[i]);
            if(started) {
                start();
            }
        }
    };
    
    public void stop() {
        started = false;
        handler.removeCallbacks(runnable);
    }
    
    public void start() {
        started = true;
        handler.postDelayed(runnable, 2000);        
    }
    

    Here's an example using a Timer and a TimerTask:

    private Timer timer;
    private TimerTask timerTask = new TimerTask() {
    
        @Override
        public void run() {
            final Random random = new Random();
            int i = random.nextInt(2 - 0 + 1) + 0;
            random_note.setImageResource(image[i]);
        }
    };
    
    public void start() {
        if(timer != null) {
            return;
        }
        timer = new Timer();
        timer.scheduleAtFixedRate(timerTask, 0, 2000);
    }
    
    public void stop() {
        timer.cancel();
        timer = null;
    }
    

提交回复
热议问题