robius_android_env/
lib.rs

1//! Abstractions for Rust access to Android state (native Java objects)
2//! managed by UI toolkits.
3//!
4//! # Usage of this crate
5//! This crate exists for two kinds of downstream users:
6//! 1. The UI toolkit that exposes its key internal states that hold
7//!    the current Android activity being displayed and the Java VM / JNI environment.
8//!    Either the UI toolkit or the app itself should set these states on startup,
9//!    either by using [ndk-context] or by activating a feature for a specific UI toolkit.
10//! 2. The platform feature "middleware" crates that need to access the current activity
11//!    and JNI environment from Rust code in order to interact with the Android platform.
12//!
13//! ## Supported UI toolkits
14//! * [Makepad]: enable the `makepad` Cargo feature.
15//! * UI toolkits compatible with [ndk-context]: supported by default.
16//! * Others coming soon! (in the meantime, see below)
17//!
18//! ## Usage of this crate for other UI toolkits
19//! For any other UI toolkits that support [ndk-context], you don't need to enable any cargo features.
20//! However, either your application code or the UI toolkit must manually initialize the Android context
21//! owned by [ndk-context], i.e., by invoking [`initialize_android_context()`](https://docs.rs/ndk-context/latest/ndk_context/fn.initialize_android_context.html).
22//! Some UI toolkits automatically do this for you, typically via the [ndk-glue] crate.
23//!
24//! [Makepad]: https://github.com/makepad/makepad/
25//! [ndk-context]: https://docs.rs/ndk-context/latest/ndk_context/
26//! [ndk-glue]: https://crates.io/crates/ndk-glue
27
28#[cfg_attr(feature = "makepad", path = "makepad.rs")]
29#[cfg_attr(not(feature = "makepad"), path = "ndk_context.rs")]
30mod inner;
31
32#[cfg(all(not(feature = "makepad"), not(feature = "ndk-context")))]
33compile_error!("Must enable either 'makepad' or 'ndk-context' feature");
34
35// Re-export all types that downstream users might need to instantiate.
36pub use jni::{JavaVM, JNIEnv, objects::JObject, errors::{Result, Error, JniError}};
37
38/// Re-exports of low-level pointer types from the `jni-sys` crate.
39pub mod sys {
40    pub use jni::sys::{jobject, JNIEnv};
41}
42
43/// Invokes the given closure `f` with the current JNI environment
44/// and the current activity.
45///
46/// Returns `None` upon error, including:
47/// * If the function that gets the current activity and JNI environment
48///   has not been set.
49/// * If the current JNI environment cannot be obtained.
50pub fn with_activity<F, R>(f: F) -> Result<R>
51where
52    F: for<'a, 'b, 'c, 'd> FnOnce(&'a mut JNIEnv<'b>, &'c JObject<'d>) -> R,
53{
54    inner::with_activity_inner(f)
55}