How to delay seconds in android?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-13 11:18:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!