安卓:当活动模,定时器孤立 [英] Android: When Activity Dies, Timer is Orphaned

查看:99
本文介绍了安卓:当活动模,定时器孤立的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个相对的Andr​​oid新手编写一个应用程序定时器。我使用的是自定义的倒数计时器类,这是主要的活动类的成员,它产生一个处理程序运行每一秒。

I'm a relative Android newbie writing a timer application. 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.

当我关闭该应用程序,主要的活动停止,但定时器将继续在后台运行,因为我想要的。问题是,该活动重新启动时,原有的定时器现在是孤儿,我无法找到的重新附着到它的一种方式。

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?

推荐答案

有几种不同的方法。

  • You can make use of the System's AlarmManager.
  • You can make your own Service.
  • You can make your TimerObject persist.

由于我不知道您的具体要求,我建议你按照<击>白兔以上链接并为自己的法官。

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.

这是否对象实际上什么每一秒甚至封闭的活动?也许这足以坚持一个参考时间戳和破坏TimerObject /处理程序退出时(的onPause ),并作出新的持久状态(如果有的话)启动活动是什么时候?

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?

这篇关于安卓:当活动模,定时器孤立的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆