重启TimerTask失败

时间:2014-09-22 19:18:51

标签: android android-task

我正在编写简单的代码来启动和停止TimerTask。在此代码中Stop可以正常工作,但我无法重新启动TimerTask。请帮我解决这个问题。

我的代码:

public class MainActivity extends Activity implements View.OnClickListener {
    private TimerThread timerThread;
    private boolean timerHasStarted = false;
    private Button button;
    private TextView text;
    private final long startTime = 1000;
    private final long interval = 1;
    private Handler handler;
    private Runnable r;
    private MediaPlayer mp;
    private TimerTask task;
    private Timer timer;
    private long delay;
    private Boolean play = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(this);

        text = (TextView) this.findViewById(R.id.timer);
        mp = MediaPlayer.create(this, R.raw.cpush);
        //mp.start();
        delay = 1000;

        timer = new Timer();
        timerThread = new TimerThread();
        timer.scheduleAtFixedRate(task, 0, 10);
    }

    public long nextLong(Random rng, long n) {
        long bits, val;
        do {
            bits = (rng.nextLong() << 1) >>> 1;
            val = bits % n;
        } while (bits - val + (n - 1) < 0L);
        return val;
    }

    @Override
    public void onClick(View v) {
        button.setBackgroundResource(R.drawable.finish);
        if( play ){
            play = false;
            task.cancel();
        }
        else{
            play = true;
            /* RESTART TimerTask Hear*/
        }
    }
    public class TimerThread extends TimerTask {
        @Override
        public void run() {
            Random rand = new Random();
            final long value = nextLong(rand, 9999999999999999L);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    text.setText("" + value);
                }
            });
        }
    }
}

1 个答案:

答案 0 :(得分:1)

计时器在取消后无法再次运行,您必须创建一个新对象并启动新对象