Android 上的倒数计时器问题

发布于 2024-10-27 18:50:46 字数 472 浏览 1 评论 0原文

您好,我的活动 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

真心难拥有 2024-11-03 18:50:46

无论如何,最好使用处理程序而不是计时器。我通常会创建一个最终的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文