我正在练习 AsyncTask
的工作,为此我想使用 onProgressUpdate
函数。目前在我的程序中,我有一个 UI,它允许用户选择输入(在 AsyncTask
完成后将显示在 TextView
中)和一个计时器(确定 Thread.sleep()
时间在 AsyncTask
)
我想做的是……如果用户选择时间 5。然后我想每隔一秒向 UI(调用进度对话框的地方)发送一个通知……指示进度5 个中的 1 ... 5 个中的 2 个 ... 5 个中的 3 个。
这是我到目前为止取得的进展:
public class ViewFiller extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... input) {
// TODO Auto-generated method stub
try {
int time;
if (input[1].equalsIgnoreCase("")) {
time = 0;
} else {
time = Integer.parseInt(input[1]) * 1000;
for (int i = 1; i <= time / 1000; i++) {
publishProgress(i, time);
}
Thread.sleep(time);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return input[0];
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
execute.setText("Execute");
progress.dismiss();
tvInput.setText(result);
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
execute.setText("Running...");
displayProgress("Updating field ... ");
// Start the progress dialog
progress.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
progress.setMessage("Updating field ... " + values[0] + " of "
+ values[1] / 1000);
}
}
当前的实现只直接给我 5 of 5
。谁能建议我一个解决方案?
最佳答案
因为它通过你的循环
的速度比你看到的要快
for (int i = 1; i <= time / 1000; i++) {
publishProgress(i, time);
你不需要那里的循环
。只需sleep
一段时间,然后显示您的进度,并在loop< 中使用
。有点像sleep()
和publishProgress()
/
try {
int time = 0;
for (int i = 1; i <= time / 1000; i++) {
if (input[1].equalsIgnoreCase("")) {
time = 0;
} else {
time = Integer.parseInt(input[1]) * 1000;
publishProgress(time);
}
Thread.sleep(time);
}
尽管我不确定 input
实际包含什么,但您可能需要 input[i]
。看起来它在其他方面总是一样的。
此外,CountDownTimer我认为这会很好。
关于android - onProgressUpdate 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19919570/