Android handler, perform post() not in the ui thread Android handler, perform post() not in the ui thread multithreading multithreading

Android handler, perform post() not in the ui thread


Handler#post() posts Messages and Runnables on Looper threads. The default constructor of a Handler will bind itself to the Looper thread that it was created on. If it's not on a Looper thread, then it'll throw an exception. So, to use a Handler on a worker thread, you must first create a thread and loop it with a Looper. Then you pass the given Looper to the Handler's constructor.

Fortunately, there's already a utility class that does most of the work for you. It's called HandlerThread. Just create a HandlerThread, and call getLooper whenever you need the Looper for the thread.

EDIT: Default Handler constructor does not choose the main thread. It chooses the current thread if it's a Looper thread already.