Skip to content

Instantly share code, notes, and snippets.

@Petrakeas
Last active April 21, 2022 08:24
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Petrakeas/ce745536d8cbae0f0761 to your computer and use it in GitHub Desktop.
Save Petrakeas/ce745536d8cbae0f0761 to your computer and use it in GitHub Desktop.
Android - Posts a runnable on a handler's thread and waits until it has finished running.
import android.os.Handler;
import android.os.Looper;
/**
* A helper class that provides more ways to post a runnable than {@link android.os.Handler}.
*
* Created by Petros Douvantzis on 19/6/2015.
*/
public class SynchronousHandler {
private static class NotifyRunnable implements Runnable {
private final Runnable mRunnable;
private final Handler mHandler;
private boolean mFinished = false;
public NotifyRunnable(final Handler handler, final Runnable r) {
mRunnable = r;
mHandler = handler;
}
public boolean isFinished() {
return mFinished;
}
@Override
public void run() {
synchronized (mHandler) {
mRunnable.run();
mFinished = true;
mHandler.notifyAll();
}
}
}
/**
* Posts a runnable on a handler's thread and waits until it has finished running.
*
* The handler may be on the same or a different thread than the one calling this method.
*
*/
public static void postAndWait(final Handler handler, final Runnable r) {
if (handler.getLooper() == Looper.myLooper()) {
r.run();
} else {
synchronized (handler) {
NotifyRunnable runnable = new NotifyRunnable(handler, r);
handler.post(runnable);
while (!runnable.isFinished()) {
try {
handler.wait();
} catch (InterruptedException is) {
// ignore
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment