mirror of
https://github.com/rust-mobile/android-activity.git
synced 2026-07-04 05:47:26 +00:00
feat: Add waker() method to AndroidAppWaker
This commit adds an "into_waker()" method to AndroidAppWaker. It converts it into an `std::task::Waker`, which is the type of waker used by asynchronous tasks for scheduling. The goal is to allow AndroidAppWaker to be easily used to set up an asynchronous context. The implementation is a straightforward wrapper for `ALooper_acquire/release/wake()`. Signed-off-by: John Nunley <dev@notgull.net> Co-authored-by: Robert Bragg <robert@sixbynine.org>
This commit is contained in:
committed by
Robert Bragg
parent
c3ed6ba77d
commit
37730905d1
@@ -1,4 +1,5 @@
|
||||
use std::ptr::NonNull;
|
||||
use std::task::{RawWaker, RawWakerVTable, Waker};
|
||||
|
||||
#[cfg(doc)]
|
||||
use crate::AndroidApp;
|
||||
@@ -54,4 +55,37 @@ impl AndroidAppWaker {
|
||||
ndk_sys::ALooper_wake(self.looper.as_ptr());
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a [`Waker`] that wakes up the [`AndroidApp`].
|
||||
///
|
||||
/// This is useful for using this crate in `async` environments.
|
||||
///
|
||||
/// [`Waker`]: std::task::Waker
|
||||
pub fn into_waker(self) -> Waker {
|
||||
const VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake, drop);
|
||||
|
||||
unsafe fn clone(data: *const ()) -> RawWaker {
|
||||
ndk_sys::ALooper_acquire(data as *const _ as *mut _);
|
||||
RawWaker::new(data, &VTABLE)
|
||||
}
|
||||
|
||||
unsafe fn wake(data: *const ()) {
|
||||
ndk_sys::ALooper_wake(data as *const _ as *mut _)
|
||||
}
|
||||
|
||||
unsafe fn drop(data: *const ()) {
|
||||
ndk_sys::ALooper_release(data as *const _ as *mut _);
|
||||
}
|
||||
|
||||
// Take the existing reference to the looper and use it for the Waker
|
||||
let looper_ptr = self.looper.as_ptr() as *const ();
|
||||
std::mem::forget(self);
|
||||
unsafe { Waker::from_raw(RawWaker::new(looper_ptr, &VTABLE)) }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AndroidAppWaker> for Waker {
|
||||
fn from(waker: AndroidAppWaker) -> Self {
|
||||
waker.into_waker()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user