I want to make a pause between two lines of code, Let me explain a bit:
-> the user clicks a button (a card in fact) and I show it by changing the background of thi
I use CountDownTime
new CountDownTimer(5000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
// do something after 1s
}
@Override
public void onFinish() {
// do something end times 5s
}
}.start();
Or you could use:
android.os.SystemClock.sleep(checkEvery)
which has the advantage of not requiring a wrapping try ... catch
.
You probably don't want to do it that way. By putting an explicit sleep()
in your button-clicked event handler, you would actually lock up the whole UI for a second. One alternative is to use some sort of single-shot Timer. Create a TimerTask to change the background color back to the default color, and schedule it on the Timer.
Another possibility is to use a Handler. There's a tutorial about somebody who switched from using a Timer to using a Handler.
Incidentally, you can't pause a process. A Java (or Android) process has at least 1 thread, and you can only sleep threads.
If you use Kotlin and coroutines, you can simply do
GlobalScope.launch {
delay(3000) // In ms
//Code after sleep
}
And if you need to update UI
GlobalScope.launch {
delay(3000)
GlobalScope.launch(Dispatchers.Main) {
//Action on UI thread
}
}
I know this is an old thread, but in the Android documentation I found a solution that worked very well for me...
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
https://developer.android.com/reference/android/os/CountDownTimer.html
Hope this helps someone...
I use this:
Thread closeActivity = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
}
});