USB device connectivity not working after 6.0 (Marshmallow)

In my Android project I'm trying to communicate a tablet with an Arduino device through the USB port, and it works for version 5.1 (API 22: Lollipop) but it doesn't for 6.0 (API 23: Marshmallow) because of the changes in permissions implemented in this Android version.

I've set my target SDK version to API 22, but still doesn't work.

In My Activity

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    [...]

    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
                ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    registerReceiver(mUsbReceiver, filter);
    filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);

    UsbAccessory[] accessories = mUsbManager.getAccessoryList();
        UsbAccessory accessory = (accessories == null ? null : accessories[0]);
        if (accessory != null) {
            if (mUsbManager.hasPermission(accessory)) {
                openAccessory(accessory);
            } else {
                synchronized (mUsbReceiver) {
                    if (!mPermissionRequestPending) {
                        mUsbManager.requestPermission(accessory,
                                mPermissionIntent);
                        mPermissionRequestPending = true;
                    }
                }
            }
        }
    }

What's wrong? What I'm missing?

1 answer

  • answered 2018-07-11 10:13 Dmitriy Kholin

    Try to grant permission.

    String permission = android.Manifest.permission.YOUR_PERMISSION;
    
    private static void requestPermission(Activity activity) {
    
        if (hasPermission(permission)) return;
    
        ActivityCompat.requestPermissions(activity, new String[]{permission}, REQUEST_CODE);
    }
    
    public static boolean hasPermission() {
        return ContextCompat.checkSelfPermission(SupAndroid.appContext, permission) == PERMISSION_GRANTED;
    }
    

    Waiting for callback in onActivityResult of your Activity