取消正在执行的 AsyncTask 的理想方法 [英] Ideal way to cancel an executing AsyncTask
本文介绍了取消正在执行的 AsyncTask 的理想方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 AsyncTask
在后台线程中运行远程音频文件提取和音频文件播放操作.Cancellable
进度条显示获取操作运行的时间.
I am running remote audio-file-fetching and audio file playback operations in a background thread using AsyncTask
. A Cancellable
progress bar is shown for the time the fetch operation runs.
我想在用户取消(决定反对)操作时取消/中止 AsyncTask
运行.处理这种情况的理想方法是什么?
I want to cancel/abort the AsyncTask
run when the user cancels (decides against) the operation. What is the ideal way to handle such a case?
推荐答案
刚发现AlertDialogs
的boolean cancel(...);
我一直在用到处实际上什么都不做.太好了.
所以……
Just discovered that AlertDialogs
's boolean cancel(...);
I've been using everywhere actually does nothing. Great.
So...
public class MyTask extends AsyncTask<Void, Void, Void> {
private volatile boolean running = true;
private final ProgressDialog progressDialog;
public MyTask(Context ctx) {
progressDialog = gimmeOne(ctx);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// actually could set running = false; right here, but I'll
// stick to contract.
cancel(true);
}
});
}
@Override
protected void onPreExecute() {
progressDialog.show();
}
@Override
protected void onCancelled() {
running = false;
}
@Override
protected Void doInBackground(Void... params) {
while (running) {
// does the hard work
}
return null;
}
// ...
}
这篇关于取消正在执行的 AsyncTask 的理想方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文