一、先大致了解下Android里关于USB的API,下图很清晰的表示了Android里面USB的树状(图随便画的表介意)
Paste_Image.png另外还有一个常量<code>UsbConstant</code>定义了跟Linux内核中linux/usb/ch9.h文件定义对应的USB常量
二、获取USB设备步骤
①类似树状图,首先你需要获取UsbManager<code>UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);</code>
②注册广播,当USB插入或者拔出的时候会有广播通知,还要开启一个
<code>ACTION_USB_PERMISSION</code>的PendingIntent意图:
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
registerReceiver(mUsbReceiver, filter);
广播:
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e( "action", action);
if (ACTION_USB_PERMISSION.equals(action)) {
Toast.makeText(MainActivity.this,"获取到权 限",Toast.LENGTH_SHORT).show();
}else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
askforpermission();
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
}
} };
③一般情况下我们会对设备进行过滤,只会获取自己想要的设备,获取的方式可以通过过滤UsbDevice实现,主要是通过设备的VendorId以及ProductId进行识别,之后对对应的设备进行权限的申请:
HashMap<String, UsbDevice> map = usbManager.getDeviceList();
Log.i("usb", "devicesize:"+String.valueOf(map.size()));
for(UsbDevice device : map.values()){
Log.e("device", "vid:"+device.getVendorId()+" pid:"+device.getProductId()+" "+device.getDeviceName());
if(30021 == device.getVendorId() && 1183 == device.getProductId()){
usbDevice = device;
}
}
if (usbDevice!=null) {
if(usbManager.hasPermission(usbDevice))
{
Toast.makeText(MainActivity.this,"已经获取到权限",Toast.LENGTH_SHORT).show();
}else{
usbManager.requestPermission(usbDevice, pendingIntent);
}
}
} catch (Exception e) {
}
}
网友评论