Search code examples
androidmedia-player

media player should stop on disconnecting headphone in my android app programatically


I have an issue in developing a media player application.
I want it so that when I remove my headphone from my device then the MediaPlayer in my app pauses.


Solution

  • The Android documentation suggests using the AUDIO_BECOMING_NOISY intent filter

    Set the intent filter in your manafest and then:

    public class MusicIntentReceiver extends android.content.BroadcastReceiver {
       @Override 
       public void onReceive(Context ctx, Intent intent) {
          if (intent.getAction().equals(
                        android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
              // signal your service to stop playback 
              // (via an Intent, for instance) 
          } 
       } 
    } 
    

    Info: http://developer.android.com/guide/topics/media/mediaplayer.html#noisyintent