当 Activity 失去焦点时停止计时器

发布于 2024-10-01 17:03:05 字数 484 浏览 0 评论 0原文

我有一个计时器,每 30 秒执行一次 TimerTask。我只希望计时器在显示活动时启动新的 TimerTask,即如果用户接到电话或启动新活动,计时器将停止。然后,当活动重新启动并成为焦点时,我需要重新启动计时器。

现在这应该很容易,我重写“onWindowFocusChanged(boolean hasFocus)”方法,并根据hasFocus的值启动或停止计时器。我启动计时器的方法是每次创建一个新的 Timer 对象和 TimerTask,停止计时器的方法是调用 Timer 对象上的 cancel() 方法并将计时器设置为 null。

我的问题是这并不总是有效,如果我启动具有计时器的活动并快速切换方向(以启动/停止活动),我发现计时器并不总是被取消,并且最终会出现多个计时器在某个时间启动计时器任务不断增加的速度。

我在这里遗漏了一些明显的东西吗?任何帮助将不胜感激。

谢谢

I have a Timer which executes a TimerTask every 30 seconds. I only want the timer to launch a new TimerTask if the Activity is displayed i.e. if the user receives a phone call or launches a new activity the Timer will stop. I then need the Timer to restart when the Activity is re-launched and comes into focus.

Now this should be easy, I override the "onWindowFocusChanged(boolean hasFocus)" method and either start or stop the timer depending on the value of hasFocus. The way I start the timer is to create a new Timer object and TimerTask each time and the way I stop the Timer is to call the cancel() method on the Timer object and set timer to null.

My problem is this doesn't always work, if I launch the activity which has the Timer and switch orientations quickly (to start/stop the Activity) I find the Timer is not always cancelled and I end up with multiple Timers launching TimerTasks at an ever increasing rate.

Am I missing something obvious here? Any help would be greatly appreciated.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

孤单情人 2024-10-08 17:03:05

当我看到这个时,这是因为我在我的应用程序中创建了 2 个 CountDownTimers。因为每个定时器只能读取类型“1”的消息[参见http://www.devdaily.com/java/jwarehouse/android/core/java/android/os/CountDownTimer.java.shtml],看来我只有 1 个计时器,而我的应用程序运行正常。我在 onDestroy 中放置了一个“timer.cancel()”来处理其中一个计时器,允许另一个计时器在 onDestroy 返回很久之后开始接收所有计时消息。

在创建另一个计时器之前取消任何现有计时器可以解决延迟计时器的问题。

When I see this, it's because I'm creating 2 CountDownTimers in my app. Because each timer can only read messages of type "1" [see http://www.devdaily.com/java/jwarehouse/android/core/java/android/os/CountDownTimer.java.shtml ], it appeared that I only had 1 timer while my app was running normally. I put a "timer.cancel()" in my onDestroy that took care of one of the timers, allowing the other timer to start receiving all the timing messages--long after the onDestroy had returned.

Canceling any existing timer before creating another took care of the lingering timer.

子栖 2024-10-08 17:03:05

我遇到了类似的问题,我最终在线程中使用延迟发布并避免使用计时器。不过,这并不是真正的修复。

I had a similar problem, I ended up using post delayed in a Thread and avoided a Timer. Not really a fix though.

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