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?
-
you need to apply splash screen and it the background load what you need for your app after loading open your main activity – mohammed momn Jan 24 '14 at 04:18
-
http://stackoverflow.com/questions/16750059/why-my-splash-screen-dont-show-the-images/16750316#16750316. Not sure what you mean by loading indicator – Raghunandan Jan 24 '14 at 04:32
2 Answers
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.

- 232,168
- 48
- 399
- 521
- Cover the Main Activity with splash screen(Any edge to edge image will do).
- Display a progress bar using Progress Bar
- Disable touch Events for the Splash screen so that the touch event doesn't pass towards the main activity screen.
- 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.