KaHeL
KaHeL

Reputation: 4371

Add a runnable thread inside an Async Task for splash screen delay

Hi I wanted to add a delay on my splash screen using a Async Task but I can't figure out how should I do it. Here's my DoInBackground code so far:

@Override
        protected Integer doInBackground(String... params) {

            Thread SplashThread = new Thread() {
                    @Override
                    public void run() {
                        try {
                            int waited = 0;
                            while(running && (waited < delayTime)) {
                                sleep(100);
                                if(running) {
                                    waited += 100;
                                }
                            }
                        } catch(InterruptedException e) {
                            // do nothing
                        } finally {
                            finish();
                            stop();
                        }
                    }
                };
                SplashThread.start();

            return null;
        }

I think the part of the return null is the main cause of problem since it's ending up my Async Task even my SplashThread is still running in background leaving a leak on thins part onwards which lead to error. I also tried to use counDownTimer as a subtitute but this leads in the same problem. Any ways to do this properly?

Upvotes: 0

Views: 1145

Answers (1)

user
user

Reputation: 87064

You don't need the additional thread that you start in the doInBackground method of your AsyncTask. The AsyncTask itself runs the doInBackground method in another thread, also, because of this the while loop it's most likely unnecessary. Do the work you want to do in the doInBackground method and then simply return. If you want/need some additional delay(although you should avoid this at all costs) you can use the Thread.sleep method to pause the thread before returning.

Upvotes: 2

Related Questions