我正在尝试在 Android 应用程序中使用 libusb,它嵌入在 Android 本机模块中并使用 cmake 构建。该代码仅调用 libusb_init 并向活动返回一个字符串,并且系统性地失败并显示 LIBUSB_ERROR_OTHER。
问题是当它从一个小的命令行程序启动时,我可以让它工作,只做我们用 adb shell 启动的 libusb_init。在这种情况下,它返回成功。
该设备(三星 Galaxy Tab E)运行 Android 7 并已植根,使用 Magisk Manager 我授予我的应用 root 权限,但这不像在命令行中执行“su”。
我主要尝试使用版本 20 和 22(我们在其他项目中主要使用版本 20)。
我已经尝试了许多 stackoverflow 解决方案和解决方法,但它们要么无效要么无法实施(例如,由于 rom 限制)。
这是我如何调用 libusb.c :
#include <jni.h>
#include <string>
extern "C" {
#include "libusb.h"
}
using namespace std;
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_myapplication_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
string hello = "Hello from C++";
libusb_context **lusb;
int rc = libusb_init(lusb);
return env->NewStringUTF(hello.c_str());
}
这是我从 Activity 调用此代码的方式:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
//The purpose of this is to ask for root access, handled with
//Magisk Manager in my case
Runtime.getRuntime().exec("su")
fab.setOnClickListener { view ->
Snackbar.make(view, "Result = ${stringFromJNI()}", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
external fun stringFromJNI(): String
companion object {
// Used to load the 'native-lib' library on application startup.
init {
System.loadLibrary("native-lib")
}
}
我在命令行中运行的小程序(无论我是否是 root 都可以使用):
#include <iostream>
extern "C" {
#include "libusb.h"
}
using namespace std;
int main (int argc, char* argv[]) {
libusb_context *lusb;
int rc = libusb_init(&lusb);
if ( rc != LIBUSB_SUCCESS ) {
cout << "Failed to open api. Error: " << libusb_error_name(rc) << endl;
return 1;
}
cout << "This worked" << endl;
return 0;
}