当我在 AsyncTask 中启动操作时,我遇到了 ProgressDialog UI 被卡住的问题。 我的问题与其他类似问题有些不同,因为我的后台任务由两部分组成: - 第一部分 (loadDB()) 与数据库访问相关 - 第二部分 (buildTree()) 与构建 ListView 内容相关,并以 runOnUiThread 调用开始
进度对话框在任务的第 1 部分正确更新,但在第 2dn 部分没有更新。 我尝试在 AsyncTask 的 onPostExecute 中移动 buildTree 部分,但它没有帮助,这部分代码仍然导致进度暂时卡住,直到这部分(有时相当冗长)工作完成。我无法从头开始重新编码 buildTree 部分,因为它基于我使用的外部代码。
关于如何解决这个问题的任何提示?有没有一种方法可以强制更新屏幕上的某些对话框?
代码在这里:
public class TreePane extends Activity {
private ProgressDialog progDialog = null;
public void onCreate(Bundle savedInstanceState) {
// first setup UI here
...
//now do the lengthy operation
new LoaderTask().execute();
}
protected class LoaderTask extends AsyncTask<Void, Integer, Void>
{
protected void onPreExecute() {
progDialog = new ProgressDialog(TreePane.this);
progDialog.setMessage("Loading data...");
progDialog.show();
}
protected void onPostExecute(final Void unused) {
if (progDialog.isShowing()) {
progDialog.dismiss();
}
}
protected void onProgressUpdate(Integer... progress) {
//progDialog.setProgress(progress[0]);
}
protected Void doInBackground(final Void... unused)
{
//this part does not block progress, that's OK
loadDB();
publishProgress(0);
//long UI thread operation here, blocks progress!!!!
runOnUiThread(new Runnable() {
public void run() {
buildTree();
}
});
return null;
}
}
public void buildTree()
{
//build list view within for loop
int nCnt = getCountHere();
for(int =0; i<nCnt; i++)
{
progDialog.setProgress(0);
//add tree item here
}
}
}
最佳答案
不要在 UI 线程中运行整个 buildTree()
方法。
相反,仅运行您想要在 UI 线程中对 UI 进行的更改:
protected Void doInBackground(final Void... unused)
{
//this part does not block progress, that's OK
loadDB();
publishProgress(0);
buildTree();
return null;
}
然后:
public void buildTree()
{
//build list view within for loop
int nCnt = getCountHere();
for(int =0; i<nCnt; i++)
{
progDialog.setProgress(0);
runOnUiThread(new Runnable() {
public void run() {
// update your UI here and return
}
});
// now you can update progress
publishProgress(i);
}
}
关于android - AsyncTask 中的 ProgressDialog 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8533220/