我有一个带有一个按钮的 Activity,它可以启动一个长时间运行的任务。我使用 AsyncTask 执行任务并显示一个确定的 ProgressBar,该进度条会随着任务的进行而更新。第一次运行任务时一切正常,但在随后的运行中会出现对话框,但已经处于 100% 和 100/100。我在我的活动中同时覆盖了 onCreateDialog 和 onPrepareDialog。我认为使用 setProgress(0) 会重置对话框,但这不起作用。我在 AsyncTask 的 onPreExecute 方法中使用 showDialog,在 AsyncTask 的 onPostExecute 中使用dismissDialog。我能够重置对话框的唯一方法是在 onPostExecute 中使用 removeDialog,但我宁愿不重新创建对话框,因为我将重复使用多次。相关代码如下。这是 API 级别 10。
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
progressDialog = new ProgressDialog(ProtoBufSerializationTestActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(true);
progressDialog.setMax(100);
progressDialog.setMessage("Testing...");
return progressDialog;
default:
return null;
}
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case PROGRESS_DIALOG:
ProgressDialog tmp = (ProgressDialog)dialog;
tmp.setProgress(0);
tmp.setSecondaryProgress(0);
return;
default:
Log.e("test", "Unknown dialog requested");
}
}
private class SerializationTestTask extends AsyncTask<Void, Integer, Long> {
@Override
protected void onPreExecute() {
showDialog(PROGRESS_DIALOG);
}
@Override
protected Long doInBackground(Void... params) {
long accumulator = 0;
int totalSize = 0;
for (int i = 0; i < 10000; i++) {
final long start = System.nanoTime();
//code to be timed
final long end = System.nanoTime();
accumulator += end - start;
if (i % 100 == 0) {
publishProgress(i);
}
}
return accumulator;
}
@Override
protected void onPostExecute(Long aLong) {
dismissDialog(PROGRESS_DIALOG);
results.setText(String.format("Serialized Message 10000 times.\nAverage time to serialize %.3fms", (double) aLong / 1e10));
}
@Override
protected void onProgressUpdate(Integer... values) {
progressDialog.incrementProgressBy(1);
}
编辑在接受@Arhimed 的建议后,我得到了以下代码。它要简单得多。我本可以使用DialogFragment
,但我认为在这种情况下没有必要。
private class SerializationTestTask extends AsyncTask<Void, Integer, Long> {
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(ProtoBufSerializationTestActivity.this, "Serialization Test", "Testing...", false);
}
@Override
protected Long doInBackground(Void... params) {
long accumulator = 0;
int totalSize = 0;
for (int i = 0; i < 10000; i++) {
final long start = System.nanoTime();
//code to be timed
final long end = System.nanoTime();
accumulator += end - start;
if (i % 100 == 0) {
publishProgress(i);
}
}
return accumulator;
}
@Override
protected void onPostExecute(Long aLong) {
dialog.dismiss();
results.setText(String.format("Serialized Message 10000 times.\nAverage time to serialize %.3fms", (double) aLong / 1e10));
}
@Override
protected void onProgressUpdate(Integer... values) {
dialog.incrementProgressBy(1);
}
}