问题
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