Skip to content

Panic in jni-unils future impl when connect run with tauri/flutter #417

@XavierIsabel

Description

@XavierIsabel

Describe the bug
I am building a flutter app connected to a Rust backend using btleplug. I am now able to scan, but rust panics when I try to connect to the ble device I want to connect to. This is the error:

I/flutter (29654): panicked at C:\Users\xavie.cargo\registry\src\index.crates.io-6f17d22bba15001f\jni-utils-0.1.1\rust\future.rs:42:98:
I/flutter (29654): called Option::unwrap() on a None value

Expected behavior
Connect simply

Actual behavior
A similar problem occured for in #395 but the answer was never given. This is my rust code to interface ble with android. Excuses in advance for my rust, I am learning at the same time. I can give more info if needed.

#[cfg(target_os = "android")]
use std::sync::Once;
#[cfg(target_os = "android")]
use once_cell::sync::OnceCell;

#[cfg(target_os = "android")]
pub static JAVA_VM: OnceCell<JavaVM> = OnceCell::new();

#[cfg(target_os = "android")]
use jni::{JNIEnv, JavaVM};
#[cfg(target_os = "android")]
use jni::objects::{JClass, GlobalRef};
#[cfg(target_os = "android")]
use jni::errors::Error;

#[cfg(target_os = "android")]
static INIT: Once = Once::new();

#[cfg(target_os = "android")]
#[no_mangle]
pub extern "system" fn Java_com_example_sifi_1gui_RustLibBLE_initializeJavaVM(env: JNIEnv, _: JClass) {
    let java_vm = env.get_java_vm().expect("Failed to get JavaVM");

    JAVA_VM.set(java_vm);

    INIT.call_once(|| {
        btleplug::platform::init(&env);
    });
}

#[cfg(target_os = "android")]
fn get_java_vm() -> &'static JavaVM {
    JAVA_VM.get().expect("JavaVM is not initialized")
}

#[cfg(target_os = "android")]
pub fn attach_thread_to_jvm() -> Result<JNIEnv<'static>, Error> {
    let java_vm = get_java_vm();
    java_vm.attach_current_thread_as_daemon()
}

#[cfg(target_os = "android")]
pub fn detach_thread_from_jvm() {
    let java_vm = get_java_vm();
    java_vm.detach_current_thread();
}

#[cfg(target_os = "android")]
pub fn setup_class_loader(env: &JNIEnv) -> Result<GlobalRef, Error> {
    let thread = env
        .call_static_method(
            "java/lang/Thread",
            "currentThread",
            "()Ljava/lang/Thread;",
            &[],
        )?
        .l()?;
    let class_loader = env
        .call_method(
            thread,
            "getContextClassLoader",
            "()Ljava/lang/ClassLoader;",
            &[],
        )?
        .l()?;

    Ok(env.new_global_ref(class_loader)?)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions