Sorry for question. It's my first time here. I did some search on net but no result. Really need help to clarify this problem. I have two question about USB headset detection and status query.
My target device is running Android version 7.1.1. The device has a USB type-c connector and support USB type-c headset. However it seems AudioService will not send intent when USB headset status changed. Does OEM have to implement his own intent for this case?
For traditional wire headset, I can use AudioManager.isWiredHeadsetOn() to check it's status. But USB type-c headset seems not work in this way. Is there any other way to get the status of USB headset?
Thanks, Lei
As addition to EscapeArtist proposed approach, you can also listen for UsbManager.ACTION_USB_DEVICE_ATTACHED
and UsbManager.ACTION_USB_DEVICE_DETACHED
actions and check wither the current connected USB device has audio interface UsbConstants.USB_CLASS_AUDIO
. Unfortunately, AudioManager.ACTION_HEADSET_PLUG
is not triggered for composite (don't sweat the wording) USB devices, such as OTG + standard USB headphones, or just USB-C headphones.
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == UsbManager.ACTION_USB_DEVICE_ATTACHED) {
context.usbManager.deviceList.values.indexOfFirst {
it.hasUsbAudioInterfaceClass()
}.takeIf { it > -1 }?.run {
//This attached USB device has audio interface
}
} else if (intent.action == UsbManager.ACTION_USB_DEVICE_DETACHED) {
val device: UsbDevice? = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
device?.apply {
if (hasUsbAudioInterfaceClass()) {
//This detached USB device has audio interface
}
}
}
}
UsbDevice
extension function that searches wither USB device has audio dedicated audio interface.
fun UsbDevice.hasUsbAudioInterfaceClass(): Boolean {
for (i in 0 until interfaceCount) {
if (getInterface(i).interfaceClass == UsbConstants.USB_CLASS_AUDIO) {
return true
}
}
return false
}
Listening for detaching devices is not mandatory, since you can rely on ACTION_AUDIO_BECOMING_NOISY
.
You can register a BroadcastReceiver
with a filter for AudioManager.ACTION_HEADSET_PLUG
Then in your receiver you can get a list of connected devices with
devices = audioManager.getDevices(GET_DEVICES_OUTPUTS)
Then you can filter that list by looking for USB headset by checking the type:
device.type == AudioDeviceInfo.TYPE_USB_HEADSET
You might want to also look at TYPE_WIRED_HEADPHONE, TYPE_WIRED_HEADSET, TYPE_LINE_ANALOG
来源:https://stackoverflow.com/questions/41583448/usb-type-c-headset-detection-in-android