USB type-c headset detection in Android

匿名 (未验证) 提交于 2019-12-03 01:04:01

问题:

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.

  1. 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?

  2. 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

回答1:

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



回答2:

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.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!