简体   繁体   English

Android:当活动死亡时,计时器是孤立的

[英]Android: When Activity Dies, Timer is Orphaned

I'm a relative Android newbie writing a timer application. 我是一个相对的Android新手写一个计时器应用程序。 I'm using a custom countdown timer class which is a member of the main activity class, and it spawns a Handler to run each second. 我正在使用自定义倒数计时器类,它是主活动类的成员,它产生一个Handler来运行每秒。

When I close the app, the main activity stops, but the timer continues to run in the background, as I want. 当我关闭应用程序时,主要活动停止,但计时器继续在后台运行,如我所愿。 The problem is that when the activity restarts, the original timer is now an orphan, and I can't find a way of re-attaching to it. 问题是,当活动重新启动时,原始计时器现在是一个孤儿,我找不到重新附加它的方法。

What's the best way of keeping a persistent connection to a timer object, even between activity restarts? 即使在活动重启之间,保持与计时器对象的持久连接的最佳方法是什么?

There are several different approaches. 有几种不同的方法。

As I do not know your exact requirements, I suggest you follow the white rabbit links above and judge for yourself. 由于我不知道您的具体要求,我建议您按照上面的 白兔 链接自行判断。

If you have to stick to the model you described above, maybe the third one is the best option for you. 如果你必须坚持上面描述的模型,也许第三个是最适合你的选择。

Does this object actually do anything each second even with closed activity? 即使是封闭活动,这个对象实际上每秒都会什么吗? Maybe it's enough to persist a reference timestamp and destroy the TimerObject/Handler on exit ( onPause ) and make a new one with the persisted state (if any) when starting the Activity? 也许它足以持久引用时间戳并在退出( onPause )时销毁TimerObject / Handler并在启动Activity时创建一个具有持久状态(如果有)的新时间戳?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM