0

I am currently writing a game and would like the app to wait a certain amount of time before proceeding. I have tried the sleep function and it does not do what I would like it to. I have a loop for ten and in that I would like one of the text boxes to have its value changed ten times with a couple of seconds gap between each one. So far I have this

for(int coolRan = 0; coolRan < 11; coolRan = coolRan + 1) {          
    Random generator = new Random();
    int RanNumGen = generator.nextInt(50) + 1;                          
    String RanNum = Integer.toString(RanNumGen);                
    higherTxt.setText(RanNum);
}

What I would like it to do after this is pause for a few seconds before performing the operation in the loop again so in Pseudocode this is what it looks like:

Loop For Ten

Generate Random Number With Maximum Value Of 50

Set A String To Equal The Random Number

Set A TextView To Equal The Random Number

Wait A Few Seconds

Perform Operation Again

nook
  • 2,378
  • 5
  • 34
  • 54
Alex
  • 531
  • 1
  • 8
  • 22

2 Answers2

1

The sleep method should work correctly if used in the following way.

Thread.sleep();

The parameter is the time in milliseconds.

For example:

Thread.sleep(5000);
//This pauses or "sleeps" for 5 seconds
Mike M
  • 752
  • 1
  • 5
  • 13
  • I am just a beginner to Java and so have put the code I mentioned in the original post in the onCreate section as I am unsure how to create and call my own public class. I have tried the code you mentioned and all it leaves me with is a blank screen whilst it performs the operation. – Alex Jun 18 '13 at 22:29
  • `Thread.sleep()` is likely undesirable in a GUI application, there are generally better ways to delay behavior without locking a thread. – dimo414 Jun 18 '13 at 22:35
  • This cannot be used in Android GUI, will not even run - but if would, would be bad practice. – Audrius Meškauskas Jun 19 '13 at 17:39
1

Thread.sleep(long millis) makes the currently executing Thread sleep for long milliseconds (1/1000 seconds).

In Android, sleeping in the UI-thread is very, very bad practice and can for instance lead to a "Application Not Responsive" (ANR) error. To bypass this, you should run it off another thread. There are several ways to do this:

  1. Calling View.postDelayed(Runnable action, long delayMillis) - this will delay it for you so you do not need to call sleep().
  2. Making the task implement AsyncTask
  3. Creating a new Thread (or Runnable) Java-style and then publishing it to the UI-thread with another Runnable (yeah.. not recommended) with Activity.runOnUiThread(Runnable)

Also note that your for-loop will run 11 times, from 0 up to 10 (both inclusive) - not 10 times.

ddmps
  • 4,350
  • 1
  • 19
  • 34