doAsyncTask 的 doInBackground 中的 Stop 方法
我有这个 AsyncTask:
private class GetMyFlights extends AsyncTask<String, Void, Integer> {
private ProgressDialog dialog;
public GetMyFlights(ListActivity activity) {}
@Override
protected Integer doInBackground(String... params) {
return getData();
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
//...
}
}
当我更改为另一个活动时,我想停止它。所以我设置了这个:
@Override
protected void onPause() {
if(mGetMyFlights != null){
mGetMyFlights.cancel(true);
Log.d(TAG, "MyFlights onPause, cancel task");
}
super.onPause();
}
但是当我更改活动时,getData 中的代码仍然有效。我如何确定已停止?
I have this AsyncTask:
private class GetMyFlights extends AsyncTask<String, Void, Integer> {
private ProgressDialog dialog;
public GetMyFlights(ListActivity activity) {}
@Override
protected Integer doInBackground(String... params) {
return getData();
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
//...
}
}
When I change to another activity I want to stop it. So I set this:
@Override
protected void onPause() {
if(mGetMyFlights != null){
mGetMyFlights.cancel(true);
Log.d(TAG, "MyFlights onPause, cancel task");
}
super.onPause();
}
But the code inside getData is still working when I change my activity. How can I be sure is stop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从我读到的所有内容来看,cancel() 方法似乎不是停止 AsyncTask 的可靠方法。中断被发送到后台线程,但这仅对可中断任务有效。普遍的共识是,为了确保 AsynTask 停止,您应该在 AsyncTask 的 doInBackground 方法中不断检查 isCancelled() 。
From everything I've read, it seems that the cancel() method is not a reliable way to stop an AsyncTask. An interrupt is sent to the background thread, but this is only effective on interruptable tasks. The general consensus is that, to ensure the AsynTask is stopped, you should continually check isCancelled() within the doInBackground method of your AsyncTask.
我通常做的是在
AsyncTask
实例上调用cancel(true)
并检查doInBackground
中的Thread.interrupted()
。您可以检查isCancelled()
,但如果实际工作是在独立于您的AsyncTask
并且不知道它的其他类中完成的,那么这不起作用。例如(直接从我自己的Data()
方法复制到我的Data
类中,独立于任何活动、异步任务等):只需确保处理
doInBackground()
中的InterruptedException
,例如:还值得注意的是,如果任务不会调用
onPostExecute()
被取消。相反,onCancelled()
被调用。What I usually do is call
cancel(true)
on theAsyncTask
instance and checkThread.interrupted()
indoInBackground
. You could checkisCancelled()
, but that doesn't work if the actual work is done in some other class that is independent from yourAsyncTask
and doesn't know about it. For example (copied directly from my owngetData()
method, inside myData
class, independent from any activities, async tasks, etc.):Just make sure to handle the
InterruptedException
in yourdoInBackground()
, e.g.:Also worth noting that
onPostExecute()
is not called if the task is cancelled. Instead,onCancelled()
is called.