Skip to content

Instantly share code, notes, and snippets.

@noaht11
Last active January 17, 2018 13:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noaht11/57ddfeaa82123b5f216c to your computer and use it in GitHub Desktop.
Save noaht11/57ddfeaa82123b5f216c to your computer and use it in GitHub Desktop.
Cancelling an AsyncTask in onDestroy
private static final String STATE_TASK_RUNNING = "taskRunning";
private MyTask mTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
// Setup views
...
// Check if the task was running so we can restart it
if (savedInstanceState != null) {
if (savedInstanceState.getBoolean(STATE_TASK_RUNNING, false)) {
mTask = new MyTask();
mTask.execute(...);
}
}
}
/**
* Suppose this was a click handler for something
*/
public void startTaskClicked(View view) {
// We can start the task now
mTask = new MyTask();
mTask.execute(...);
}
private boolean isTaskRunning() {
return (mTask != null) && (mTask.getStatus() == AsyncTask.Status.RUNNING);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// If the task is running, save it in our state
if (isTaskRunning()) {
outState.putBoolean(STATE_TASK_RUNNING, true);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Cancel the task if it's running
if (isTaskRunning()) {
mTask.cancel(true);
}
}
private class MyTask extends AsyncTask<...> {
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment