Question

I'm using an AsyncTask subclass for some background processing. The problem is that when I use the class with the .get() method, the ProgressDialog I specify in the onPreExecute() does not show.

I works fine if I use a callback withing the onPostExecute() method.

My first thought was that this was because the .get() waits for the process to complete but that can't be blocking the UI thread either so that's not the case.

Can anyone explain why this behavior is so and if there is a workaround for this ?? I'd really like to use the .get() method if I can.

Was it helpful?

Solution

I initially accepted the other answer but it seems to be wrong.

The .get() method will block the UI thread to wait for the result and any dialogs displayed will also be blocked. This is the expected behavior for this method.

The only alternative is to not use .get() if the background activity is for any noticable amount of time and instead use callback methods to the calling activity.

OTHER TIPS

Calling AysncTask.get() on UI thread will block UI thread execution and make UI thread waiting for AysncTask.doInBackground() to finish. By doing this, you are actually sacrifice the benefit of AsycnTask, all code now are executed synchronously in UI thread and Background thread (still two thread, but UI thread now wait for background thread).

Also bear in mind that you will probably get ANR exception (blocked more than 5 seconds) by calling get() on UI thread.

If you really have to use it, call your showDialog() method before myAsyncTask.get():

showDialog();
myAsyncTask.execute();
myAsyncTask.get(); // <-- UI thread blocked and wait at this point.
dismissDialog();// <-- This line will be executed after doInBackground() finish.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top