[英]Start thread when iOS application enters background state
I have a Requirement where I need to Create and Start a thread when application enters the Background State. 我有一个要求,当应用程序进入后台状态时,需要在其中创建和启动线程。 The function of the Created Thread is to fetch data from local DB and upload to server, and I don't need to do any updates on UI. Created Thread的功能是从本地数据库获取数据并上传到服务器,并且我不需要在UI上进行任何更新。 My questions are: 我的问题是:
applicationWillResignActive
method or in applicationDidEnterBackground
? 我到底应该在哪里创建线程-在applicationWillResignActive
方法中还是在applicationDidEnterBackground
? The things I've tried 我尝试过的东西
I just tried the with NSThread concept, but it was not working. 我只是尝试使用NSThread概念,但是它不起作用。 Below is code that I wrote to the best of my knowledge: 以下是据我所知编写的代码:
- (void)applicationWillResignActive:(UIApplication *)application { [NSThread detachNewThreadSelector:@selector(FetchReportFromDBAndUpload) toTarget:self withObject:nil]; } - (void)FetchReportFromDBAndUpload { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; //Check for internet connection and fetch data from DB and upload to server [pool release]; }
Is this correct way of creating the thread, or do I need to do some changes? 这是创建线程的正确方法,还是我需要进行一些更改? If not please guide me how to achieve this. 如果没有,请指导我如何实现。 Thanks in advance 提前致谢
You must call the beginBackgroundTaskWithExpirationHandler:
method of the UIApplication
class from the AppDelegate's applicationDidEnterBackground:
method. 您必须从AppDelegate的applicationDidEnterBackground:
方法调用UIApplication
类的beginBackgroundTaskWithExpirationHandler:
applicationDidEnterBackground:
方法。 This method marks your task as a background task so the system will not kill it when the app enters background state. 此方法将您的任务标记为后台任务,因此当应用程序进入后台状态时,系统不会将其杀死。 (Note that background tasks that are not related to VoiceIP, playing music, GPS tracking are still limited to more or less 10 minutes of background execution time, ie. they don't run forever.) (请注意,与VoiceIP,播放音乐,GPS跟踪无关的后台任务仍被限制为大约10分钟的后台执行时间,即它们不会永远运行。)
Here's more detailed information and a code example: http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html 这里是更详细的信息和代码示例: http : //developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.