Android: When Activity Dies, Timer is Orphaned

▼魔方 西西 提交于 2020-01-05 04:03:30

问题


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?


回答1:


There are several different approaches.

  • 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.

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?



来源:https://stackoverflow.com/questions/13629813/android-when-activity-dies-timer-is-orphaned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!