- Java code
package com.timer.timer;import java.util.Timer;import java.util.TimerTask;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity { private Timer timer = null; private TimerTask task = null; private Button start = null; private TextView viewstart = null; private boolean flag = false; private int i = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); start = (Button)findViewById(R.id.timer); viewstart = (TextView)findViewById(R.id.viewtimer); start.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub timer = new Timer(); timer.schedule(task, 10*1000); new timerthread().start(); } }); task = new TimerTask() { @Override public void run() { // TODO Auto-generated method stub flag = true; return; } }; } private class timerthread extends Thread{ @Override public void run() { // TODO Auto-generated method stub super.run(); while(true){ if(flag){ timer.cancel(); task.cancel(); timer.purge(); timer = null; System.out.println("取消timer "+timer); break; } System.out.println(i++); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return ; } }}
希望再定时器到了之后再点击按钮 再次启动他 现在第一次可以 能打印0到9 第二次就死了 提示task已经在队列中了
------解决方案--------------------
在
timer = new Timer();
timer.schedule(task, 10*1000);
new timerthread().start();
的前面加上:
flag = false;