applicationDidEnterBackground 的代码一直在跑……

2016-02-19 15:29:45 +08:00
 wohenyingyu01
说好只能跑 5 秒的,我就试了下,没想到根本停不下来,附代码:
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(@"%@",NSStringFromSelector(_cmd));
while (YES) {
static int count=0;
count++;
[NSThread sleepForTimeInterval:1];
NSLog(@"sleeping %d",count); //wtf it can run forever?
}
}

按了 home 键之后一直打印到 80 几了还在跑,是不是有什么地方写错了……
2787 次点击
所在节点    iDev
9 条回复
sparanoid
2016-02-19 15:30:28 +08:00
moved to /go/idev
icodesign
2016-02-19 15:33:09 +08:00
没人跟你说跑 5 秒
iOSer2012
2016-02-19 16:13:57 +08:00
不应该对这个方法做这种测试,这个方法只是表明 application 到了后台。这个方法根据官方文档
Your implementation of this method has approximately five seconds to perform any tasks and return. If you need additional time to perform any final tasks, you can request additional execution time from the system by calling beginBackgroundTaskWithExpirationHandler:. In practice, you should return from applicationDidEnterBackground: as quickly as possible. If the method does not return before time runs out your app is terminated and purged from memory.

You should perform any tasks relating to adjusting your user interface before this method exits but other tasks (such as saving state) should be moved to a concurrent dispatch queue or secondary thread as needed. Because it's likely any background tasks you start in applicationDidEnterBackground: will not run until after that method exits, you should request additional background execution time before starting those tasks. In other words, first call beginBackgroundTaskWithExpirationHandler: and then run the task on a dispatch queue or secondary thread.
更不应该在这个方法使用死循环来测试 application 会不会被系统 kill
loveuqian
2016-02-19 16:15:54 +08:00
@iOSer2012
如果我想 app 在后台也干一些事
这件事要一直干的,不能停
正确的姿势应该是什么
iOSer2012
2016-02-19 16:27:31 +08:00
iOS 支持的后台任务有限,基本上就是音频,位置相关 ,voip, 蓝牙

,详细看 Table 3-1 Background modes for apps
https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html
还有一个中文的
https://github.com/bboyfeiyu/iOS-tech-frontier/blob/master/issue-3/iOS%E5%90%8E%E5%8F%B0%E6%A8%A1%E5%BC%8F%E5%BC%80%E5%8F%91%E6%8C%87%E5%8D%97.md
iOS7 以后 又增加了几个:后台获取,远程通知的后台处理, URLSession 的后台传输的处理
http://objccn.io/issue-5-5/
iOSer2012
2016-02-19 16:36:15 +08:00
wohenyingyu01
2016-02-19 17:02:51 +08:00
@iOSer2012 我就是看文档说 approximately 5 seconds 的,为什么说不能测试呢?看到了就想去证实一下应该是本能反应吧…我知道如何延长时限,就是想试试被系统结束的极限条件是什么……
wadahana
2016-02-25 15:33:50 +08:00
ios7 以上正常可以活 180s ; ios6 好像是 300 or 600s 忘了。
[[UIApplication sharedApplication] backgroundTimeRemaining] 可以读到还能活多久
后台下载用 NSURLSession
如果只需要激活几次偷偷写数据,用 GPS
wohenyingyu01
2016-02-25 18:01:48 +08:00
@wadahana 老司机!!!谢谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/257648

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX