应用程序在后台模式下执行 180 秒后重新启动。通过在功能中启用后台模式
Posted
技术标签:
【中文标题】应用程序在后台模式下执行 180 秒后重新启动。通过在功能中启用后台模式【英文标题】:App restart after 180 sec of execution in background mode. By enable the background modes in capabilities 【发布时间】:2018-02-17 04:59:31 【问题描述】:我根据我的要求制作了一个示例应用程序,代码如下
设计:包含 1 个按钮 1 个标签
.h文件代码
@interface ViewController : UIViewController
int count;
NSTimer *theTimer;
UIBackgroundTaskIdentifier counterTask;
@property (weak, nonatomic) IBOutlet UILabel *theCount;
.m 文件代码
- (IBAction)start:(id)sender
counterTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:^
// If you're worried about exceeding 10 minutes, handle it here
theTimer=[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(countUp)
userInfo:nil
repeats:YES];
];
count=0;
theTimer=[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(countUp)
userInfo:nil
repeats:YES];
- (void)countUp
if (count==100000)
[theTimer invalidate];
[[UIApplication sharedApplication] endBackgroundTask:counterTask];
else
count++;
NSString *currentCount;
currentCount=[[NSString alloc] initWithFormat:@"%d",count];
_theCount.text=currentCount;
问题在于,在后台运行此应用程序时(通过按主页按钮并最小化 iPhone 中的应用程序),即使在功能中启用后台模式,它也会在 180 秒后重新启动。我需要将其延长至 4 小时。请帮我。
【问题讨论】:
如果你的应用有bluetooth-central
后台能力,当设备发送更新时你的应用会被短暂唤醒。你不能让应用程序永远活着来做其他事情,只有 10 秒来处理更新。现在,很明显,如果用户在四个小时后唤醒设备,您的应用应该已经接收并处理了此后发生的所有更新。但是这种计时器方法是行不通的。
【参考方案1】:
在更高版本的 ios 中,后台任务的限制为 3 分钟(180 秒)。您不能将其延长至 4 小时。
苹果文档:
注意:启动任务时始终提供过期处理程序,但如果您想知道应用还剩多少时间可以运行,请获取 UIApplication 的 backgroundTimeRemaining 属性的值。
关于该主题的良好堆栈溢出帖子:
How long does Apple permit a background task to run?
【讨论】:
developer.apple.com/library/content/documentation/iPhone/… ( 执行长时间运行的任务 ) - 我的要求是从外部附件接收定期更新的应用程序。 你认为我在哪里得到了上面的报价......? 仅仅因为您使用的是外部配件,并不意味着 iOS 会让您随时运行后台任务。如果您需要在后台与外部附件通信,请查看 iOS 中的外部附件框架。 感谢您的回答。在我的项目中,我需要连接 BLE MedicalTreatment 设备并将设备时间从 30 分钟设置为 4 小时。并通过我的应用程序开始,之后需要在应用程序屏幕上运行的计时器完成后传递到下一个屏幕。但在后台应用程序在 180 秒后从头开始重新启动。我该怎么办? 不要在后台运行超过允许的后台时间的任务。你不需要计时器就能看到已经 4 小时了。当时间应该开始时在本地保存时间,并在应用返回前台时检查当前时间与保存的时间。以上是关于应用程序在后台模式下执行 180 秒后重新启动。通过在功能中启用后台模式的主要内容,如果未能解决你的问题,请参考以下文章
在后台模式下从 Nodejs 执行 VBS(任务计划程序或 Windows 服务)
HttpURLConnection getInputStream:总是在 180 秒后超时