Archive

Posts Tagged ‘message handler’

The Message Handler

August 25th, 2009 No comments

(Android phone – how-to/example)

A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it — from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

This is how one will send an empty signaling message from a function to another.
In the main activity declare your handler:

private Handler m_myMsgHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
   switch(msg.what)
   {
   case R.id.message_id1:
   // do the according processing
….

In the caller method, one has just to send the empty message:

m_myMsgHandler.sendEmptyMessage(R.id.message_id1);

Alternatively, one can send a delayed message:

m_myMsgHandler.sendEmptyMessageDelayed(R.id.message_id1, longDelayMilliseconds);

Passing data from one caller method to the message handler is also straight-forward:

Message message = m_myMsgHandler.obtainMessage(R.id.message_id2, data);
message.sendToTarget();

where data, is the data you want to encapsulate (ex: byte[] data, int data etc)

In the message handler, in the switch, one will use the data as follows:


case R.id.message_id1:
   byte[] val = (byte[]) msg.obj;

Categories: android java Tags: