Updating progress dialog in Activity from AsyncTask

瘦欲@ 提交于 2019-12-17 02:31:41

问题


In my app I am doing some intense work in AsyncTask as suggested by Android tutorials and showing a ProgressDialog in my main my activity:

dialog = ProgressDialog.show(MyActivity.this, "title", "text");
new MyTask().execute(request);

where then later in MyTask I post results back to activity:

class MyTask extends AsyncTask<Request, Void, Result> {

    @Override protected Result doInBackground(Request... params) {
        // do some intense work here and return result
    }

    @Override protected void onPostExecute(Result res) {
        postResult(res);
    }
}

and on result posting, in main activity I hide the dialog:

protected void postResult( Result res ) {
    dialog.dismiss();
    // do something more here with result...
}

So everything is working fine here, but I would like to somehow to update the progress dialog to able to show the user some real progress instead just of dummy "Please wait..." message. Can I somehow access the progress dialog from MyTask.doInBackground, where all work is done?

As I understand it is running as separate Thread, so I cannot "talk" to main activity from there and that is why I use onPostExecute to push the result back to it. But the problem is that onPostExecute is called only when all work is already done and I would like to update progress the dialog in the middle of doing something.

Any tips how to do this?


回答1:


AsyncTask has method onProgressUpdate(Integer...) that you can call each iteration for example or each time a progress is done during doInBackground() by calling publishProgress().

Refer to the docs for more details




回答2:


you can update from AsyncTask's method onProgressUpdate(YOUR_PROGRESS) that can be invoked from doInBackground method by calling publishProgress(YOUR_PROGRESS) the data type of YOUR_PROGRESS can be defined from AsyncTask<Int, YOUR_PROGRESS_DATA_TYPE, Long>



来源:https://stackoverflow.com/questions/4591878/updating-progress-dialog-in-activity-from-asynctask

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