libusb 是一个 C 库,提供对 USB 设备的通用访问。开发人员旨在使用它来促进与 USB 硬件通信的应用程序的生产。 它是可移植的:使用单个跨平台 API,它提供对 Linux、macOS、Windows 等 USB 设备的访问 它是用户模式:应用程序与设备通信不需要特殊权限或提升权限。 它与版本无关:支持从 1.0 到 3.1(最新)的所有 USB 协议版本。
The Android build system will then correctly include libusb in the application package (APK) file, provided ndk-build is invoked before the package is built.
Runtime Permissions: --------------------
The Runtime Permissions on Android can be transferred from Java to Native over the following approach:
JAVA:
--> Obtain USB permissions over the android.hardware.usb.UsbManager class
set_the_native_Descriptor(int fileDescriptor) { libusb_context *ctx; libusb_device_handle *devh; libusb_set_option(&ctx, LIBUSB_OPTION_NO_DEVICE_DISCOVERY, NULL); libusb_init(&ctx); libusb_wrap_sys_device(NULL, (intptr_t)fileDescriptor, &devh); } /* From this point you can regularly use all libusb functions as usual */
About LIBUSB_OPTION_NO_DEVICE_DISCOVERY:
The method libusb_set_option(&ctx, LIBUSB_OPTION_NO_DEVICE_DISCOVERY, NULL) does not affect the ctx. It allows initializing libusb on unrooted Android devices by skipping the device enumeration.
Rooted Devices: ---------------
For rooted devices the code using libusb could be executed as root using the "su" command. An alternative would be to use the "su" command to change the permissions on the appropriate /dev/bus/usb/ files.
Users have reported success in using android.hardware.usb.UsbManager to request permission to use the UsbDevice and then opening the device. The difficulties in this method is that there is no guarantee that it will continue to work in the future Android versions, it requires invoking Java APIs and running code to match each android.hardware.usb.UsbDevice to a libusb_device.
For a rooted device it is possible to install libusb into the system image of a running device:
1. Enable ADB on the device.
2. Connect the device to a machine running ADB.
3. Execute the following commands on the machine running ADB:
# Make the system partition writable adb shell su -c "mount -o remount,rw /system"