热门IT资讯网

Timer and TimerTask计时器

发表于:2024-11-29 作者:热门IT资讯网编辑
编辑最后更新 2024年11月29日,利用Timer和TimerTask做一个计时器包括开始、停止、暂停、恢复四个功能需要注意的问题主要有两点:1、Timer和TimerTask在调用cancel()取消后不能再执行 schedule语句

利用Timer和TimerTask做一个计时器

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

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

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

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

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

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


package com.example.testtimer2;import java.util.Timer;import java.util.TimerTask;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;import android.annotation.SuppressLint;import android.app.Activity;@SuppressLint("HandlerLeak")public class MainActivity extends Activity implements OnClickListener{private Button btnStart;private Button btnPause;private boolean isStop = true;private boolean isPause = false;private int count = 0;private int delay_time = 1000;private int UPDATE_UI = 0x11; private Timer mTimer;private TimerTask mTimerTask;@Overrideprotected void onCreate(Bundle savedInstanceState) {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);}private void startTimer(){if(mTimer == null){mTimer = new Timer();}if(mTimerTask == null){mTimerTask = new TimerTask(){public void run() {do{try{Thread.sleep(delay_time);mHandler.sendEmptyMessage(UPDATE_UI);if(!isPause){count++;}if(isStop){count = 0;}}catch(Exception e){e.printStackTrace();}}while(!isStop);}};}if(mTimer != null && mTimerTask != null){/** * Timer.schedule(TimerTask task, long delay, long period) * 三个参数分别为:1、要执行的任务 2、延迟多少时间开始执行 3、每隔多少时间执行一次 * */mTimer.schedule(mTimerTask, delay_time);}}private void stopTimer(){if(mTimer != null){mTimer.cancel();mTimer = null;}if(mTimerTask != null){mTimerTask.cancel();mTimerTask = null;}count = 0;}private Handler mHandler = new Handler(){public void handleMessage(Message msg){switch(msg.what){case 0x11:initUI();break;}}};private void initUI(){((TextView) findViewById(R.id.textView1)).setText(count + "");}@Overridepublic void onClick(View arg0) {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布局

        

//string.xml

    TestTimer2    Settings    Hello world!    start    stop    resume    pause    time



0