All Things Techie With Huge, Unstructured, Intuitive Leaps

Android Source Code - Turn Off Media Player When You Click Back Button


Android persists activities even when you don't want them unless you explicitly kill them.  Sometimes the media player persists even if you kill the first activity of the app.  If you have an activity that kicks a media player, and you want to turn that media player off from other activities, including hitting the back button, you must do the following:

1) Make the media player into a static class.  The following code should do it:

package com.me.coderzen;

import android.content.Context;
import android.media.MediaPlayer;

public class StaticPlayer {
public static MediaPlayer player;
    public static void SoundPlayer(Context ctx,int raw_id){
            player = MediaPlayer.create(ctx, raw_id);
            player.setLooping(false); 
            player.setVolume(100, 100);
        }

}

On you media player activity you kick the player:

StaticPlayer.SoundPlayer(this, R.raw.sound_file);

Then to kill it from the back button, you override the back button function:

  @Override
   public boolean onKeyDown(int keyCode, KeyEvent event) {
       if (keyCode == KeyEvent.KEYCODE_BACK ) {
      if (StaticPlayer.player != null)
      StaticPlayer.player.stop();
           this.finish();
           
       }
       return super.onKeyDown(keyCode, event);
   }

I know that there is a newer, easier back button override, but this one works in my code.

And if you have a quit button in your menu, just put the stop in for the StaticPlayer before you call the this.finish().

Hope this helps someone.

No comments:

Post a Comment