Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

How to delay seconds in android?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...