Sunday, December 16, 2012

Android beginner tutorial: Part 22 - Handlers

Today we will learn about Handlers and threads in Android SDK.

Handler is a class provided by the Android SDK for creating background processes (threads) and the connection between the process and the user interface. A handler allows you to send and process Messages, which are objects that contain a certain piece of data.

The most simple way to create a background process is to create a Handler instance in an Activity. The background process can interact with Handlers, which update the user interface in the Activity. This way we can track the progress of a process and display it in a visual progress bar, for example.

Before sending a message to a Handler object, we first need to call its obtainMessage() method to receive a Message object.

Handler handler;
Message message = handler.obtainMessage();

We can then send the message using the sendMessage() method:

handler.sendMessage(message);

There are a few methods for adding messages to the message queue of the Handler object.

The sendMessage() method simply sends the provided message to the Handler.

The sendMessageAtFrontOfQueue() methods sends the provided message to the Handler, and puts it at the front of the queue, giving it priority over the rest of the messages in the queue. By default, every new message is added to the end of the queue.

The sendMessageAtTime() method adds the message to the queue at a specific time.

The sendMessageDelayed() method adds the message to the queue after a time delay.

To handle the received messages using a Handler, use its method called handleMessage, which is called out by each message.

Handler handler;
...
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// code here
...
}
}

And that's the basic idea behind handlers. Now we also know a little bit about threads in Android SDK. This knowledge will be of use in the next tutorial, where we will create and handle background threads.

Thanks for reading!

No comments:

Post a Comment