AsyncTask ProgressDialog not showing with .get()

穿精又带淫゛_ 提交于 2020-01-05 11:53:52

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/10659759/asynctask-progressdialog-not-showing-with-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!