简体   繁体   English

防止iOS在3分钟后杀死我的应用

[英]Prevent iOS from killing my app after 3 minutes

To avoid implementing a persistent caching logic of a whole navigation stack I want to keep my app "alive" (at least for 2 hours) even in the background, so when the user reopens the app it is where it was before going to sleep. 为了避免在整个导航堆栈中实现持久的缓存逻辑,我希望即使在后台也可以保持应用程序“活动”(至少2个小时),因此,当用户重新打开应用程序时,它就是睡觉前的位置。

I tried with a background task: 我尝试了一个后台任务:

_timerBackgroundTaskId = UIApplication.SharedApplication.BeginBackgroundTask(() =>
{
    // Run some dummy code here. Shouldn´t this prevent the task from actually stopping?
    var remaining = UIApplication.SharedApplication.BackgroundTimeRemaining;
    this.Log().Debug($"Expiration. Remaining: {remaining}. Timer seconds left: {_secondsLeft}");
});
// I´m actually using the timer for something :)
_nsTimer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(1), delegate { TimerTick(); });

// later on (after 3 minutes)
UIApplication.SharedApplication.EndBackgroundTask(_timerBackgroundTaskId.Value);

No matter what I try, after 3 minutes iOS kills the app. 无论我如何尝试,iOS都会在3分钟后终止该应用程序。 Some answers in SO tell how to do it with a fake/silent background sound, but I don´t want any trouble with Apple reviews. SO中的一些答案说明了如何使用伪造的/无声的背景声音来做到这一点,但是我不希望Apple评论有任何麻烦。

Any advice? 有什么建议吗?

In fact, the app was killed because I was running a background task longer than 3 minutes, which is the limit. 实际上,该应用程序被杀死是因为我运行的后台任务超过了3分钟,这是极限。 The solution to my problem was as easy as limiting the task to 3 minutes max. 解决我的问题的方法很简单,只需将任务限制为最多3分钟即可。

By default iOS won´t ever kill your app , unless the device runs severely out of memory. 默认情况下,iOS不会杀死您的应用程序 ,除非该设备严重耗尽内存。

The 3 minutes limit is applied ONLY when you run some task in the background (ie: UIApplication.SharedApplication.BeginBackgroundTask ) to prevent battery drain. 在您在后台运行某些任务(即UIApplication.SharedApplication.BeginBackgroundTask )时才应用3分钟的限制,以防止电池耗尽。

If you don´t start any background task before the app goes to background, the app will always be there, keeping the state (I´ve tested this waiting for hours). 如果您没有在应用程序进入后台之前启动任何后台任务,则该应用程序将始终保持在该状态,并保持状态(我已经测试了此等待时间)。

In my case I was using a background task to keep a countdown/alarm working. 就我而言,我正在使用后台任务来保持倒数/警报工作。 But I´ve just found a workaround scheduling local notifications. 但是我刚刚发现了一种安排本地通知的解决方法。

If you MUST run a background task, to keep the app state you´ve got 2 options: 如果您必须运行后台任务,要保持应用状态,您有2个选择:

  1. End the task before 3 minutes 3分钟前结束任务
  2. Implement a restoring strategy. 实施恢复策略。 iOS itself provides a built-in API for it. iOS本身为其提供了内置API

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

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