Timer task TimerTask run cancel Android example

Update TextView from TimerTask, Handler, schedule, run, cancel TimerTask, Android example

public class TimerActivity extends Activity {
	TimerTask mTimerTask;
	final Handler handler = new Handler();
	Timer t = new Timer();	
TextView hTextView;
TableRow hTableRow;
Button hButton, hButtonStop;
 
 
private int nCounter = 0;
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        hTextView = (TextView)findViewById(R.id.idTextView);
        hButton = (Button)findViewById(R.id.idButton);
        hButton.setOnClickListener(mButtonStartListener);
        hButtonStop = (Button)findViewById(R.id.idButtonStop);
        hButtonStop.setOnClickListener(mButtonStopListener);
 
 
 
    } // end onCreate
 
View.OnClickListener mButtonStartListener = new OnClickListener() {
	public void onClick(View v) {
		doTimerTask();
    }
};
 
 
 
 
	View.OnClickListener mButtonStopListener = new OnClickListener() {
    	public void onClick(View v) {
    		stopTask();
 
    	}
    };
 
 
    public void doTimerTask(){
 
    	mTimerTask = new TimerTask() {
    	        public void run() {
    	                handler.post(new Runnable() {
    	                        public void run() {
    	                        	nCounter++;
                                        // update TextView
    	                        	hTextView.setText("Timer: " + nCounter);
 
    	                        	Log.d("TIMER", "TimerTask run");
    	                        }
    	               });
    	        }};
 
            // public void schedule (TimerTask task, long delay, long period) 
    	    t.schedule(mTimerTask, 500, 3000);  // 
 
    	 }
 
    	  public void stopTask(){
 
    	   if(mTimerTask!=null){
    	      hTextView.setText("Timer canceled: " + nCounter);
 
    	      Log.d("TIMER", "timer canceled");
    	      mTimerTask.cancel();
    	 }
 
    }    
}
This entry was posted in Android Examples Code and tagged , , , , , . Bookmark the permalink.


Comments are closed.

52,322 views