Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

android - Intent.ACTION_HEADSET_PLUG is received when activity starts

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");
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
         }
     }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...