spogebob92 spogebob92 - 2 months ago 22
Java Question

Sleep() in java (Android)

I am following this tutorial to have a loading screen in my program. The tutorial says my activity should Sleep() using the Sleep() command, however it does not recognise Sleep() as a function and provides me with an error, asking if I would like to create a method called Sleep().

Here is a link to the tutorial:

http://androidcookbook.com/Recipe.seam;jsessionid=4DBCC1688B51DB16A2A40A86E135D361?recipeId=1599

Here is the code sample:

public class LoadingScreenActivity extends Activity {

//Introduce an delay
private final int WAIT_TIME = 2500;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
System.out.println("LoadingScreenActivity screen started");
setContentView(R.layout.loading_screen);
findViewById(R.id.mainSpinner1).setVisibility(View.VISIBLE);

new Handler().postDelayed(new Runnable(){
@Override
public void run() {
//Simulating a long running task
this.Sleep(1000);
System.out.println("Going to Profile Data");
/* Create an Intent that will start the ProfileData-Activity. */
Intent mainIntent = new Intent(LoadingScreenActivity.this,ProfileData.class);
LoadingScreenActivity.this.startActivity(mainIntent);
LoadingScreenActivity.this.finish();
}
}, WAIT_TIME);
}
}

Answer

You can use one of the folllowing methods:

Thread.sleep(timeInMills);

or

SystemClock.sleep(timeInMills);

SystemClock.sleep(milliseconds) is a utility function very similar to Thread.sleep(milliseconds), but it ignores InterruptedException. Use this function for delays if you do not use Thread.interrupt(), as it will preserve the interrupted state of the thread.