Code example for MediaPlayer

Methods: setOnCompletionListenersetOnErrorListenersetOnPreparedListenersetWakeMode

0
     * Makes sure the media player exists and has been reset. This will create the media player 
     * if needed, or reset the existing media player if one already exists. 
     */ 
    void createMediaPlayerIfNeeded() { 
        if (mPlayer == null) {
            mPlayer = new MediaPlayer();
 
            // Make sure the media player will acquire a wake-lock while playing. If we don't do 
            // that, the CPU might go to sleep while the song is playing, causing playback to stop. 
            // 
            // Remember that to use this, we have to declare the android.permission.WAKE_LOCK 
            // permission in AndroidManifest.xml. 
            mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
 
            // we want the media player to notify us when it's ready preparing, and when it's done 
            // playing: 
            mPlayer.setOnPreparedListener(this);
            mPlayer.setOnCompletionListener(this);
            mPlayer.setOnErrorListener(this);
        } 
        else 
            mPlayer.reset();
    }