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:
If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes. And when it completes, the AsyncTask won't update the UI of the new Activity.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .
Android AsyncTask going to do background operation on background thread and update on main thread. In android we cant directly touch background thread to main thread in android development. asynctask help us to make communication between background thread to main thread.
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 MediaPlayer
object is still running using the code above, then call AsyncTask.cancel(true)
and override void onCancelled (Result result)
and then kill the MediaPlayer
from within your thread. Remember, onCancelled
will only be called AFTER doInBackground
returns (or you can periodically check isCancelled()
to see if something has called cancel()
on your thread. If you set cancel(true)
then I believe it won't bother waiting for doInBackground
to finish, but of course that's not as clean.
I don't know exactly what you're doing in you AsyncTask, but what ever it is should keep going even it onPause()
is called. If onDestroy()
is called and you have your AsyncTask referencing stuff in your Activity, you're going to run into problems though because the AsycnTask will essentially start throwing null pointer exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With