package com.example.task01;

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

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.TextureView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

			TextView text_reponse;
			Button btn_start, btn_stop;
			
			TimerTask mTimerTask;
			final Handler handler = new Handler();
			Timer t = new Timer();	

			private int nCounter = 0;

			@Override
		    public void onCreate(Bundle savedInstanceState) 
			{
		        super.onCreate(savedInstanceState);
		    	setContentView(R.layout.activity_main);
		        
		    	text_reponse = (TextView)findViewById(R.id.reponse);	
		        btn_start = (Button)findViewById(R.id.btn_start);
		        btn_stop = (Button)findViewById(R.id.btn_stop);

		        btn_start.setOnClickListener(mButtonStartListener);
		        btn_stop.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
		    	                        	text_reponse.setText("Timer: " + nCounter);
		 
		    	                        	Log.d("TIMER", "TimerTask run");
		    	                        }
		    	               });
		    	        }};
		 
		            // public void schedule (TimerTask task, long delay, long period) 
		    	    t.schedule(mTimerTask, 0, 3000);  // 
		 
		    }
 
		    public void stopTask()
		    {
		 
		    	   if(mTimerTask!=null){
		    		   text_reponse.setText("Timer canceled: " + nCounter);
		 
		    	      Log.d("TIMER", "timer canceled");
		    	      mTimerTask.cancel();
		    	 }
		 
		    }    
}
