我正在调用几个AsyncTasks来完成一项工作。为了知道什么时候完成。我有一个对象(同步)和一个分子,它保存当前运行AsyncTasks的数量。
部署完所有内容后,我会执行以下操作:
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage(getString(R.string.please_wait));
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setCancelable(false);
pd.setProgress(0);
pd.setMax(Utils.getAsyncs());
pd.show();
new Thread(new Runnable() {
@Override
public void run() {
while (Utils.getAsyncs() > 0)
pd.setProgress(pd.getMax() - Utils.getAsyncs());
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
}
});
}
}).start();
当对话框显示时,它会开始前进,但在某些时候它会卡在所有内容的末尾,然后解散(正如预期的那样)。
我试图把
pd.setProgress(pd.getMax() - Utils.getAsyncs());
也在runOnUiThread中,但这使事情变得更糟,我确信我错过了其他的东西。因此我的问题。感谢
按要求编辑:
public static int getAsyncs() {
return asyncs;
}
编辑2:我根据评论
进行了以下操作while (Utils.getAsyncs() > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
runOnUiThread(new Runnable() {
public void run() {
pd.setProgress(pd.getMax() - Utils.getAsyncs());
}
});
}
似乎更好
答案 0 :(得分:1)
在班级字段中
private Handler progressHandler = new Handler();
private Runnable progressRunnable = new Runnable() {
@Override
public void run() {
progressDialog.setProgress(progressValue);
progressHandler.postDelayed(this, 1000);
}
};
启动耗时线程时
// Here start time consuming thread
// Here show the ProgressDialog
progressHandler.postDelayed(progressRunnable, 1000);
耗时线程结束时
progressHandler.removeCallbacks(progressRunnable);
/// Here dismiss the ProgressDialog.
<强>增加:强>
相反,新的线程(新的Runnable)可能会用于您耗时的代码,我建议这样做:
初始化任务:
MyTask task = new MyTask();
task.execute();
// Here show the PorgressDialog
progressHandler.postDelayed(progressRunnable, 1000);
在主类中添加此私有类:
private class MyTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
//Here do your time consuming work
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
// This will be called on the UI thread after doInBackground returns
progressHandler.removeCallbacks(progressRunnable);
progressDialog.dismiss();
}
}
答案 1 :(得分:0)
做点喜欢的事
new Thread(new Runnable() {
public void run() {
while (prStatus < 100) {
prStatus += 1;
handler.post(new Runnable() {
public void run() {
pb_2.setProgress(prStatus);
}
});
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(prStatus == 100)
prStatus = 0;
}
}
}).start();