如何延迟android中的秒数?

时间:2015-12-09 03:12:54

标签: android delay system-clock

我想延迟秒并显示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?

问题出在那里吗?

1 个答案:

答案 0 :(得分:3)

尝试处理程序

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);