I've found several similar examples of headset state detection all using a switch to determine the state of the ACTION_HEADSET_PLUG broadcast. I'm using this code in a service to trigger some other code when a headset is plugged in.
The following example does indeed detect the correct headset state but for some reason seems to run twice..ie. when I plug the headset in I get two "Headset is plugged" log messages in a row and another two "Headset was unplugged" when I unplug. Any code I drop in the switch statement also gets called twice. I don't understand why this is so. How can change this so my code is only called once?
public class HeadsetObserverService extends Service {
private static final String TAG = "HeadsetObserverService";
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Create a filter. We are interested in the Intent.ACTION_HEADSET_PLUG action
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_HEADSET_PLUG);
// Register a new HeadsetReceiver
registerReceiver(new HeadsetReceiver(), filter);
// We return START_STICKY. If our service gets destroyed, Android will try to restart it when resources are available.
return START_STICKY;
}
private class HeadsetReceiver 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("unplugged", "Headset was unplugged");
// Cancel notification here
break;
case 1:
Log.d("plugged", "Headset is plugged");
// Show notification
break;
default:
Log.w("uh", "I have no idea what the headset state is");
}
}
}
}
}