이 블로그 검색

Getting Through the Handlers

The most flexible means of making an Android-friendly background thread is to create

an instance of a Handler subclass. You need only one Handler object per activity, and

you do not need to manually register it. Merely creating the instance is sufficient to

register it with the Android threading subsystem.

Your background thread can communicate with the Handler, which will do all of its work

on the activity’s UI thread. This is important, as UI changes, such as updating widgets,

should occur only on the activity’s UI thread.

You have two options for communicating with the Handler: messages and Runnable

objects.

Messages

To send a Message to a Handler, first invoke obtainMessage() to get the Message object

out of the pool. There are a few flavors of obtainMessage(), allowing you to create empty

Message objects or ones populated with message identifiers and arguments. The more

complicated your Handler processing needs to be, the more likely it is you will need to

put data into the Message to help the Handler distinguish different events.

Then, you send the Message to the Handler via its message queue, using one of the

sendMessage...() family of methods, such as the following:

sendMessage(): Puts the message on the queue immediately

sendMessageAtFrontOfQueue(): Puts the message on the queue immediately and places it at the front of the message queue (versus the back, which is the default), so your message takes priority over all others

sendMessageAtTime(): Puts the message on the queue at the stated time, expressed in the form of milliseconds based on system uptime (SystemClock.uptimeMillis())

sendMessageDelayed(): Puts the message on the queue after a delay, expressed in milliseconds

sendEmptyMessage(): Sends an empty Message object to the queue, allowing you to skip the obtainMessage() step if you were planning on leaving it empty anyway

To process these messages, your Handler needs to implement handleMessage(), which

will be called with each message that appears on the message queue. There, the

Handler can update the UI as needed. However, it should still do that work quickly, as

other UI work is suspended until the Handler is finished.

For example, let’s create a ProgressBar and update it via a Handler. Here is the layout