Download Code

In this tutorial you will learn how to implement Runnable class,to run code in a separate thread.You can read basics of thread in android application from here.First i’ll give you some information about classes,which will be used.

Runnable

Runnables is used to represent a command that can executed.It is mostly to used to run any module in different threads.

Handler

A Handler is used to send and process Message and Runnable object’s associated with the Thread’s MessageQueue. Every.Every handler instance associated with the single thread and it’s message queue.

There are two main uses for a Handler:-

  • To schedule messages and runnables to be executed as some point in the future
  • To enqueue an action to be performed on a different thread than your own.

Looper

Looper is used to run message loop for a thread.By default threads don’t have message loop,to create that call prepare() method,and then loop() method to process messages until loop end.
Basic Example of Looper

class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }

OK let’s start with the thread example using Runnable class.In this project we will deal with current and background Thread.

Go ahead and create Android Application Project.

Now go to your activity_main.xml and use two buttons and a Text-view in xml. Like this.

runnable

Now go to your MainActivity.java class.Create Button and TextView variables,refer their id’s and apply click Listener by implementing classes just like this.

public class MainActivity extends Activity implements OnClickListener{
	Button threadStart, threadRun; // Button variables
	TextView Info;                 // textview to display information about thread
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		threadStart = (Button)findViewById(R.id.startBtn);    // refering id's
		threadRun = (Button)findViewById(R.id.runBtn);        // refering id's
		Info = (TextView)findViewById(R.id.threadInfo);       // refering id's
		threadStart.setOnClickListener(this);  // click listener
		threadRun.setOnClickListener(this);  // click listener
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.startBtn:
			break;
		case R.id.runBtn:	
			break;
		}
	}	
}

Now add Runnable class code and call runnable run method to start thread.

MainActivity.java

package com.example.runnable;

/*
 * 
 * All Rights Reserved By: Farhan Rasheed
 * 
 * */

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.os.Looper;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends Activity implements OnClickListener{


	Button threadStart, threadRun; // Button variables
	TextView Info;                 // textview to display information about thread

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		threadStart = (Button)findViewById(R.id.startBtn);    // refering id's
		threadRun = (Button)findViewById(R.id.runBtn);        // refering id's
		Info = (TextView)findViewById(R.id.threadInfo);       // refering id's
		threadStart.setOnClickListener(this);  // click listener
		threadRun.setOnClickListener(this);  // click listener

		
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.startBtn:
			Thread thread = new Thread(new MyRunnable());
		    thread.start(); //in background thread
			break;
		case R.id.runBtn:
			 Thread th = new Thread(new MyRunnable());
			 th.run(); //in current thread
			break;
		}
	}
	
	private class MyRunnable implements Runnable {

		@Override
		public void run() {
			// check if it's run in main thread, or background thread
			if(Looper.getMainLooper().getThread()==Thread.currentThread()){
				//in main thread
				Info.setText("in main thread");
			}else{
				//in background thread

				runOnUiThread(new Runnable(){

					@Override
					public void run() {
						Info.setText("in background thread");
					}

				});
			}
		}

	}

	

}

Now Run your android application project.Output should be like this.
runnable

that’s it for this tutorial i hope you get everything in detail.

Thanks.