如何在 android 中延迟秒数?
How to delay seconds in android?
我想延时显示Toast,我尝试SystemClock.sleep
但它只显示最后一条消息(“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();
那应该是按1s,5s,10s顺序显示的吧?
我也参考了这个做法,但是实现不了...
How to set delay in android?
那么问题出在哪里?
尝试处理程序
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);
}
用法:
showToast("1s, 1000, this);
showToast("5s, 5000, this);
showToast("10s, 10000, this);
我想延时显示Toast,我尝试SystemClock.sleep
但它只显示最后一条消息(“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();
那应该是按1s,5s,10s顺序显示的吧?
我也参考了这个做法,但是实现不了... How to set delay in android?
那么问题出在哪里?
尝试处理程序
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);
}
用法:
showToast("1s, 1000, this);
showToast("5s, 5000, this);
showToast("10s, 10000, this);