Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art
Sending Messages Between Threads Using an Activity Thread Queue and HandlerBack to Android Cookbook Home | Up to Chapter: Inter/Intra-Application Communication

Author: Vladimir Kroz ('vkroz')
In Published Edition? Yes
FormatLanguage: WikiFormat

Sending Messages Between Threads Using an Activity Thread Queue and Handler


You need to pass information or data from a Service or other background task, to an Activity. Since Activities run on the UI thread it is not safe to call them from a background thread.



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() {
		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

. . . .


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;
// Dummy code to simulate delay while working with remote server
				try {
				} catch (InterruptedException e) {

See Also