private Handler mHandler = new Handler() { public void handleMessage(Message msg) { int arg1 = msg.arg1; if (arg1 == 0) {//时间到 } textView.setText(String.valueOf(arg1)); } }; /** * 开始自动减时 */ private void startTime() { if (timer == null) { timer = new Timer(); } timerTask = new TimerTask() { @Override public void run() { Message message = Message.obtain(); message.arg1 = time; mHandler.sendMessage(message);//发送消息 time--;//自动减1 } }; timer.schedule(timerTask, 0, 1000);//1000ms执行一次 }
private void stopTime() { if (timer != null) { timer.cancel(); timer = null; } if (timerTask != null) { timerTask.cancel(); timerTask = null; } time = 0; }