A simple Java Looper implementation / example. Only depends on SLF4J for a logging facade.
#> mvn verify
Quickest way is by using JitPack (Also see for instructions on gradle usage)
Add JitPack repository
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Add dependency
<dependency>
<groupId>com.github.ivovandongen</groupId>
<artifactId>jloop</artifactId>
<version>master</version>
</dependency>
A main looper can be created once and can be accessed statically from any other thread for usage after. For a more complete reference see the Unit Test
On the main thread:
Looper looper = Looper.prepareMainLooper();
looper.run() // Will block indefinitely
On any other thread:
Looper.prepareMainLooper().post(() -> {
// Do what must be done on the main thread
});
Other methods available are Looper#postDelayed
and Looper#ask()
For other use cases, a regular looper can be prepared on a Thread. Reference to this looper must be handed to other threads manually:
Looper looper = Looper.prepare();
looper.run() // Will block indefinitely
A LooperThread
is a convenient way to create a Looper
on a new, separate Thread
. See the
Unit Tests for more details.
LooperThread lp = new LooperThread();
lp.start(); // Will block until backing Looper is ready