What should I do to give a periodic delay?

Asked 2 years ago, Updated 2 years ago, 49 views

There's a variable called status. You want to view the value of this variable and display specific text. I'd like to give you a slight delay.

What I'm saying is

In this way, the delay time can be changed, and I want to set the displayed text once I've tried Thread.sleep (time delay), but it doesn't work. Is there a good way?

android

2022-09-22 21:28

1 Answers

You can use Handler's postDelayed method. This is a code that gives a specified delay to a specific code in the main UI thread. Maybe you can solve the problem you want.

Please refer to the code below and correct it accordingly.

private int mInterval = 5000; // 5 seconds is the default, so you can change it. 
private Handler mHandler;

@Override
protected void onCreate(Bundle bundle) {

    // // your code here

    mHandler = new Handler();
    startRepeatingTask();
}

Runnable mStatusChecker = new Runnable() {
    @Override 
    public void run() {
          try {
               UpdateStatus(); //You can change the value of mInterval in this function. 
          } } finally {
               // Code that is invoked unconditionally. 
               // If an exception is found in updateStatus, the code below is executed. 
               mHandler.postDelayed(mStatusChecker, mInterval);
          }
    }
};

void startRepeatingTask() {
    mStatusChecker.run(); 
}

void stopRepeatingTask() {
    mHandler.removeCallbacks(mStatusChecker);
}


2022-09-22 21:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.