在iphone上运行的后台任务

时间:2012-06-14 13:54:36

标签: iphone ios5 ios4 multitasking

我有一些测试代码用于保持我的应用程序在后台状态下保持运行,这在iOS 5.1模拟器上运行良好,但在实际设备上却没有那样。

现在我已经知道了我必须遵循的要求, 所以我为voip和location设置了“后台模式”。

在我的委托的applicationDidEnterBackground方法中,我调用以下函数 我称之为“doBackgroundActivity()” 请求申请时间在后台完成一些长期运行的任务:

-(void) threadedMethod{    
while(true){
    NSLog(@"looping");            
    [self showLocalNotification:@"This notification will come every 2 min. if the app is running in background. Close it!"];        
    [NSThread sleepForTimeInterval: (5)];        // 60 sec = 1 min
}

}

    -(void) doBackgroundActivity{
        self->_backgroundTask = [ [UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ 
                [[UIApplication sharedApplication] endBackgroundTask: self->_backgroundTask];
                self->_backgroundTask = UIBackgroundTaskInvalid;
            }
        ];


        [self threadedMethod];



[[UIApplication sharedApplication] endBackgroundTask:self->_backgroundTask];
    self->_backgroundTask = UIBackgroundTaskInvalid;
}

如您所见,doBackgroundAcitivity()只调用threadedMethod(),所做的就是运行一个无限循环,每隔5秒左右发送一次本地通知。

现在在模拟器中运行此操作并最小化应用程序时,我会每隔5秒左右看到一次通知。即使我运行其他应用程序,我看到我的应用程序发送通知,应用程序仍在后台运行。

但这不会发生在设备上。看起来操作系统在发送第一个通知后立即杀死应用程序,我不会再看到我希望稍后看到的更多后续通知?

我还需要做些什么来保持应用程序在后台运行吗?

1 个答案:

答案 0 :(得分:0)

如果您要查看的所有内容都是在您的应用关闭时向用户发出通知,则应使用UILocalNotifications

您可以设置通知何时触发,以及是否应重复通知,以及重复之间的时间量。

作为旁注,我不建议在循环中使用sleep()来控制何时执行代码,因为它会阻止线程执行任何操作,并且对于任何其他想要执行的任务都不好使用那个线程。相反,你应该使用NSTimers,以及控制代码执行时间的其他方法。