广播播放盘usb不识别u盘 (广播播放盘usb不识别u盘)

修改AndroidManifest.xml文件。添加 <uses-feature> 元素来声明您的应用使用 android.hardware.usb.accessory 功能。

<uses-feature android:name="android.hardware.usb.accessory" />

接收 U盘连接通知,需要在Activity 中的 android.hardware.usb.action.USB_ACCESSORY_ATTACHED Intent 指定 <intent-filter> 和 <meta-data> 元素对。<meta-data> 元素指向一个外部 XML 资源文件,该文件声明关于要检测的配件的识别信息。

<intent-filter> <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" /></intent-filter><meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" android:resource="@xml/accessory_filter" 电脑 />

res/xml/accessory_filter.xml文件内容:

<?xml version="1.0" encoding="utf-8"?><resources> <usb-device class="8" protocol="80" subclass="6" /></resources>

获取与U盘通信的权限

private val usbManager by lazy { getSystemService(Context.USB_SERVICE) as UsbManager } private val accessory by lazy { intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY) as UsbAccessory? } private val usbReceiver by lazy { UsbReceiver() }

val filter = IntentFilter(ACTION_USB_PERMISSION) filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED) filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED) registerReceiver(usbReceiver, filter) val usbDevice = intent.getParcelableExtra<Parcelable>(UsbManager.EXTRA_DEVICE) as UsbDevice? if (usbDevice != null && usbManager.hasPermission(usbDevice)) { 电脑 //在这种情况下,不需要请求许可 电脑 } else { // 首先向用户请求与底层USB设备通信的权限 val permissionIntent = PendingIntent.getBroadcast( this, 0, Intent( ACTION_USB_PERMISSION ), 0 ) usbManager.requestPermission( accessory, permissionIntent ) }

class UsbReceiver : BroadcastReceiver() { companion object { const val ACTION_USB_PERMISSION = "com.jiaohongyun.sharedu.USB_PERMISSION" } override fun onReceive(context: Context, intent: Intent) { if (ACTION_USB_PERMISSION == intent.action) { synchronized(this) { val accessory: UsbAccessory? = intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY) if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { //同意了 电脑 accessory?.apply { } } else { //拒绝了 } } }电脑 }}
电脑 电脑