-3

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?

Community
  • 1
  • 1
Ban Lin
  • 95
  • 2
  • 10
  • Did you try ```Thread.sleep(5000)``` ? – Alberto Anderick Jr Dec 09 '15 at 03:29
  • The second parameter is not to define the time interval. But is to define the message to be shown using Toast. – Nabin Dec 09 '15 at 03:30
  • 2
    It's a better idea to use `handler` and `postDelayed` than `Thread.sleep`. – David Fang Dec 09 '15 at 03:31
  • Yes, I have tried this way, but the result is the same. – Ban Lin Dec 09 '15 at 03:31
  • `handler`and`postDelayed`seem first delay and the run? – Ban Lin Dec 09 '15 at 03:34
  • 1
    Doesn't matter what's displayed as you are FREEZING THE UI THREAD. Absolutely, completely, not at all what you want to do... ever. Most likely, the user will get the "app not responding" message. Regardless, the reason it only *seems* to show the caption is because you set the first one and then STOP THE APP... so it can't update the screen until those silly delays are over. – 323go Dec 09 '15 at 03:38

1 Answers1

5

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);
Illegal Argument
  • 10,090
  • 2
  • 44
  • 61