Let's get's dirty with few terms first.
Handler:
A Handler allows communicating back with UI thread from other
background thread. This is useful in android as android doesn’t allow
other threads to communicate directly with UI thread.
In technical terms, it is a way to post Messages or runnable to your associated thread message queue.
so in total there are two task performed by handler
- to schedule messages and runnables to be executed as some point in the future; and
- to enqueue an action to be performed on a different thread than your own.
so how to schedule one
post(Runnable),
postAtTime(Runnable, long),
postDelayed(Runnable, Object, long),
sendEmptyMessage(int),
sendMessage(Message),
sendMessageAtTime(Message, long),
sendMessageDelayed(Message, long).
Looper:
Whatever I mentioned earlier is supported by Looper It has a loop()
method which keeps running and listening for the new messages, main thread has one running all the time so you can receive messages from another thread to this thread, if you are creating your own thread and want to listen then don't forget to call prepare() in the thread that is to run the loop.
A simple example
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
so now to answer your questions:
1: Things(Threads and so Looper and Handler) keep running until it gets finished by the user or killed by the system.
2: A looper has a loop() method that will process each message in the queue, and block when the queue is empty.
3: In case of updating the UI from background thread make sure app is in the foreground or terminate the background thread in onDestroy() you can quit the looper processing messages using handler.getLooper().quitSafely()
or handler.looper.quit()
if the handler is attached to the main thread.
It's recommended in case of orientation change or other configuration changes make sure to terminate the background thread.