Android USB Automatically Grant Permission

后端 未结 3 859
孤城傲影
孤城傲影 2020-12-16 08:58

Is there anyway to access the IUsbManager Interface class to call the service.grantDevicePermission() method to automatically set the permission for the USB device without a

3条回答
  •  鱼传尺愫
    2020-12-16 09:23

    Of course yes! you can use this code, worked for me:

    public boolean grantAutomaticPermission(UsbDevice usbDevice)
     {
        try
        {
         Context context=YourActivityOrApplication;
         PackageManager pkgManager=context.getPackageManager();
         ApplicationInfo     appInfo=pkgManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
    
         Class serviceManagerClass=Class.forName("android.os.ServiceManager");
         Method getServiceMethod=serviceManagerClass.getDeclaredMethod("getService",String.class);
         getServiceMethod.setAccessible(true);
         android.os.IBinder binder=(android.os.IBinder)getServiceMethod.invoke(null, Context.USB_SERVICE);
    
         Class iUsbManagerClass=Class.forName("android.hardware.usb.IUsbManager");
         Class stubClass=Class.forName("android.hardware.usb.IUsbManager$Stub");
         Method asInterfaceMethod=stubClass.getDeclaredMethod("asInterface", android.os.IBinder.class);
         asInterfaceMethod.setAccessible(true);
         Object iUsbManager=asInterfaceMethod.invoke(null, binder);
    
    
         System.out.println("UID : " + appInfo.uid + " " + appInfo.processName + " " + appInfo.permission);
         final Method grantDevicePermissionMethod = iUsbManagerClass.getDeclaredMethod("grantDevicePermission", UsbDevice.class,int.class);
         grantDevicePermissionMethod.setAccessible(true);
         grantDevicePermissionMethod.invoke(iUsbManager, usbDevice,appInfo.uid);
    
    
         System.out.println("Method OK : " + binder + "  " + iUsbManager);
         return true;
        }
        catch(Exception e)
        {
         System.err.println("Error trying to assing automatic usb permission : ");
         e.printStackTrace();
         return false;
        }
     }
    

    What i did is implement the way android does this using reflection. In order to use this code you must have the:

    
    

    However there is an issue, i don't known exactly, correct me if i am wrong: The USER holds the permission, not the application, then if you try to start the application from applications dash board you will fail. Is necessary to ensure than android begins your aplication, for example, setting it as launcher and let it start in a HOME intent.

    Greetings, expect can help someone.

提交回复
热议问题