SoFunction
Updated on 2025-04-04

Two ways to implement countdown in Android Handler

background:

In recent projects, the login/register function block is just in time. It needs to complete login/registration by sending a verification code and using the verification code within the specified time. I also had this function in previous projects, but I felt it was too complicated, so I had to implement it again by myself. Use Handler to do it, and I think the code is brief and the logic is clear.

Code 1:

//In the callback function that successfully obtains the verification code to the server, start sending a message:();
(MSG_CODE);

//Message processing: private static final int MSG_CODE = 0;
 private int limitTime = 121;
 private Handler mHandler = new Handler(new () {
    @Override
    public boolean handleMessage(Message msg) {
      if(==MSG_CODE){
        limitTime--;
        if(limitTime>0){
          (MSG_CODE,1000);
          ("Countdown:"+limitTime+"s");

        }else{
          ("Get verification code");
        }
        return true;
      }
      return false;
    }
  });

Code 2:

//In the callback function that successfully obtains the verification code to the server, start sending a message:(myRunnale);

//Message processing: private int time = 11;

  private Handler mHandler = new Handler();
  private Runnable myRunnale = new Runnable() {
    @Override
    public void run() {
      time--;
      if(time>0){
        (myRunnale,1000);
        ("Remaining"+time+"s");
      }else{
        ("complete");
      }
    }
  };

From the above code, we can see that using (Runnable) is a convenient way to publish Messgae.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.