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.