[英]how to stop asyncTask android
在我的Android项目中,我在一项活动中使用了许多AsynTask
。 启动其他AsynTask
时,我需要停止其中一个。
我正在使用myAsynTask.cancel(true);
在我的android项目中。 但是它确实停止了AsynTask
。
protected String doInBackground(String... args) {
HashMap<String, String> params = new HashMap<>();
params.put("id", args[0]);
Log.d("get value: ", params.toString());
JSONObject json = jParser.makeHttpRequest(url_comment, "GET", params);
Log.d("All matches: ", json.toString());
if(isCancelled()) {
finish();
}
else {
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONmatches = json.getJSONArray(TAG_vedio);
for (int i = 0; i < JSONmatches.length(); i++) {
JSONObject c = JSONmatches.getJSONObject(i);
String title = c.getString(TAG_title);
String url = c.getString(TAG_url);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_title, title);
map.put(TAG_url, url);
arrayList22.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
您积极把检查isCancelled
在执行在循环doInBackground
。
如果isCanceled
为true,则应该break
循环。
从官方的Android文档中 :
可以通过调用
cancel(boolean)
任务。 调用此方法将导致对isCancelled()
后续调用返回true。 调用此方法后,在doInBackground(Object[])
返回之后,将调用onPostExecute(Object)
而不是onPostExecute(Object)
。 为了确保尽快取消任务,如果可能的话(例如在循环内doInBackground(Object[])
,应始终定期从doInBackground(Object[])
检查isCancelled()
的返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.