当应用关闭时,在“后台”中运行计时器 [英] Run timer in 'background' when app is closed

查看:164
本文介绍了当应用关闭时,在“后台”中运行计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的应用程序关闭时,我需要在后台运行一个计时器,但我一直在阅读这是不可能的。我知道我可以在后台运行它约10分钟,但我需要的远不止于此(至少2小时)。

I need to run a timer in the background when my app is closed, however I have been reading that this isn't possible. I know that I can run it in the background for ~10 minutes, but I need considerably more than that (up to at least 2 hours).

我想知道是否有一种方法可以通过在应用程序关闭时保存计时器值,当前时间,在重新打开时检索它们,并将它们与当前时间进行比较来获得差异。然后我可以重新启动计时器并将值加在一起。

I was wondering if there is a way to do this by saving the timer value when the app is closed, the current time, retrieving them when it re-opens, and comparing them to the current time to get the difference. I could then restart the timer and add the values together.

任何人对我如何做到这一点都有任何建议吗?

Anyone have any suggestions as to how I could do this?

推荐答案

正确的方法是保持定时器正在运行的错觉,而不是实际保持它运行。这有两个方面:

The correct approach is to maintain the illusion that the timer is running, without actually keeping it running. There are two aspects to this:


  1. 在应用程序离开前台之前,它应该保存有关计时器的信息(例如,如果您正在计时,计时器开始的时间或计时器应该停止的时间,如果您倒计时的话。您可以使用各种不同的技术在持久存储中保存此信息(例如plist,keyed archiver,Core Data等)。

  1. Before the app leaves the foreground, it should save information about the timer (e.g. either the time the timer started if you're counting up or the time the timer is supposed to stop if you're counting down). You can use a variety of different technologies to save this information (e.g. a plist, keyed archiver, Core Data, etc.) in persistent storage.

然后当应用程序启动时再次检查已保存的时间并重新构建UI以从适当的状态再次启动计时器。

Then when the app starts up again, check the saved time and reconstruct the UI to start the timer again from the appropriate state.

如果您倒计时一段时间(即如果您希望在达到特定时间点时让用户知道,即使应用程序未运行,您也可以使用本地通知。请参阅本地和远程通知编程指南,侧重于本地通知。

If you're counting down to some time (i.e. you want to let the user know when the particular point in time has been reached, even if the app isn't running), you could use a local notification. See the Local and Remote Notification Programming Guide, focusing on the local notifications.

这篇关于当应用关闭时,在“后台”中运行计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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