Reputation: 1
In my android project I use many AsynTask
in one activity. I need to stop one AsynTask
when I start other.
I'm using myAsynTask.cancel(true);
in my android project. But it does stop the 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;
}
Upvotes: 0
Views: 62
Reputation: 3401
From the official Android documentation:
A task can be cancelled at any time by invoking
cancel(boolean)
. Invoking this method will cause subsequent calls toisCancelled()
to return true. After invoking this method, onCancelled(Object), instead ofonPostExecute(Object)
will be invoked afterdoInBackground(Object[])
returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value ofisCancelled()
periodically fromdoInBackground(Object[])
, if possible (inside a loop for instance.)
Upvotes: 1
Reputation: 7759
You actively have to check for isCancelled
while executing your loop in doInBackground
.
You should break
the loop if isCanceled
is true.
Upvotes: 1