Last active
January 17, 2018 13:02
-
-
Save noaht11/57ddfeaa82123b5f216c to your computer and use it in GitHub Desktop.
Cancelling an AsyncTask in onDestroy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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