0

I am using a timer in my application for repeated task. By default, the timer should repeat the task with a delay of one second. I am starting the timer when the application Starts. All this is works perfectly. Also,When I came out of my application and open some other application, the timer keeps running.

When I open Google Maps application, my timer stops running. I don't know why this is happening. I googled and found from the activity life cycle that, if other applications needs memory, all processes will be killed. This is what happening in my case, I guess.

I do not want my timer to stop. It must run always till the user uninstall my application.

  1. Why the above problem occurs?
  2. How to achieve my requirement?
  3. Does Using services will solve the problem? If so, Is there any way to keep timer always ON without using services?
  4. Does Alarm Manager be helpful? Even if the user restarts the phone, the timer should work properly.
4

1 回答 1

0

是的,一项服务将解决您的问题。Activity 的持久性受其生命周期控制,因此最终您无法控制其执行。服务是持久的,因为它不会被系统关闭。但是,如果您进行大量计算,请注意操作系统不会像屏幕活动那样慷慨地分配资源。

简而言之:
1)好吧,根据您提供的信息,我想您得出了正确的结论。
2)通过服务。
3)是的,它会解决你的问题,不,我认为没有其他方法可以做到这一点,至少不是在活动中。
4)如果您实际上不是询问 Java.util.Timer 的持久性,而是询问在特定时间执行一段代码的方法,这可能是更好(/更容易)的解决方案。不过,我不知道它在相当频繁的时间点上效果如何。系统重启后即可恢复服务,无需担心手机关机。您可以订阅启动事件。

于 2013-06-04T15:19:59.860 回答