Sleep() in Android Java

spogebob92 picture spogebob92 · Feb 18, 2013 · Viewed 88.7k times · Source

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 recognize Sleep() as a function and provides me with an error, asking if I would like to create a method called Sleep().

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

Karan_Rana picture Karan_Rana · Feb 18, 2013

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.