Android ASync task ProgressDialog isn't showing until background thread finishes

后端 未结 4 444
遇见更好的自我
遇见更好的自我 2020-12-01 14:37

I\'ve got an Android activity which grabs an RSS feed from a URL, and uses the SAX parser to stick each item from the XML into an array. This all works fine but, as expected

相关标签:
4条回答
  • 2020-12-01 15:09

    It is because you used AsyncTask.get() that blocks the UI thread "Waits if necessary for the computation to complete, and then retrieves its result.".

    The right way to do it is to pass Activity instance to your AsyncTask by constructor, and finish whatever you want to do in AsyncTask.onPostExecution().

    0 讨论(0)
  • 2020-12-01 15:11

    If you subclass the AsyncTask in your actual Activity, you can use the onPostExecute method to assign the result of the background work to a member of your calling class.

    The result is passed as a parameter in this method, if specified as the third generic type.

    This way, your UI Thread won't be blocked as mentioned above. You have to take care of any subsequent usage of the result outside the subclass though, as the background thread could still be running and your member wouldn't have the new value.

    0 讨论(0)
  • 2020-12-01 15:21

    This works for me

    @Override
    protected void onPreExecute() {
            dialog = new ProgressDialog(viewContacts.this);
            dialog.setMessage(getString(R.string.please_wait_while_loading));
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);
            dialog.show();
        }
    
    0 讨论(0)
  • 2020-12-01 15:22

    I suspect something is blocking your UI thread after you execute the task. For example, I have seen folks do things like this:

    MyTask myTask = new MyTask();
    TaskParams params = new TaskParams();
    myTask.execute(params);
    myTask.get(5000, TimeUnit.MILLISECONDS);
    

    The get invocation here is going to block the UI thread (which presumably is spinning off the task here...) which will prevent any UI related stuff in your task's onPreExecute() method until the task actually completes. Whoops! Hope this helps.

    0 讨论(0)
提交回复
热议问题