Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bad practice use Thread.sleep(Milliseconds) for wait a bit before start another activity?

I'm making a SplashScreen for an app ... When the app starts, it start LoadingActivity ... sleep for 3 seconds, finish(); and then starts the MainActivity. Splash serves to update the database. If the database is already updated, I want the splash still for 3 seconds anyway.

I am using the following code:

protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        Intent intent = new Intent(LoadingActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}

Is it a bad pratice? and why? The app is running nicelly in AVD.

like image 553
Filipe Tagliacozzi Avatar asked Dec 05 '25 03:12

Filipe Tagliacozzi


2 Answers

Sleeping on the UI thread is always a bad idea. In this case you are in an onPostExecute, which is on the UI thread.

Throw your sleep into the doInBackground method of your AsyncTask instead, and you won't get any ANR's there (Android not responding).

Users don't like waiting for splash screens, so it is better not to wait at all. But sometimes the splash screen is required (ie due to contracts).

like image 126
Grimmace Avatar answered Dec 06 '25 15:12

Grimmace


Yes it is bad practice, onPostExecute() is called on UI thread so basically you are blocking your UI thread for 3 whole seconds. I suspect you want to show a splash screen. You can instead do it like this.

new Handler().postDelayed(new Runnable(){
    @Override
    public void run(){
        Intent intent = new Intent(LoadingActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
     }
},3000);

or if you want to stick with AsyncTask then override doInBackground() and sleep in it and launch your Activity in onPostExecute() normally.

like image 30
M-WaJeEh Avatar answered Dec 06 '25 15:12

M-WaJeEh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!