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

 ̄綄美尐妖づ 提交于 2021-02-04 12:41:05

问题


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.


回答1:


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




回答2:


You can get a ACTION_HEADSET_PLUG Intent over the Broadcast when ever someone Plugs a Headset in or out.

At the start of your App you can use AudioManager.isWiredHeadsetOn() to check if ther is a headset pluged in at the moment. (Dont forgget to add MODIFY_AUDIO_SETTINGS permission.)




回答3:


Register Broadcast in same Activity.

private BroadcastReceiver mNoisyReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if( mMediaPlayer != null && mMediaPlayer.isPlaying() ) {
            mMediaPlayer.pause();
        }
    }
};

Handles headphones coming unplugged. cannot be done through a manifest receiver

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
       IntentFilter filter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
       registerReceiver(mNoisyReceiver, filter);
    }

UnRegister Receiver

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(mNoisyReceiver);
}


来源:https://stackoverflow.com/questions/29032029/media-player-should-stop-on-disconnecting-headphone-in-my-android-app-programati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!