Android implements countdown jump and delay operation

The App startup page counts down for 3 seconds to jump to the App's homepage. This operation is common in many Apps. What if you need to do a delayed operation? Write a sub-thread to stay for 3 seconds and then perform the operation. In this case, special attention needs to be paid to the fact that the UI operation must be placed in the main thread, so does it need to be converted into the main thread? NO, use Handler to easily implement countdown and delay operations.

1. Detailed operation of countdown on startup page

private int duration = 6;
private Handler updateHandler = new Handler() {
    @Override
    public void dispatchMessage(Message msg) {
      super.dispatchMessage(msg);
      if (msg.what == 2) {
        if (duration > 0) {
          duration--;
          appStartBinding.jumpButton.setText(duration + "s跳过");
          if (duration == 1) {
            //用户自己的操作
          }
          updateHandler.sendEmptyMessageDelayed(2, 1000);
        }
      }
    }
  };

//在需要倒计时的地方执行以下代码
updateHandler.sendEmptyMessage(2);

 2. Delay operation

Use Handler to make delayed requests, no need to worry about whether the UI thread is on the main thread

private Handler updateHandler = new Handler() {
    @Override
    public void dispatchMessage(Message msg) {
      super.dispatchMessage(msg);
      if (msg.what == 14) {
        //用户自己的操作
      }
    }
  };

//在需要延时操作的地方执行以下代码
/**
 * 第一参数:what
 * 第二个参数:需要延时的毫秒数
 */
 updateHandler.sendEmptyMessageDelayed(14, 2000);

To implement the countdown and delay operations above, don’t forget to remove them in the Activity’s onDestroy() method.

if (updateHandler != null) {
      updateHandler.removeCallbacksAndMessages(null);
    }

The above are the specific steps and codes for simple and practical countdown jump and delay operations in Android. There are many ways to implement countdown and delay operations. You still need to see whether it can meet your needs.

Guess you like

Origin blog.csdn.net/weitao_666/article/details/100727400