private class MusicIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) { int state = intent.getIntExtra("state", -1); switch (state) { case 0: Log.d(TAG, "Headset is unplugged"); break; case 1: Log.d(TAG, "Headset is plugged"); break; default: Log.d(TAG, "I have no idea what the headset state is"); } } } 

}

 IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG); registerReceiver(myReceiver, filter); 

With this design, I track the connection disconnecting headphones. With connection problems in it, the state comes in 1. The problem is that I only need to catch the headset disconnection event itself, and the state comes 0 from time to time when the headphones are not connected.

    1 answer 1

    For example, you can when connecting, state = 1 set the flag that the headphones are connected and when state = 0 comes in to see if the headphones are connected at the moment:

     boolean isHSConnected = false; ... switch (state) { case 0: if(isHSConnected) { // Log.d(TAG, "Headset is unplugged"); isHSConnected = false; } break; case 1: Log.d(TAG, "Headset is plugged"); isHSConnected = true; break;