第一次写AsyncTask
,我似乎有一个微妙的设计缺陷,防止ProgressDialog
,ProgressBar
,甚至Log.d()
正常工作。我怀疑,不知何故,我实际上并没有创建一个新的线程/任务。Android:ASyncTask的行为违背文档
简称:症状
一个
ProgressDialog
是在构造函数创建的,该代码的Android订单给它显示onPreExecute()
,但是对话从来没有显示。onProgressUpdate()
应该在我从doInBackground()
内调用publishProgress()
时执行,对吗?那么,它不会。相反,它在doInBackground()
完成时执行。
长:
事情我必须通过仿真器,并在可能的情况核实调查
,在手机上:onPreExecute()
是绝对称得上进度直到
doInBackground()
完成后才重置酒吧update_dialog.show()
肯定会执行,但除非我删除中的.dismiss()
;我想象对话框,像进度条,不显示,直到后doInBackground()
完成,但自然是立即解雇代码将愉快地显示对话框时,没有计算涉及
doInBackground()
绝对调用publishProgress()
当它发生时,
onProgressUpdate()
不立即执行!也就是说,我在函数中有一个断点,调试器不会在那里停止,直到doInBackground()
完成! (也许这是调试器的一个现象,而不是doInBackground()
,但我观察在移动设备上相同的症状)的都会更新进度条...
doInBackground()
完成一切同样只后,在Android的监视器
Log.d()
数据显示,高达doInBackground()
一切完成后,才
,当然还有对话并不无论是在模拟器或设备上显示出来(除非我删除
.dismiss()
fromonPostExecute()
)
任何人都可以帮助找到问题吗?理想情况下,我想要一个工作对话框,但Android已经弃用了,无论如何,我会很好地处理一个工作进度条。
代码
下面是要领,计算&Ç:少细节
当我打电话AsyncTask
从主线程:
if (searching) { // this block does get executed!
Compute_Task my_task = new Compute_Task(overall_context, count);
my_task.execute(field, count, max_x, max_y);
try { result = my_task.get(); } catch (Exception e) { }
}
的AsyncTask
本身:
private class Compute_Task extends AsyncTask<Object, Integer, Integer> {
public Compute_Task(Context context, int count) {
super();
current_positions = 0;
update_dialog = new ProgressDialog(context);
update_dialog.setIndeterminate(true);
update_dialog.setCancelable(false);
update_dialog.setTitle("Thinking");
update_dialog.setMessage("Please wait");
}
protected void onPreExecute() {
super.onPreExecute();
update_dialog.show();
ProgressBar pb = ((ProgressBar) ((Activity) overall_context).findViewById(R.id.progress_bar));
pb.setMax(base_count);
pb.setProgress(0);
}
protected void onPostExecute() {
super.onPostExecute();
update_dialog.dismiss();
}
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
ProgressBar pb = ((ProgressBar) ((Activity) overall_context).findViewById(R.id.progress_bar));
pb.setMax(base_count);
pb.incrementProgressBy(1);
Log.d(tag, values[0].toString());
}
protected Integer doInBackground(Object... params) {
Integer result = compute_scores(
(boolean[][]) params[0], (Integer) params[1], (Integer) params[2], (Integer) params[3], 0)
);
return result;
}
public int compute_scores(boolean[][] field, int count, int max_x, int max_y, int level) {
int result, completed = 0;
switch(count) {
// LOTS of computation goes on here,
// including a recursive call where all params are modified
if (level == 0)
publishProgress(++completed);
}
}
ProgressDialog update_dialog;
}