-
-
Save timoyuen/c15cdea82267eaeeb8d7 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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