So, the art of registering a broadcast receiver for ACTION_HEADSET_PLUG and actually processing the plug in/out events is well figured out now.
But... my app needs to know early on at onCreate()
whether the headset is plugged in or not (if it isn't, it should simply display a dialog and exit, as this is a headset-only app, not to be used with a speaker).
Yet, everywhere I read, registering the receiver should be done either in onStart() or onResume() -- which leave no chance for onCreate()
to use a flag set by the receiver.
Any idea how to workaround this?
Is there a way to poll the headset jack?
You can use AudioManager's isWiredHeadsetOn() to determine if a headset is plugged in, although note that as per the documentation:
This is not a valid indication that audio playback is actually over the wired headset as audio routing depends on other conditions.
You'll also want to look at the values of isSpeakerphoneOn()
, isBluetoothA2dpOn()
, and isBluetoothScoOn()
to get a better idea of what is currently enabled.