如何使用c++api获取flatter中的蓝牙设备列表

9gm1akwq  于 2021-07-12  发布在  Java
关注(0)|答案(0)|浏览(314)

我需要开发一个Flutter应用程序,显示蓝牙设备列表。但这是通过c实现的。为此,我编写了这样的c代码。

extern "C" char * GetBluetoothDevices()
{
    JavaVM *jvm; 
    JNIEnv *env;  
    JavaVMInitArgs vm_args;                        // Initialization arguments
    JavaVMOption* options = new JavaVMOption[1];   // JVM invocation options
    options[0].optionString = "-Djava.class.path=.";   // where to find java .class
    vm_args.version = JNI_VERSION_1_6;             // minimum Java version
    vm_args.nOptions = 1;                          // number of options
    vm_args.options = options;
    vm_args.ignoreUnrecognized = false;     // invalid options make the JVM init fail
    //=============== load and initialize Java VM and JNI interface =============
    jint rc = JNI_CreateJavaVM(&jvm, reinterpret_cast<JNIEnv**>((void**) &env), &vm_args);  // YES !!
    delete options;    // we then no longer need the initialisation options.
    if (rc != JNI_OK) {
        // TO DO: error processing...
        exit(EXIT_FAILURE);
    }
    //=============== Display JVM version =======================================
    jint ver = env->GetVersion();

    // TO DO: add the code that will use JVM <============  (see next steps)

    char btDevices[] = "";
    jclass cls2 = env->FindClass("com/example/bluetooth2/MainActivity");  // try to find the class
    if (cls2 == nullptr) {
        return "";
    }
    else {                                  // if class found, continue
        jmethodID mid = env->GetStaticMethodID(cls2, "SearchBTDevices", "()Ljava/lang/String;");  // find method
        if (mid == nullptr)
            return "";
        else {
            jstring returnString = (jstring)env->CallStaticObjectMethod(cls2, mid);                      // call method
            const char *js = env->GetStringUTFChars(returnString, NULL);
            strcpy(btDevices, js);
            env->ReleaseStringUTFChars(returnString, js);
        }
    }

    jvm->DestroyJavaVM();

    return btDevices;
}

我在mainactivity.java文件中编写了这样的java代码,以获得android中的蓝牙设备。

public class MainActivity extends AppCompatActivity {

    public static String SearchBTDevices() {
        System.out.println("Hello, World in java from SearchBTDevices");
        BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
        BA.startDiscovery();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

        Set<BluetoothDevice>pairedDevices = BA.getBondedDevices();
        String btDevices = "";

        for(BluetoothDevice bt : pairedDevices) {
            btDevices += bt.getName() + "-" + bt.getAddress() + ";";
        }

        return btDevices;

    }

}

使用dart::ffi包,我正在调用capi getbluetoothdevices。
我知道在运行android应用程序时,我们不应该用c
创建jvm。
我的问题是如何从dart/flatter获取jnienv对象并将其传递给c++api?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题