Android 上的倒数计时器问题
您好,我的活动 oncreate 方法中有一个倒计时器,如下所示,
start1 = new CountDownTimer(level1time, 1000)
//timer updated every second
{
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//switch activities
}
}
.start();
}
然后我稍后在代码中调用 start1.cancel 。当此特定活动启动一次但稍后再次创建此活动时,该活动会因第一个计时器完成而立即切换。
我的理解是,每次创建活动时都应该创建一个新的计时器,但情况似乎并非如此。有谁知道如何解决这个问题?
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. Does anyone know how to fix this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无论如何,最好使用处理程序而不是计时器。我通常会创建一个最终的 Runnable 对象,该对象具有我想要在一定时间后运行的内容,在 onCreate() 中创建一个新的处理程序,并在一定延迟后使用 postDelayed(Runnable, int) 将 Runnable 发布给它。如果用户离开活动或者您希望它不执行,您可以简单地使用定义的 Runnable 调用 Handler.removeCallbacks(Runnable) 来停止其上的“计时器”。
这是解决你的问题的高级方法。熟悉了Handler类,这就变成一个很容易的问题了。
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.