Wednesday, May 13, 2015

Timer task TimerTask run cancel 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(onCreateBundle) savedInstanceState { 
        super.onCreate(savedInstanceState); 
        (layoutmain); 
        setContentViewR.. 
        hTextView = (TextView) findViewById(R.id.idTextView); 
        hButton = (Button) findViewById(R.id.idButton); 
        setOnClickListener(); 
        hButton.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(); 
            } 
        } 
    }

No comments:

Post a Comment