USB interface in android

前端 未结 5 1818
天命终不由人
天命终不由人 2021-02-06 10:02

I rooted my device and working in host mode. I can able to detect the usb device connected to my tab but Am having two questions.

1) i try to display my device name usi

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-06 10:41

    Just a minor note on the above code, which in principle works just fine. Requesting the user permission to access the USB device is an asynchronous call. So the code should not proceed for that particular device if it does not (yet) have permissions.

    Please allow me to make a small update to the onClick and onReceive methods:

        Button btnDiscover = (Button) findViewById(R.id.buttonDiscover);
        btnDiscover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                txtInfo.setText("");
                HashMap deviceList = manager.getDeviceList();
                for (UsbDevice device : deviceList.values()) {
                    Log.i("discover", "Model    :" + device.getDeviceName());
                    if (!manager.hasPermission(device)) {
                        Log.i("discover", "No permission to access, so requesting it now from user (async)");
                        manager.requestPermission(device, mPermissionIntent);
                    } else {
                        showUsbDetails(device);
                    }
                }
            }
        });
    
    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (MainActivity.ACTION_USB_PERMISSION.equals(action)) {
                Log.i("BroadcastReceiver", "onReceive: ACTION_USB_PERMISSION");
                synchronized (this) {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if(device != null){
                            showUsbDetails(device);
                        }
                    }
                    else {
                        txtInfo.append("permission denied for device " + device);
                    }
                }
    

    Needless to say that showUsbDetails now contains the part from the original code that does the communication with the USB device to query for the manufacturer and other strings.

提交回复
热议问题