问题描述
很抱歉.这是我第一次来我在网上做了一些搜索,但没有结果.确实需要帮助来澄清此问题.我有两个关于USB耳机检测和状态查询的问题.
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.
-
我的目标设备正在运行Android版本7.1.1.该设备具有USB C型接口,并支持USB C型耳机.但是,当USB耳机状态更改时,AudioService似乎不会发送意图. OEM是否必须针对这种情况实施自己的意图?
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?
对于传统的有线耳机,我可以使用AudioManager.isWiredHeadsetOn()来检查其状态.但是USB Type-C耳机似乎无法以这种方式工作.还有其他方法可以获取USB耳机的状态吗?
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?
谢谢,雷
推荐答案
除了EscapeArtist建议的方法外,您还可以收听UsbManager.ACTION_USB_DEVICE_ATTACHED
和UsbManager.ACTION_USB_DEVICE_DETACHED
动作,并检查当前连接的USB设备是否具有音频接口.不幸的是,AudioManager.ACTION_HEADSET_PLUG
不会为复合(不费吹灰之力)USB设备触发,例如OTG +标准USB耳机,或者只是USB-C耳机.
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
}
}
}
}
用于搜索USB设备的
UsbDevice
扩展功能具有音频专用音频接口.
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
}
听取分离设备不是强制性的,因为您可以依靠ACTION_AUDIO_BECOMING_NOISY
.
Listening for detaching devices is not mandatory, since you can rely on ACTION_AUDIO_BECOMING_NOISY
.
这篇关于Android中的USB Type-C耳机检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!