-1

How do I detect if the headphone was disconnected while the media is currently playing....Is there a state listener for that?

And how do I detect when the headphone is connected?

TheBido
  • 7
  • 3

1 Answers1

2

According to this link, you can create a BroadcastReceiver that checks for an intent sent when headphones are plugged or unplugged.

broadcastReceiver = new BroadcastReceiver() {
         @Override
         public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
               pluggedState = intent.getIntExtra("state", -1);
               if (pluggedState == 0) {
                  // headset not plugged in
               }
               if (pluggedState == 1) {
                  // headset plugged in
               }
            }
         }
};

Note that Intent.ACTION_HEADSET_PLUG is sent by a sticky broadcast, meaning that as soon as the broadcast receiver is registered (likely when the activity is started), you will receive a value from the last time the intent was updated. See this question for more details.

Bingostew
  • 138
  • 6