Last active
February 2, 2018 13:37
-
-
Save ognian-/9c29c85e57a2e6478193629dd0a1d295 to your computer and use it in GitHub Desktop.
Looper pool
This file contains 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
public class LooperPool { | |
private final ArrayList<Handler> mIdleHandlers = new ArrayList<Handler>(); | |
public void addTask(final Runnable task) { | |
Handler handler = null; | |
synchronized (mIdleHandlers) { | |
if (!mIdleHandlers.isEmpty()) { | |
handler = mIdleHandlers.remove(mIdleHandlers.size() - 1); | |
} | |
} | |
if (handler != null) { | |
handler.post(task); | |
} else { | |
new Thread() { | |
@Override | |
public void run() { | |
Looper.prepare(); | |
final Handler newHandler = new Handler(); | |
Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() { | |
@Override | |
public boolean queueIdle() { | |
synchronized (mIdleHandlers) { | |
mIdleHandlers.add(newHandler); | |
} | |
return true; | |
} | |
}); | |
newHandler.post(task); | |
Looper.loop(); | |
} | |
}.start(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment