利用Timer和TimerTask做一个计时器

包括开始、停止、暂停、恢复四个功能

需要注意的问题主要有两点:

1、Timer和TimerTask在调用cancel()取消后

不能再执行 schedule语句,否则提示出错

2、只能在UI主线程中更新控件/组件。

在其他线程中,更新控件/组件,会提示出错


packagecom.example.testtimer2;importjava.util.Timer;importjava.util.TimerTask;importandroid.os.Bundle;importandroid.os.Handler;importandroid.os.Message;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.TextView;importandroid.annotation.SuppressLint;importandroid.app.Activity;@SuppressLint("HandlerLeak")publicclassMainActivityextendsActivityimplementsOnClickListener{privateButtonbtnStart;privateButtonbtnPause;privatebooleanisStop=true;privatebooleanisPause=false;privateintcount=0;privateintdelay_time=1000;privateintUPDATE_UI=0x11;privateTimermTimer;privateTimerTaskmTimerTask;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnStart=((Button)findViewById(R.id.button1));btnPause=((Button)findViewById(R.id.button2));btnStart.setOnClickListener(this);btnPause.setOnClickListener(this);}privatevoidstartTimer(){if(mTimer==null){mTimer=newTimer();}if(mTimerTask==null){mTimerTask=newTimerTask(){publicvoidrun(){do{try{Thread.sleep(delay_time);mHandler.sendEmptyMessage(UPDATE_UI);if(!isPause){count++;}if(isStop){count=0;}}catch(Exceptione){e.printStackTrace();}}while(!isStop);}};}if(mTimer!=null&&mTimerTask!=null){/***Timer.schedule(TimerTasktask,longdelay,longperiod)*三个参数分别为:1、要执行的任务2、延迟多少时间开始执行3、每隔多少时间执行一次**/mTimer.schedule(mTimerTask,delay_time);}}privatevoidstopTimer(){if(mTimer!=null){mTimer.cancel();mTimer=null;}if(mTimerTask!=null){mTimerTask.cancel();mTimerTask=null;}count=0;}privateHandlermHandler=newHandler(){publicvoidhandleMessage(Messagemsg){switch(msg.what){case0x11:initUI();break;}}};privatevoidinitUI(){((TextView)findViewById(R.id.textView1)).setText(count+"");}@OverridepublicvoidonClick(Viewarg0){if(arg0.equals(btnStart)){if(isStop){startTimer();}else{stopTimer();}isStop=!isStop;if(isStop){btnStart.setText(R.string.start_time);}else{btnStart.setText(R.string.stop_time);}}if(arg0.equals(btnPause)){if(isPause){}else{}isPause=!isPause;if(isPause){btnPause.setText(R.string.resume_time);}else{btnPause.setText(R.string.pause_time);}}}}

//layout布局

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context=".MainActivity"><TextViewandroid:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentTop="true"android:layout_centerHorizontal="true"android:layout_marginTop="23dp"android:text="@string/show_time"/><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_alignParentRight="true"android:layout_below="@+id/textView1"android:layout_marginTop="38dp"android:text="@string/start_time"/><Buttonandroid:id="@+id/button2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/button1"android:layout_alignParentRight="true"android:layout_below="@+id/button1"android:layout_marginTop="16dp"android:text="@string/pause_time"/></RelativeLayout>

//string.xml

<?xmlversion="1.0"encoding="utf-8"?><resources><stringname="app_name">TestTimer2</string><stringname="action_settings">Settings</string><stringname="hello_world">Helloworld!</string><stringname="start_time">start</string><stringname="stop_time">stop</string><stringname="resume_time">resume</string><stringname="pause_time">pause</string><stringname="show_time">time</string></resources>