Skip to content

Expose main thread's looper for runOnUiThread compatibility#198

Merged
rib merged 1 commit intorust-mobile:mainfrom
markkimsal:expose-main-looper
Mar 12, 2026
Merged

Expose main thread's looper for runOnUiThread compatibility#198
rib merged 1 commit intorust-mobile:mainfrom
markkimsal:expose-main-looper

Conversation

@markkimsal
Copy link
Contributor

Posting to the UI thread is only possible via the looper obtained from the main activity thread. android-activity creates the AndroidApp inside a worker thread and there is no way to access the main thread's looper. Even interacting with the UI will send events into the AndroidAppInner looper and execute code in the worker thread.

This PR simply records a pointer to the thread's looper before spawning the worker thread and makes it available in a similar fashion to the existing looper.

Related discussion:
#197

@markkimsal markkimsal force-pushed the expose-main-looper branch 2 times, most recently from 53b965f to edf5f87 Compare May 7, 2025 17:25
This makes it possible to register file descriptors that can wake up the
Java main / UI thread as well as callbacks that will run on the Java
main / UI thread.

Although it can be common to refer to this thread as the "main" thread,
we choose to explicitly refer to it as the "java main" thread thread in
the API to avoid confusion with the Rust thread that runs
"android_main".

Co-authored-by: Robert Bragg <robert@sixbynine.org>
@rib rib force-pushed the expose-main-looper branch from edf5f87 to 22ffc11 Compare March 12, 2026 20:39
@rib
Copy link
Member

rib commented Mar 12, 2026

Hi, sorry for taking a long time to look at this.

Thanks, the idea seems good to me.

I've rebased this and added corresponding support to the game-activity backend.

I've updated the implementation to expose ndk::looper::ForeignLooper instead of raw ALooper pointers to avoid any ambiguity with needing to retain/release ALooper references (and you can still use .ptr() if you want the underlying ALooper API.

The other change I made was to refer to this as the "java main" Looper and not just the "main looper" to avoid confusion with the thread/Looper that's associated with android_main.

Based on this work, I have also experimented with building a more ergonomic AndroidApp::run_on_java_main_thread API that can be used to run boxed closures on the java main / ui thread and I'm planning to open a follow PR for that soon.

@rib rib merged commit 2a05cd2 into rust-mobile:main Mar 12, 2026
3 checks passed
@rib
Copy link
Member

rib commented Mar 13, 2026

For reference here, this is the follow up PR that adds a run_on_java_main_thread API: #232

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants