Thursday, 18 November 2010

How to handle handlers?

Flattr this

One of the first problems I encountered with Android, was that it crashed when I tried to interact with UI components from a thread!
I haven't managed to dig into why exactly it was designed this way, but there is only one "UI Thread" per application which is allowed to modify UI components.

So, the question is, what to do when you want to do a long running action in background and let the user know what is going on?

Introducing: Handler

Handler is a component which allows you to create messages from other threads and receive them in the UI thread.
Let's get familiar with it through a common example: ProgressBar

Very straightforward way to use this, is to create an inner class or anonymous instance and override the handleMessage function. However, this is also a quick way to bloat up your activity class and make it unreadable.

So, my way of using it is as so:
1. Create a Handler which get a reference to the bar we want to update:

package net.fizzl.example;

import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;

public class FooHandler extends Handler {
private ProgressBar pbar;
public FooHandler(ProgressBar pbar) {
this.pbar = pbar;

public void handleMessage(Message msg) {
if(msg.what == MSG_PROGRESS) {

// Message Names
public static final int MSG_PROGRESS = 1;

2. Create a Thread that gets a reference to the handler.

package net.fizzl.example;

import android.os.Handler;
import android.os.Message;

public class FooThread extends Thread {
private Handler h;
public FooThread(Handler h) {
this.h = h;

public void run() {
while(dostuff) {
int progress = dostuff();
Message msg = h.obtainMessage(FooHandler.MSG_PROGRESS, progress, 0);

3. Use these in your Activity:

ProgressBar pb = findViewById(;
FooHandler h = new FooHandler(pb);
FooThread t = new FooThread(h);
4. Profit!

That's about it. This ofcourse assumes your actual ProgressBar has been set up beforehand to work with the expectations of the thread that sends messages to it.

What happens here, is like so:
1. Thread starts running. It gets progress from its internal function that "does stuff".
2. Thread asks the Handler to give it a prepared message with 'what' set to the value that indicates that it should update the status bar.
3. Thread sends the message.
4. Handler adds the message to its queue.
5. When Handlers message pump is called in the UI Thread, it finds the message and executes its handleMessage.
6. Now that we are running in UI Thread, we can safely call the ProgressBars setProgress.
UI Thread redraws stuff etc. Thread keeps on running and posting messages.

Anyway, I hope you enjoyed this write up and can make a bit more responsive UI's from now on!

No comments:

Post a Comment