我正在使用异步任务,如下所示:
private first_async first; // global variable
// In onCreate
first = new first_async();
first.execute(1);
// then on click of the button I want to stop this, but it works after some time like this:
if (!first.isCancelled()) {
first.cancel(false);
}
private class first_async extends AsyncTask<Integer, Void, Void> {
int var;
@Override
protected void doInBackground(Integer... params) {
while (!isCancelled()) {
var = params[0];
// do some task
}
return null;
}
@Override
protected void onPostExecute(void thumb) {
super.onPostExecute(thumb);
if (var >= 7) {
} else {
first_time_imageURL = new first_time_get_images_URL();
first_time_imageURL.execute(var+1);
}
}
}
所以问题是在一段时间后取消异步任务工作。如果我不正确,请纠正我,或者如果有其他替代方案,请提及。
答案 0 :(得分:0)
if (!first.isCancelled()) {
first.cancel(false);
}
这里假的应该是真的,这将取消Asynctask。所以:
first.cancel(true);