USB权限获取有以下两种方式:
一、直接在AndroidManifest.xml文件中配置
<activity
android:name=".DemoCustomAndroidUSBActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- USB -->
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter" />
<!-- USB END -->
</activity>
需要注意的是:
其中 device_filter.xml 中列出了可用 usb 设备,当usb 设备连接手机之后,app 会自动询问是否允许获取该 usb 的权限。
device_filter.xml 放置位置如下图所示 :
device_filter.xml中的内容为:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<usb-device vendor-id="1027" product-id="24577" />
<usb-device vendor-id="3405" product-id="567" />
</resources>
usb设备通过 vendor-id(厂商 id) 和 product-id (产品 id)一起来定义的,这里有一个 linux 的 usb设备厂商 id 和产品 id 的汇总,可以作为 Android usb 设备的参考。
二、动态代码获取
2.1 代码中获取(前提是已经定位到要申请USB权限的usbdevice)
//获取USB设备ACTION
private static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";
// 获取USB设备列表及定位到要申请权限的USB设备
// mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
// HashMap devices = mUsbManager.getDeviceList();
// List deviceList = new ArrayList();
// for (UsbDevice device : devices.values()) {
// if (3540==device.getVendorId() && 567==device.getProductId()) {//获取打印机设备 vid和pid
// currentDevice=device;
// }
// }
//开始申请USB权限
private void getUsbPermission(UsbDevice mUSBDevice) {
UltraLog.d("开始申请USB权限");
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
}
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
喜欢就支持以下吧
请登录后发表评论
注册
社交帐号登录