Friday, 4 January 2013

Simple Timer Example in android



Best Timer example for android



Timer t = new Timer();

  TimerTask task = new TimerTask() {

   @Override
   public void run() {
    runOnUiThread(new Runnable() {

     @Override
     public void run() {
      TextView tv1 = (TextView) findViewById(R.id.timer);
      tv1.setText(time + "");
      if (time > 0)
       time -= 1;
      else
       tv1.setText("Welcome");
     }
    });
   }
  };

  t.scheduleAtFixedRate(task, 0, 1000);





TimerActivity.java


package com.android.timer;

import java.util.Timer;
import java.util.TimerTask;

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

public class TimerActivity extends Activity {

  int time = 20;
 Timer t;
 TimerTask task;
 Button start;

  @Override
 protected void onCreate(Bundle savedInstanceState) {

   super.onCreate(savedInstanceState);
  setContentView(R.layout.main);  

   start = (Button) findViewById(R.id.start);
  
  start.setOnClickListener(new OnClickListener() {

    @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    if (start.getText().toString().equals("START")) {
     start.setText("STOP");
     time = 20;
     startTimer();     
     
    }else{
     t.cancel();
     t.purge();
     TextView tv1 = (TextView) findViewById(R.id.timer);
     tv1.setText("20"); 
     start.setText("START");
    }
   }
  });

  }
 public void startTimer(){
  t = new Timer();   
  task = new TimerTask() {

    @Override
   public void run() {
    runOnUiThread(new Runnable() {

      @Override
     public void run() {
      TextView tv1 = (TextView) findViewById(R.id.timer);
      tv1.setText(time + "");
      if (time > 0)
       time -= 1;
      else {
       tv1.setText("Welcome");           
      }
     }
    });
   }
  };
  t.scheduleAtFixedRate(task, 0, 1000);
 }
}