本文介绍了从 AsyncTask 更新 Activity 中的进度对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我按照 Android 教程的建议在 AsyncTask 中做了一些紧张的工作,并在我的主要活动中显示了一个 ProgressDialog:

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);

然后在 MyTask 后面我将结果发布回活动:

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...
}

所以这里一切正常,但我想以某种方式更新进度对话框,以便能够向用户显示一些真正的进度,而不是仅仅显示请稍候..."的假消息.我可以从 MyTask.doInBackground 以某种方式访问​​进度对话框,在那里完成所有工作吗?

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?

据我所知,它作为单独的线程运行,所以我无法从那里与主要活动对话",这就是为什么我使用 onPostExecute 将结果推回它.但问题是 onPostExecute 仅在所有工作都已完成并且我想在做某事的过程中更新对话框的进度时才被调用.

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?

推荐答案

AsyncTask 有方法 onProgressUpdate(Integer...) 你可以调用每个迭代例如或每次进度完成doInBackground() 通过调用publishProgress().

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().

有关详细信息,请参阅文档

这篇关于从 AsyncTask 更新 Activity 中的进度对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 22:06