Monday, May 14, 2012

Android Threading (Basic)

A thread is a sequential path of code execution within a program. And each thread has its own local variables, program counter and lifetime.

in this example we create simplest thread by implementing Runnable interface.

Start Coding.. so lets move ahead with some coding..

create a Simple Android App Name "AndroidThreadingBasic" with 2.3.3 SDK,

your Activity should be like this.

package com.rdc;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MyActivity extends Activity implements OnClickListener {
 //Declear the button and Textview instance variable
 private Button btnStart=null; 
 private TextView tv=null;
    public void onCreate(Bundle savedInstanceState) {
        //get the id of Button from xml file
        btnStart = (Button) findViewById(;
      //get the id of TextView from xml file
        tv = (TextView) findViewById(;

 public void onClick(View v) {
    // create thread by implementing Runnable interface
    new Thread(new Runnable() {
          public void run() {
          System.out.println("Thread is running now..");
          for(int i=1;i<=10;i++){

Now put this code in your main.xml file


The output Screen will be like this..

and check your logcat, it will print 1 to 10 integers with message.

Note : if you want to update UI then you should use Handler or AsyncTask Thread Check my Blogs below

Android Threading with Handler and  

Android Threading With AsyncTask

I'd love to hear your thoughts! 

No comments:

Post a Comment