Monday, May 27, 2013

Release MediaPlayer in onDestroy() and onPause()

If you try run the last exercise of "Simple example of using MediaPlayer", you can notice that if you exit the app, the sound will still playing, and then switch back to the app, both old sound and new sound will overlap.

Actually, you have to release the MediaPlayer in onDestroy() and onPause(), when the app exit. Or any other handling method, depends on your own case.

 @Override
 protected void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
  if (mediaPlayer != null) {
   mediaPlayer.release();
   mediaPlayer = null; 
  }
 }

 @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  if (mediaPlayer != null) {
   mediaPlayer.release();
   mediaPlayer = null; 
  }
 }

Simple example of using MediaPlayer


Next:
- Get video size for MediaPlayer by implementing onVideoSizeChanged()


No comments: