我想在我的代码中加上 60秒的延迟。我用了下面的代码,加了一些延迟;但它的行为并不像预期的那样。
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//Calling my function after 15 seconds delay.
}
}, 15000);
P.S。 :我不想使用 Thread.sleep(),因为它会在正常的应用程序操作中造成障碍。
答案 0 :(得分:1)
您可以尝试使用CountDownTimer。
// You can change millisInFuture and countDownInterval according to your need.
long millisInFuture = 60000;
long countDownInterval = 1000;
new CountDownTimer(millisInFuture, countDownInterval) {
@Override
public void onTick(long l) {
// Method call according to countDownInterval.
// For E.g we are taking 1000 so this method call every 1 second.
}
@Override
public void onFinish() {
// When 60 second completed call this method.
// Do your logic here.
}
}.start();
您想要做的事情就像这样。
long millisInFuture = 60000;
long countDownInterval = 1000;
int counter = 0;
new CountDownTimer(millisInFuture, countDownInterval) {
@Override
public void onTick(long l) {
// Method call according to countDownInterval.
// For E.g we are taking 1000 so this method call every 1 second.
}
@Override
public void onFinish() {
// When 60 second completed call this method.
// Do your logic here.
counter++;
if (counter == 1) {
// Call your 1st function
} else if (counter == 2) {
// Call your 2nd function
} else if (counter == 3) {
// Call your 3rd function
} else if (counter == 4) {
// Call your 4th function
} else if (counter == 5) {
// Call your 5th function
}
if (counter < 5) {
start();
}
}
}.start();