在Android上使用libusb而无需Root权限

11
我正在尝试通过OTG从基于Android的智能手机与USB设备通信。我已经能够使用Android USB Host API与我的设备进行通信。但是,使用USB主机API解决方案存在性能问题(单个大块传输受到16384字节的限制)。 libusb可以执行更大的请求,现在我正尝试使用Android NDK集成它。我成功地为Android编译了libusb源代码,甚至有了initUSB(),但libusb_open(dev, &dev_handle)会返回-3(访问被拒绝)。
如何传递文件描述符?
int fd = connection.getFileDescriptor()

在Android USB Host API下获取USB_PERMISSION后,如何在libusb中获取USB设备访问权限?

尝试使用这个 libusb 分支 https://github.com/martinmarinov/rtl_tcp_andro-/tree/master/jni/libusb-andro。它有 open2(, int fd) 函数来做这件事。 - 4ntoine
投票以获得来自Android团队的良好解释:https://code.google.com/p/android/issues/detail?id=56450 - 4ntoine
2个回答

5
这就是您正在寻找的内容。
https://github.com/kuldeepdhaka/libusb/tree/android-open2
只需编译并将其放置其中即可 :)
请查看“Android使用说明”部分以获取完整的用法说明。
我对libusb进行了所有必要的修改(而且我也在使用它)。
它还针对“Android 5.0+”进行了SELinux修复。

1
听起来很有前途,我已经看了你的Github项目,但我仍然不确定如何使用它。你是在使用JNI从Java代码中调用libusb吗? - dweebo
@dweebo 是的,Java -> JNI -> libusb。 - Kuldeep Dhaka
1
@dweebo,所有东西都在这里 https://gitlab.com/madresistor。联系我(Freenode上的#madresistor下的Kuldeep)或发邮件给我(kuldeepdhaka9@gmail.com),我可以向您详细解释它。 - Kuldeep Dhaka
这个 GitHub 与主 GitHub(https://github.com/libusb/libusb)有何不同? - Alexandre Willame
我在你的 Github 名下搜索了一下,但没有找到。不久前,我打开了 https://github.com/libusb/libusb/issues/862 。 - fuzzyTew
显示剩余2条评论

3
请参考https://github.com/libusb/libusb/wiki/Android,其中现在已经讨论了一些关于安卓的内容。以下是来自建议的自述文件更改(2021年2月)的引用:
Runtime Permissions:
--------------------

The Runtime Permissions on Android can be transfered from Java to Native over the following approach:
 Java:
  // obtaining the Usb Permissions over the android.hardware.usb.UsbManager class
  usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
  HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
  for (UsbDevice usbDevice : deviceList.values()) {   usbManager.requestPermission(usbDevice, mPermissionIntent); }
  // get the native FileDescriptor of the UsbDevice and transfer it to Native over JNI or JNA
  UsbDeviceConnection usbDeviceConnection = usbManager.openDevice(camDevice);
  int fileDescriptor = usbDeviceConnection.getFileDescriptor();
  // JNA sample method: 
  JNA.INSTANCE.set_the_native_Descriptor(fileDescriptor);  
 Native:
  // Initialize LibUsb on Android
  set_the_native_Descriptor(int fileDescriptor) {
   libusb_context *ctx;
   libusb_device_handle *devh;
   libusb_set_option(&ctx, LIBUSB_OPTION_WEAK_AUTHORITY, NULL);        // important for Android
   libusb_init(&ctx);
   libusb_wrap_sys_device(NULL, (intptr_t)fileDescriptor, &devh);

   //  From this point you can regulary use all LibUsb functions as usual.
  }

参见 https://github.com/libusb/libusb/pull/874,该修改使得非root用户的使用更加顺畅。如果需要,请更新维基百科上的相关信息。如果您有能力,请贡献您的力量来改善事物。 - fuzzyTew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接