Why are you using the AsyncTask in this way?
What it does now:
- Creates the MediaPlayer on the main thread - it's a long process, so it should go to the background thread, it can cause ANRs.
- Calls setVolume, start, setLooping from background thread - these are very short commands, so no need to run them in the background.
- Calls stop, reset and release from the main thread.
What would be a working solution:
- Create your MediaPlayer from the background thread.
- After created, set looping and start playing. (These are fast calls, so you can do it from main thread if you prefer it, but only after your MediaPlayer has been created.)
- When you want to stop play (in your example, when onPause called), you can call stop() and release(). But check before, if it has been created and started (because it is done in the background thread, it is possible, that you pause your activity before mediaplayer starts playing the audio).
EDIT: this is the source code I tested, it works for me (even if the preparing time for the media player is really slow, and the activity is paused before it loads):
private MediaPlayer mMediaPlayer;
private volatile boolean mMediaPlayerStopped ;
@Override
protected void onPause() {
Log.v("MusicTest", "Paused activity") ;
stopMediaPlayer();
super.onPause();
}
private void stopMediaPlayer() {
Log.v("MusicTest", "Stopping MediaPlayer") ;
mMediaPlayerStopped = true ;
if (mMediaPlayer != null) {
mMediaPlayer.stop() ;
mMediaPlayer.reset() ;
mMediaPlayer.release() ;
mMediaPlayer = null ;
}
}
private void startMediaPlayer() {
mMediaPlayerStopped = false ;
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
Log.v("MusicTest", "Creating MediaPlayer") ;
MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.alarm10);
mediaPlayer.setVolume(100, 100) ;
mediaPlayer.setLooping(true) ;
Log.v("MusicTest", "Starting MediaPlayer") ;
mediaPlayer.start() ;
mMediaPlayer = mediaPlayer ;
if (mMediaPlayerStopped) {
Log.v("MusicTest", "MediaPlayer was stopped while preparing") ;
stopMediaPlayer();
}
return null;
}
}.execute();
}
@Override
protected void onResume() {
Log.v("MusicTest", "Resumed activity") ;
startMediaPlayer();
super.onResume();
}