Background processing using a Handler in Android


The handler is a class that gets associated with the main thread and provides communication with other threads. Our goal is to send data to the main thread from non UI threads. There will be only one handler per activity.

Background Processing using a Handler

Create a new xml layout. Layout is very simple and uses one TextView.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:id="@+id/textView"
        android:layout_marginLeft="136dp"
        android:layout_marginTop="42dp"
        android:textSize="28sp"
        android:text="10" />

</RelativeLayout>

Create a new Handler

Create a new Handler to get associated with our activity. Add following code inside your activity. Our thread will use handler to interact with the main thread.

    Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
		}
		
	};

Get the reference of TextView from onCreate().

textView = (TextView) findViewById(R.id.textView);

New Background Thread

We will create a background thread inside onStart() callback of Activity.

  • Our goal is to create a count-down timer using background processing.
  • Create a for loop and add make thread sleep for 1 second each time.
  • Use handler.sendMessage() to handle the main thread using Handler.
  • Then execute the thread by invoking start().
Thread myThread = new Thread(new Runnable(){
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
			  for(int i = 10; i>0;i--){
				  try {
					Thread.sleep(1000);
					handler.sendMessage(handler.obtainMessage());
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				  
			  }	
			}
		});
    //execute the thread
    myThread.start();

Complete code for count-down timer using handlers in android

  • Complete the steps described above.
  • Go to handleMessage() and receive the text from TextView. In this way our thread is interacting with the main thread.
  • You need to take the current value from TextView as a string and then convert it into an integer value.
  • Decrement the value of integer by 1.
  • Set the new value using setText().
package com.example.handlerkb4dev;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
	TextView textView;
	Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			String string = textView.getText().toString();
			int num = Integer.parseInt(string);
			num = num-1;
			string = Integer.toString(num);
			textView.setText(string);
		}
		
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textView = (TextView) findViewById(R.id.textView);
	}
    
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Thread myThread = new Thread(new Runnable(){
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
			  for(int i = 10; i>0;i--){
				  try {
					Thread.sleep(1000);
					//handler.sendMessage(handler.obtainMessage());
					handler.sendMessage(handler.obtainMessage());
					
				  } catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				  
			  }	
			}
		});
		myThread.start();
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}