While the following code is executing, I want the ability to stop it from running, even if it’s halfway done. For example, if I have a boolean x = true; then I want to send some king of stop(ReadJSONFeedMainTask); command to this thread/class. I want to cancel everything, even what may be occurring in onPostExecute(). How can I do this?
Here is my code:
private void doStuff() {
new ReadJSONFeedMainTask().execute(urlString);
}
private class ReadJSONFeedMainTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return Helper.readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
try {
dictItems = new ArrayList<HashMap<?, ?>>();
JSONArray jsonArray = new JSONArray(result);
Log.i("JSON", "Number of items in feed: " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
Iterator<?> it = jsonObject.keys();
while (it.hasNext())
{
// do a bunch of time consuming stuff
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
To cancel the task, do asyncTaskVariable.cancel(). If it’s already in onPostExecute it’s going to have to finish it though- you’re on the UI thread and can’t kill it. Best you can do there is set a variable that tells it to terminate (from another thread of course), and have it check that variable periodically, returning if its set.