Sending messages between threads using activity thread queue and Handler class

Discussion There are many situations when it is required to have a thread running in the background and send information to main Activity’s UI thread. At the architectural level there are different approaches that can be taken:

  1. Use of Android AsyncTask class
  2. Start a new thread

Though using AsyncTask is very convenient, there are a situations when you really need to construct a worker thread by yourself. In such situation you likely will need to send some information back to Activity thread. Keep in mind that Android doesn’t allow other threads to modify any content of main UI thread. Instead you’re required to wrap data into Messages and send them through message queue. The implementation consists of two parts.

1) Add handler

Add an instance of Handler class to e.g., your MapActivity instance.

public class MyMap extends MapActivity {
    . . . 
    public Handler _handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Log.d(TAG, String.format("Handler.handleMessage(): msg=%s", msg));
            // This is where main activity thread receives messages
            // Put here your handling of incoming messages posted by other threads
			super.handleMessage(msg);
		}

	};
. . . .

}

2) Post Message

In the worker thread post a message to activity main queue whenever you need Add handler class instance to your MapActivity instance.

	/**
	 * Performs background job
	 */
	 class MyThreadRunner implements Runnable {
		// @Override
		public void run() {
			while (!Thread.currentThread().isInterrupted()) {
// Just dummy message -- real implementation will put some meaningful data in it
				Message msg = Message.obtain();
				msg.what = 999;
				MyMap.this._handler.sendMessage(msg);
// Dummy code to simulate delay while working with remote server
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
				}
			}
		}
	 }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s