For example, there are a lot of tasks are posted to UI thread as follows.
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Some logic to display/update something in UI
}
}, 5000);
What happens to these tasks when the android application went to the background?
Will these tasks be processed even in the background? Will the complete UI thread be suspended in the background? Or? All the tasks posted to UI thread are suspended?
What happens to UI thread when there are no tasks posted to it after the activity is completely loaded? Will it be suspended, if there are no tasks are in the Looper?
Thanks in advance.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With