Skip to content

Example showing how to request for permissions #19

Closed as not planned
Closed as not planned
@charleschege

Description

@charleschege

Is there an example showing how to request for example STORAGE permissions using jni and ndk-context like:

let ctx = ndk_context::android_context();
    let vm = unsafe { jni::JavaVM::from_raw(ctx.vm().cast()) }.unwrap();
    let context = unsafe { JObject::from_raw(ctx.context().cast()) };
    let env = vm.attach_current_thread().unwrap();

    // Query the global Audio Service
    let class_ctx = env.find_class("android/content/Context").unwrap();
    let storage_service = env
        .get_static_field(class_ctx, "AUDIO_SERVICE", "Ljava/lang/String;")
        .unwrap();

    let storage_manager = env
        .call_method(
            context,
            "getSystemService",
            "(Ljava/lang/String;)Ljava/lang/Object;",
            &[storage_service],
        )
        .unwrap()
        .l()
        .unwrap();

    // Request storage permission
    let permission_read = env
        .new_string("android.permission.READ_EXTERNAL_STORAGE")
        .unwrap();
    let permission_write = env
        .new_string("android.permission.WRITE_EXTERNAL_STORAGE")
        .unwrap();

env.call_method(
        storage_manager,
        "requestPermissions",
        "([Ljava/lang/String;I)V",
        &[
            permission_read.into(),
            JValue::from(permission_request_code),
        ],
    )
    .unwrap();

With the strict Rust types enforced it can be difficult to know exactly what to do and where the errors occured like the example above results in error:

02-20 12:35:17.831 15654 15693 I RustStdoutStderr: thread '<unnamed>' panicked at 'called `Result::unwrap()` on an `Err` value: JavaException', src/lib.rs:66:6
02-20 12:35:17.831 15654 15693 I RustStdoutStderr: note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Which doesn't say much.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions