沃梦达 / IT编程 / 移动开发 / 正文

Android 获取 usb 权限的两种方法

这篇文章主要介绍了Android 获取 usb 权限的两种方式,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下

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<String, UsbDevice> devices = mUsbManager.getDeviceList();
//   List<UsbDevice> deviceList = new ArrayList<UsbDevice>();
//   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);
  filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
  mContext.registerReceiver(mUsbReceiver, filter);
  mUsbManager.requestPermission(mUSBDevice, pendingIntent); // 该代码执行后,系统弹出一个对话框/等待权限
//以下代码是因为在系统层将弹出框直接修改掉了,可以不用
//  long start = System.currentTimeMillis();
//  while (!mUsbManager.hasPermission(mUSBDevice)) {
//   long current = System.currentTimeMillis();
//   if ((current - start) > 3500) {
//    break;
//   }
//   try {
//    Thread.sleep(50);
//   } catch (InterruptedException e) {
//    e.printStackTrace();
//   }
//  }
// }

2.2 注册广播接受者


private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
  @SuppressLint("NewApi")
  public void onReceive(Context context, Intent intent) {
   String action = intent.getAction();

   if (ACTION_USB_PERMISSION.equals(action)) {
    synchronized (this) {
     mContext.unregisterReceiver(mUsbReceiver);
     UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
     if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
       && currentDevice.equals(device)) {
      //TODO 授权成功,操作USB设备
     }else{
      //用户点击拒绝了
     }
    }
   }
  }
 };

总结

以上所述是小编给大家介绍的Android 获取 usb 权限的两种方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程学习网网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

本文标题为:Android 获取 usb 权限的两种方法