I am trying to pause music that is playing when the headset is unplugged.
I have created a BroadcastReceiver that listens for ACTION_HEADSET_PLUG intents and acts upon them when the state extra is 0 (for unplugged). My problem is that an ACTION_HEADSET_PLUG intent is received by my BroadcastReceiver whenever the activity is started. This is not the behavior that I would expect. I would expect the Intent to be fired only when the headset is plugged in or unplugged.
Is there a reason that the ACTION_HEADSET_PLUG Intent is caught immediately after registering a receiver with that IntentFilter? Is there a clear way that I can work with this issue?
I would assume that since the default music player implements similar functionality when the headset is unplugged that it would be possible.
What am I missing?
This is the registration code
registerReceiver(new HeadsetConnectionReceiver(),
new IntentFilter(Intent.ACTION_HEADSET_PLUG));
This is the definition of HeadsetConnectionReceiver
public class HeadsetConnectionReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.w(TAG, "ACTION_HEADSET_PLUG Intent received");
}
}
I use a different approach to stop playback when headset is unplug. I do not want you to use it since you are already fine, but some other people may find it useful. If you get control of audio focus, then Android will send you an event audio becoming noisy, so if you write a receiver for this event it will look like
public void onReceive(Context context, Intent intent) {
if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) {
if (isPlaying()){
stopStreaming();
}
}
}
Thanks for the reply Jake. I should have updated the original post to indicate that I discovered the issue that I was having. After a bit of research, I discovered that the ACTION_HEADSET_PLUG Intent is broadcast using the sendStickyBroadcast method in Context.
Sticky Intents are held by the system after being broadcast. That Intent will be caught whenever a new BroadcastReceiver is registered to receive it. It is triggered immediately after registration containing the last updated value. In the case of the headset, this is useful to be able to determine that the headset is already plugged in when you first register your receiver.
This is the code that I used to receive the ACTION_HEADSET_PLUG Intent:
private boolean headsetConnected = false;
public void onReceive(Context context, Intent intent) {
if (intent.hasExtra("state")){
if (headsetConnected && intent.getIntExtra("state", 0) == 0){
headsetConnected = false;
if (isPlaying()){
stopStreaming();
}
} else if (!headsetConnected && intent.getIntExtra("state", 0) == 1){
headsetConnected = true;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With