Is it possible to display something before the main activity finishes onCreate() in Android?

StackOverflow https://stackoverflow.com/questions/23479009

문제

Given a one-activity app like this:

public class MyActivity extends Activity {
  protected void onCreate(Bundle savedInstanceState) {

  loadingScreen = new RelativeLayout(this);
  // add a bitmap to loadingScreen
  setContentView(loadingScreen);

  Dict dict = new Dict();
  dict.init(); 
  // this method takes ~10 seconds 
  }
}

In theory, it looks like this would display a loading screen while the dictionary initializes. In practice, nothing is displayed until onCreate() returns, so the user sees a blank white screen for 10 seconds. What's the best way to display a please wait while this app loads screen?

I believe I could create a separate thread for dict.init(), but that seems like overkill in this case because I don't want the app to be usable or interactive while dict.init() runs. I'd like it to run on the main thread (and hang the rest of the app while it executes), I just want to display something on the screen first.

PS, I tried moving dict.init() to onStart(), that appeared to have no effect.

edit: Perhaps I should have clarified this to avoid getting "You're doing it wrong" type answers, but the init takes 2 or 3 seconds on modern phones and tables, 10 seconds is a worst-case on old phones. This app is a word game, it can't be used without the dictionary. Moving dict.init() to an async task will not improve the user's experience, and the question I asked is whether it's possible to display a splash screen without doing that. I gather that the answer is "No."

도움이 되었습니까?

해결책

I'd like it to run on the main thread (and hang the rest of the app while it executes)

No, no wouldn't and your users wouldn't like you much either

I believe I could create a separate thread for dict.init(), but that seems like overkill in this case because I don't want the app to be usable or interactive while dict.init() runs.

This is exactly what you should do. You can use a variety of ways including an AsyncTask and show a ProgressDialog while the work is being done.

so the user sees a blank white screen for 10 seconds.

If it is taking this long then you might want to rethink your flow. Even if you go with a separate Thread and show a ProgressBar, most users aren't going to want to stare at that for 10 seconds. You should load the data in the background and allow them to do something else while it loads, if possible. You could use something like an IntentService depending on how you are getting the data.

Example of AsyncTask

Painless Threading

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top