我正在使用AsyncTask
. Cancellable
显示提取操作运行时间的进度条。
当用户取消(决定反对)操作时,我想取消/中止AsyncTask
运行。处理这种情况的理想方法是什么?
我正在使用AsyncTask
. Cancellable
显示提取操作运行时间的进度条。
当用户取消(决定反对)操作时,我想取消/中止AsyncTask
运行。处理这种情况的理想方法是什么?
刚刚发现AlertDialogs
我boolean cancel(...);
一直在使用的任何地方实际上什么也没做。伟大的。
所以...
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;
}
// ...
}
如果您正在进行计算:
isCancelled()
定期检查。如果您正在执行 HTTP 请求:
HttpGet
或HttpPost
某处的实例(例如公共字段)。cancel
,打电话request.abort()
。这将导致IOException
您的doInBackground
.就我而言,我有一个在各种 AsyncTasks 中使用的连接器类。为了简单起见,我在abortAllRequests
该类中添加了一个新方法,并在调用cancel
.
问题是 AsyncTask.cancel() 调用仅调用任务中的 onCancel 函数。这是您要处理取消请求的地方。
这是我用来触发更新方法的一个小任务
private class UpdateTask extends AsyncTask<Void, Void, Void> {
private boolean running = true;
@Override
protected void onCancelled() {
running = false;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
onUpdate();
}
@Override
protected Void doInBackground(Void... params) {
while(running) {
publishProgress();
}
return null;
}
}
很简单:不要使用AsyncTask
. AsyncTask
专为快速结束(数十秒)的短操作而设计,因此不需要取消。“音频文件播放”不符合条件。您甚至不需要后台线程来播放普通的音频文件。
唯一的方法是检查 isCancelled() 方法的值并在它返回 true 时停止播放。
这就是我编写 AsyncTask
的方式,关键是添加 Thread.sleep(1);
@Override protected Integer doInBackground(String... params) {
Log.d(TAG, PRE + "url:" + params[0]);
Log.d(TAG, PRE + "file name:" + params[1]);
downloadPath = params[1];
int returnCode = SUCCESS;
FileOutputStream fos = null;
try {
URL url = new URL(params[0]);
File file = new File(params[1]);
fos = new FileOutputStream(file);
long startTime = System.currentTimeMillis();
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
byte[] data = new byte[10240];
int nFinishSize = 0;
while( bis.read(data, 0, 10240) != -1){
fos.write(data, 0, 10240);
nFinishSize += 10240;
**Thread.sleep( 1 ); // this make cancel method work**
this.publishProgress(nFinishSize);
}
data = null;
Log.d(TAG, "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d(TAG, PRE + "Error: " + e);
returnCode = FAIL;
} catch (Exception e){
e.printStackTrace();
} finally{
try {
if(fos != null)
fos.close();
} catch (IOException e) {
Log.d(TAG, PRE + "Error: " + e);
e.printStackTrace();
}
}
return returnCode;
}
我们的全局 AsyncTask 类变量
LongOperation LongOperationOdeme = new LongOperation();
以及中断 AsyncTask 的 KEYCODE_BACK 动作
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
LongOperationOdeme.cancel(true);
}
return super.onKeyDown(keyCode, event);
}
这个对我有用。
我不喜欢cancel(true)
不必要地强制中断我的异步任务,因为它们可能有要释放的资源,例如关闭套接字或文件流、将数据写入本地数据库等。另一方面,我遇到过这样的情况异步任务在部分时间拒绝完成自己,例如有时当主要活动被关闭并且我请求异步任务从活动的onPause()
方法内部完成时。所以这不是简单调用的问题running = false
。我必须采用混合解决方案:两者都调用running = false
,然后给异步任务几毫秒的时间来完成,然后调用cancel(false)
或cancel(true)
。
if (backgroundTask != null) {
backgroundTask.requestTermination();
try {
Thread.sleep((int)(0.5 * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
if (backgroundTask.getStatus() != AsyncTask.Status.FINISHED) {
backgroundTask.cancel(false);
}
backgroundTask = null;
}
结果,doInBackground()
完成后,有时会调用该onCancelled()
方法,有时会调用onPostExecute()
. 但至少可以保证异步任务终止。
参考 Yanchenko 在 2010 年 4 月 29 日的回答:在每次执行 AsyncTask 期间必须多次执行“doInBackground”下的代码时,使用“while(running)”方法很简洁。如果每次执行 AsyncTask 时必须只执行一次“doInBackground”下的代码,则将“doInBackground”下的所有代码包装在“while(running)”循环中不会阻止后台代码(后台线程)在AsyncTask 本身被取消,因为只有在 while 循环内的所有代码至少执行一次后才会评估“while(running)”条件。因此,您应该 (a.) 将 'doInBackground' 下的代码分解为多个 'while(running)' 块或 (b.) 执行多个 'isCancelled'https://developer.android.com/reference/android/os/AsyncTask.html。
对于选项(a.),因此可以将 Yanchenko 的答案修改如下:
public class MyTask extends AsyncTask<Void, Void, Void> {
private volatile boolean running = true;
//...
@Override
protected void onCancelled() {
running = false;
}
@Override
protected Void doInBackground(Void... params) {
// does the hard work
while (running) {
// part 1 of the hard work
}
while (running) {
// part 2 of the hard work
}
// ...
while (running) {
// part x of the hard work
}
return null;
}
// ...
对于选项 (b.),您在“doInBackground”中的代码将如下所示:
public class MyTask extends AsyncTask<Void, Void, Void> {
//...
@Override
protected Void doInBackground(Void... params) {
// part 1 of the hard work
// ...
if (isCancelled()) {return null;}
// part 2 of the hard work
// ...
if (isCancelled()) {return null;}
// ...
// part x of the hard work
// ...
if (isCancelled()) {return null;}
}
// ...