James Gu
James Gu

Reputation: 1392

Android onCreate loading delay

My app takes a while to initiate (MainActivity), so I want a separate thread to show a loading indicator for 10 seconds (ignore all other touch events within this 10 seconds) then disappear automatically. How do I do this?

Upvotes: 0

Views: 2774

Answers (2)

Shakti
Shakti

Reputation: 1581

  1. Cover the Main Activity with splash screen(Any edge to edge image will do).
  2. Display a progress bar using Progress Bar
  3. Disable touch Events for the Splash screen so that the touch event doesn't pass towards the main activity screen.
  4. Remove the Splash Screen from view when the loading is done in background or after a specific time.

Benefits:

No handlers/threads required because you stay in the main activity the whole time.

Updating progress bar will be a breeze because you stay in the UI thread the whole time.

Application less likely to crash because touch events are disabled during loading so no burden on UI thread.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

If your main activity takes several seconds to initialize, then the initialization is what should be on a separate thread, not the splash screen. You should never block the UI thread with time-consuming operations.

You can organize your initialization something like this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // set up the splash screen
    setContentView(R.layout.splash_screen);

    // set up and start the initialization thread
    final Handler handler = new Handler();
    new Thread() {
        public void run() {
            // Do time-consuming initialization.
            // When done:
            handler.post(new Runnable() {
                public void run() {
                    // set up the real UI
                }
            });
        }
    }.start();
}

That will remove the splash screen and replace it with the real UI after the time-consuming initialization is finished.

If you always want to wait a minimum of 10 seconds, you can record the start time in a local variable before starting the thread and then after initialization is finished, if there is still time left you can use postDelayed or postAtTime.

The above code uses a Handler and a Thread because what you want to do is fairly straightforward. As an alternative, you could use an AsyncTask, which does essentially the same thing. It also has built-in tools that allow you to "publish" initialization progress to the UI thread. See the docs for details.

Upvotes: 2

Related Questions