我有一个代码如下,每当我取消对话框时,就会发生InterruptException并且cancel
方法不起作用。如下所示,我在cancel
方法中打印onPostExecute
的状态,它是假的而不是真的。在添加isRunning
参数之前,显然线程仍然在后台运行。虽然isRunning
确实停止了线程(onPostExecute
方法已执行),但我想知道为什么会发生异常以及为什么我仍然在false
方法中得到isCanceled
。谢谢!
public void startDownload(View view){
dialog = new ProgressDialog(this);
final Downloader downloader = new Downloader(this, dialog);
downloader.execute(0);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
downloader.cancel(true);
}
});
}
public class Downloader extends AsyncTask<Integer, Integer, String> {
private Context context;
private PowerManager.WakeLock wakeLock;
private ProgressDialog dialog;
public boolean isRunning = true;
public Downloader(Context context, ProgressDialog dialog) {
this.context = context;
this.dialog = dialog;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
wakeLock.acquire();
dialog.setMessage("Downloading...");
dialog.setIndeterminate(true);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setCancelable(false);
dialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
isRunning = false;
}
});
dialog.show();
}
@Override
protected String doInBackground(Integer[] params) {
int count = params[0];
while(count<100 && isRunning){
publishProgress(count);
try{
count++;
System.out.println(count);
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dialog.setIndeterminate(false);
dialog.setMax(100);
dialog.setProgress(values[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
wakeLock.release();
dialog.dismiss();
if (s != null)
Toast.makeText(context,"Download error: "+ s, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
System.out.println(isCancelled());
}
}
答案 0 :(得分:0)
确保您没有使用.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
而不是.execute()
执行其他AsyncTask,或者并行启动此AsyncTask。否则,如果您已经在后台运行另一个AsyncTask,那么另一个AsyncTask将在最后一个完成之前运行。
另一方面,尽量不要使用自定义布尔值跟踪AsyncTask生命周期状态,为此,使用isCancelled()
在运行时检查内容或中断任何循环,如果需要,覆盖AsyncTask&#39; s onCancelled()
方法来实现您当时可能需要的任何功能。
请勿忘记查看参考资料:AsyncTask - Android Developers。