Rescheduling Timer in android

I'm trying to have a Timer that schedules a TimerTask for successive executions. I don't know how many times it'll work. on a user click, the Timer will stop, and on another, it'll run again. Everything works until stopping, when i reschedule, I get exceptions saying that the Timer is canceled or already scheduled. How do I make it stop and run again? I've tried everything I could think of and it's still not working.

This is the latest code I'm trying:

        Timer myTimer;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    cameraTimedTask = new camera(this);

        myTimer = new Timer("cameraTimer");

        Button b=(Button)findViewById(R.id.b);
        b.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                myTimer.purge();
                myTimer.scheduleAtFixedRate(cameraTimedTask, 1000, 5000);
            }
        });

        Button bb=(Button)findViewById(R.id.button);
        bb.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                myTimer.cancel();
                myTimer.purge();
                myTimer = null;
                myTimer = new Timer("camerasTimer");
                Log.i("Check","[main]"+" timer stopped");
            }
        });

    }

You can't reschedule a TimerTask. You need a new one every time. Moreover, it is advised in android to use Handlers and postDelayed.


in my opinion, try to use Countdown timer instead of timer

quick usage:

 new CountDownTimer(30000, 1000) {

 public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
 }

 public void onFinish() {
     mTextField.setText("done!");
 }
}.start();

or if you want something more complex:

 public class MyCountDownTimer extends CountDownTimer {
   public MyCountDownTimer(long startTime, long interval) {
    super(startTime, interval);

  }
  @Override
   public void onFinish() {
   text.setText("Time's up!");
  }

  @Override
 public void onTick(long millisUntilFinished) {
 text.setText("" + millisUntilFinished / 1000);

 }

}

The perfect solution for you would be to use a Handler

private Runnable runnable;
private Handler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   handler = new Handler();
   runnable = new Runnable() {

    @Override
    public void run() {
          // run code delayed code in here once
    }
};

Then in your multirepeating code you have to remove the posted callbacks and then reschedule for execution.

handler.removeCallbacks(runnable);
handler.postDelayed(runnable, 200);
链接地址: http://www.djcxy.com/p/74922.html

上一篇: 如何从TimerTask运行中重新安排Timer

下一篇: 在android中重新调度计时器