Countdown timer problem on android
Hi I have a countdown timer in my activity oncreate method as follows
start1 = new CountDownTimer(level1time, 1000)
//timer updated every second
{
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//switch activities
}
}
.start();
}
I then call start1.cancel later in my code. This works when this particular activity is started once but when this activity is created again later the activities switch instantly due to the first timer finishing.
My understanding is that a new timer should be created each time the activity is created but that does not seem to be the case. 开发者_如何学GoDoes anyone know how to fix this problem?
In any case it's better to use Handlers instead of Timers. I generally create a final Runnable object that has what I want run after a certain time, create a new Handler in onCreate(), and post the Runnable to it after a certain delay with postDelayed(Runnable, int). If the user leaves the activity or you ever want it to not execute, you can simply call Handler.removeCallbacks(Runnable) with your defined Runnable to stop the "timer" on it.
That's a high-level approach to your question. Get familiar with the Handler class and this becomes a very easy problem.
精彩评论