dart-lang / dart-lang/native

Possibility of using `Looper.loop()` from the Dart thread?

Open
#1,449 7 comments 1 reaction 0 assignees View on GitHub
package:jni package:jnigen
Dominant language
Dart
Stars
275
Forks
144
Avg merge
2d 10h
Merged PRs (30d)
47

Description

Hi!

I'm currently trying out `jnigen` to set up a video player. I decided to use the latest `media3.ExoPlayer` as the player, and was able to generate all of the bindings in Dart, which is awesome.

However, when playing around with `ExoPlayer` I ran into threading issues:

```dart
_player = ExoPlayer_Builder(context).build();
_player.play(); // <- Throws an exception saying that the access happened in a wrong thread
```

I was able to get around this by setting the looper for `ExoPlayer_Builder` to the looper of the Dart's thread (and preparing it beforehand):

```dart
Looper.prepare();

_player = ExoPlayer_Builder(context).setLooper(Looper.myLooper()).build();
_player.play(); // <- All good now
```

However, when adding callback listeners to the player, no callbacks actually go through. This is because the `Looper.loop()` was not called anywhere.

I can't call `.loop()` from any of the methods that can be accessed from the UI, as it would hang the thread. I tried calling it as:

```dart
Looper.prepare();

Future.delayed(Duration.zero, () async {
Looper.loop();
});
```

This does work - all callbacks are sent through, but causes the app to crash when hot-restarting, because of an assertion when calling `Dart_EnterIsolate`.

I also tried calling the `.loop()` method from a different Isolate, but that didn't work, because the other Isolate has a different thread.

Attaching the player to the main looper does work, but the problem there is that I have to wrap all of my calls with `ui.runOnPlatformThread()`, and that the closure there seems to overcapture the context, so it's extremely unwieldy to use :(

Not sure how I can get the looper to work. I'm probably doing something stupid because I'm not very well-versed with JNI or the Android platform in general. Any help or ideas would be appreciated

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.