最近在做安卓程序过程中,写了一个按钮走秒的messageBox控件,走秒的实现是用异步线程AsyncTask实现的,具体如下
public class TimerDisplay extends AsyncTask<Void, Integer, Void> {
private int count = 10;
private Button handlerButton;
private AlertDialog currentAlertDialog;
private String handlerText = null;
public TimerDisplay(Button handlerButton, AlertDialog currentAlertDialog) {
this.handlerButton = handlerButton;
this.currentAlertDialog = currentAlertDialog;
this.handlerText = handlerButton.getText().toString();
}
@Override
protected Void doInBackground(Void... params) {
try {
while (count >= 0) {
if (currentAlertDialog.isShowing()) {
publishProgress(count);
count--;
Thread.sleep(1000);
} else {
count = -999;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
if (values[0] > 0) {
handlerButton.setText(handlerText + " (" + String.valueOf(values[0]) + ")");
super.onProgressUpdate(values);
} else if (values[0] == 0) {
handlerButton.performClick();
currentAlertDialog.dismiss();
}
}
}
在外层调用该类的方式如下:
TimerDisplay td = new TimerDisplay(positiveButton, alertDialog);
td.execute();
最后发现了这样一个bug
该messageBox在应用中多次创建时,且每次都是在走秒未走完时,关闭掉dialoge,循环操作次数达到7次以上时,messageBox不会出现走秒的情况了
在查找问题的过程中,发现每次之所以出现不走秒的情况,是因为异步线程没有走doInBackground()方法,在代码中打log发现虽然没有走doInBackground()方法,但是走了
onPreExecute() 方法,且线程处于running状态,
最后查找问题发现异步线程在设计之初,就有一个个数限制,当超过这个个数之后,线程就不会被执行,
解决办法是
http://stackoverflow.com/questions/16832376/asynctask-doinbackground-not-called
TimerDisplay td = new TimerDisplay(positiveButton, alertDialog);
FULL_TASK_EXECUTOR = (ExecutorService) Executors.newCachedThreadPool();
td.executeOnExecutor(FULL_TASK_EXECUTOR);
创建线程池,把异步线程放在线程池中,当线程没有使用时,会被移出线程池,这个每次创建异步线程都能成功