问题
I want to delay seconds and show Toast,I try to SystemClock.sleep
But it only show last message("10s")...
Toast.makeText(MainActivity.this,"1s", Toast.LENGTH_SHORT).show();
SystemClock.sleep(5000);
Toast.makeText(MainActivity.this,"5s", Toast.LENGTH_SHORT).show();
SystemClock.sleep(5000);
Toast.makeText(MainActivity.this,"10s", Toast.LENGTH_SHORT).show();
That should be displayed in sequence 1s, 5s, 10s is not it?
I also made reference to this practice, but it can not be achieved... How to set delay in android?
So does the problem lie?
回答1:
Try Handler
public void showToast(final String message, int timeInMilliSeconds, final Context context) {
Runnable runnable = new Runnable() {
@Override
public void run() {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
};
Handler handler = new Handler();
handler.postDelayed(runnable, timeInMilliSeconds);
}
Usage:
showToast("1s, 1000, this);
showToast("5s, 5000, this);
showToast("10s, 10000, this);
来源:https://stackoverflow.com/questions/34170130/how-to-delay-seconds-in-android