美文网首页
Android获取USB权限

Android获取USB权限

作者: _WhatsUp_ | 来源:发表于2017-08-18 17:29 被阅读0次

定义BroadcastReceiver

private BroadcastReceiver mUsbPermissionActionReceiver;
private static final String ACTION_USB_PERMISSION = "com.template.USB_PERMISSION";//可自定义
    private static UsbManager mUsbManager;

    //获取USB权限
    private void tryGetUsbPermission(){



        mUsbPermissionActionReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (ACTION_USB_PERMISSION.equals(action)) {
                    context.unregisterReceiver(this);//解注册
                    synchronized (this) {
                        UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            if(null != usbDevice){
                                Log.e(TAG,usbDevice.getDeviceName()+"已获取USB权限");
                            }
                        }
                        else {
                            //user choose NO for your previously popup window asking for grant perssion for this usb device
                            Log.e(TAG,String.valueOf("USB权限已被拒绝,Permission denied for device" + usbDevice));
                        }
                    }

                }
            }
        };



        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);

        if(mUsbPermissionActionReceiver != null) {
            registerReceiver(mUsbPermissionActionReceiver, filter);
        }

        PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

        boolean has_idcard_usb = false;
        for (final UsbDevice usbDevice : mUsbManager.getDeviceList().values()) {

            if(usbDevice.getVendorId() == 1024 && usbDevice.getProductId() == 50010)//身份证设备USB
            {
                has_idcard_usb = true;
                Log.e(TAG,usbDevice.getDeviceName()+"已找到身份证USB");
                if(mUsbManager.hasPermission(usbDevice)){
                    Log.e(TAG,usbDevice.getDeviceName()+"已获取过USB权限");
                }else{
                    Log.e(TAG,usbDevice.getDeviceName()+"请求获取USB权限");
                    mUsbManager.requestPermission(usbDevice, mPermissionIntent);
                }
            }

        }

        if(!has_idcard_usb)
        {
            Log.e(TAG,"未找到身份证USB");
        }

    }

调用

//尝试获取USB权限
tryGetUsbPermission();

相关文章

网友评论

      本文标题:Android获取USB权限

      本文链接:https://www.haomeiwen.com/subject/dtwarxtx.html