当前位置: 代码迷 >> Eclipse >> android的timer如何能够重复的启用
  详细解决方案

android的timer如何能够重复的启用

热度:24   发布时间:2016-04-23 12:24:13.0
android的timer怎么能够重复的启用
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;