Tuesday, 4 June 2013

Thread Example in ANDROID -- Timer Thread Example

See more post on threads :
Non Runnable States in Multithreading

What is thread in java ?

This example shows how a thread get activated on every interval of time. Here an array of string is given which is used to display a text change for every activated thread calls.

public class Threadexample extends Activity {

  protected int splashTime = 3000;
     TextView tv1;
     String[] name = {"Angel","Mark","Coding","Playground","For","All","Coderz"};
     int timer =0;
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_threadexample);
         tv1 = (TextView) findViewById(R.id.textView1);
         Thread th=new Thread(){
  
             @Override
             public void run(){
                 try  
                 {
                     for (timer = 0; timer < 7; timer++)
                     {
                         int waited = 0;
                         while(waited < splashTime)
                         {
                             Thread.sleep(100);
                             runOnUiThread(new Runnable() { 
                                 public void run() {
                                     try {
                                         tv1.setText(name[timer]);
                                     }
                                     catch(Exception e) 
                                     {
                                         e.printStackTrace();
                                     } 
                                 }
                             });
                             waited += 100;
                         }
                     }
                 }catch (InterruptedException e) {
                 }
  
             }
         };
         th.start();
     }
  
  }



No comments:

Post a Comment