Search code examples
javaandroidtimerdelaystopwatch

Call method after delay


I've crated Log in screen, and if user mistake 3 times i want to show timer of 2 min. I want that timer to be visually shown on the screen. I'll try this code and it's work, but I don't know how to display timer on screen.

 Handler handler = new Handler();
 long waitingTime = 2 * 60 * 1000; // 2 min

 handler.postDelayed(new Runnable() {
 @Override
 public void run()
 {
     //Do something after 2 min         
 }
 }, waitingTime);

Solution

  • You need to have Handler called every second and update the UI during every pass. When you reach 2 mins you can cancel the handler.

    Code should be like this:

    final Handler handler = new Handler();
    //class variable
    count = 0;
    
    handler.post(new Runnable() {
        @Override
        public void run() {
            updateCounter(count++);
    
            if(count < 120) {
                handler.postDelayed(this, 1000);
            }
        }
    });
    

    And function to update counter:

    private void updateCounter(final int count) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // you have the seconds passed
                // do what ever you want
            }
        });
    }