onTick(long millisUntilFinished ) - In this method we have to pass countdown mill seconds after done countdown it will stop Ticking. onFinish() - After finish ticking, if you want to call any methods or callbacks we can do in onFinish(). start() - It is used to call countdown timer.
Timer import kotlin. concurrent. schedule fun main(args: Array<String>) { // Execution starting point println("Hello world!!") // Delay of 5 sec Timer(). schedule(5000){ //calling a function newMethod() } } fun newMethod(){ println("Delayed method call!") }
You can use this for Simplest Solution: new Handler(). postDelayed(new Runnable() { @Override public void run() { //Write your code here } }, 5000); //Timer is in ms here.
Try this code:
import android.os.Handler;
...
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do something after 5s = 5000ms
buttons[inew][jnew].setBackgroundColor(Color.BLACK);
}
}, 5000);
You can use CountDownTimer
which is much more efficient than any other solution posted. You can also produce regular notifications on intervals along the way using its onTick(long)
method
Have a look at this example showing a 30seconds countdown
new CountDownTimer(30000, 1000) {
public void onFinish() {
// When timer is finished
// Execute your code here
}
public void onTick(long millisUntilFinished) {
// millisUntilFinished The amount of time until finished.
}
}.start();
If you use delay frequently in your app, use this utility class
import android.os.Handler;
public class Utils {
// Delay mechanism
public interface DelayCallback{
void afterDelay();
}
public static void delay(int secs, final DelayCallback delayCallback){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
delayCallback.afterDelay();
}
}, secs * 1000); // afterDelay will be executed after (secs*1000) milliseconds.
}
}
Usage:
// Call this method directly from java file
int secs = 2; // Delay in seconds
Utils.delay(secs, new Utils.DelayCallback() {
@Override
public void afterDelay() {
// Do something after delay
}
});
Using the Thread.sleep(millis)
method.
If you want to do something in the UI on regular time intervals very good option is to use CountDownTimer:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Handler answer in Kotlin :
1 - Create a top-level function inside a file (for example a file that contains all your top-level functions) :
fun delayFunction(function: ()-> Unit, delay: Long) {
Handler().postDelayed(function, delay)
}
2 - Then call it anywhere you needed it :
delayFunction({ myDelayedFunction() }, 300)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With