开发者

Android AsyncTask and

Hi i have an AsyncTask in my application called in OnCreate() that retrieve some data over the web and display an indeterminate progress bar while downloading.

The problem is when i start the app the screen remain blank until the AsyncTask is finished. The code is something like that.

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    loadData();
    //Several UI Code   
    startAsyncTasks();
}


 private void startAsyncTasks(){
    new Connect开发者_运维问答ingTask().execute();
 }


OnCreate() is executed before the Activity is being shown on the screen, so the whole data download process executes before showing the activity.

Solution could be to start AsyncTask in OnStart() method instead of in OnCreate() (also overriden). OnStart() is executed while activity is going to be shown on the screen (see activity lifecycle).

This is the case I have implemented in my app and it works. You should show a progress dialog in OnStart() method, and update and dismiss it in AsyncTask in proper moments.

This is how it looks in my app:

  1. AsyncTask is started in activity OnStart() along with showing dialog box
  2. Data is being downloaded in inner class extending AsyncTask
  3. After data is downloaded the dialog box is dismissed and further data processing initialized (OnPostExecute())

The drawback could be that OnStart() is called on the first activity call, but also after restoring it (for example after minimizing the application). So AsyncTask can be executed few times in opposite to OnCreate(), that is called only once - when activity is created (not when it is restored).

There can also be some issues if You do the jUnit test of such activity with dialog in AsyncTask - let me know if You do - will post some solution

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜