I have an AsyncTask that is executed before I move on to the next Activity. Inside this AsyncTask, I have a MediaPlayer.
protected void onPause() {
stopProgress();
Log.i(TAG, "onPAUSE");
try {
} finally {
// If we allocated a player, then cleanup after it
if (player != null) {
player.reset();
player.release();
player = null;
Log.d(TAG,"end of player cleanup");
}
}
super.onPause();
}
Use Scenario:
- Click play button in Activity 1
- Move on to Activity 2 before player even loads (log information from onPause is definitely called).
- While in Activity 2, player from Activity 1 plays when finished loading.
Nothing should happen to the AsyncTask. It will continue to run. However, this isn’t a great way to run a media player in the background (use a service for that). Your code will cancel the media player, but depending on what you have in your AsyncTask, it may still be active. You can ensure that the AsyncTask is killed by calling
cancel (boolean mayInterruptIfRunning)on the task.If for whatever reason your
MediaPlayerobject is still running using the code above, then callAsyncTask.cancel(true)and overridevoid onCancelled (Result result)and then kill theMediaPlayerfrom within your thread. Remember,onCancelledwill only be called AFTERdoInBackgroundreturns (or you can periodically checkisCancelled()to see if something has calledcancel()on your thread. If you setcancel(true)then I believe it won’t bother waiting fordoInBackgroundto finish, but of course that’s not as clean.