我正在尝试在我的应用程序中启用后台位置模式。我在plist文件中启用了“位置更新”后台模式。 该应用程序包含一个每15秒更新一次的计时器。
当应用导航到后台时,我正在执行以下操作
- (void)applicationDidEnterBackground:(UIApplication *)application {
UIApplication* app = [UIApplication sharedApplication];
self.bgTaskID = [app beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"background task %lu expired", (unsigned long)self.bgTaskID);
[app endBackgroundTask:self.bgTaskID];
self.bgTaskID = UIBackgroundTaskInvalid;
}];
[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(initializeLocationManager) userInfo:nil repeats:NO];
if(self.timerLocationBackground)
{
[self.timerLocationBackground invalidate];
self.timerLocationBackground = nil;
}
self.timerLocationBackground = [NSTimer scheduledTimerWithTimeInterval:15
target:self
selector:@selector(initializeLocationManager)
userInfo:nil
repeats:YES];}`
initializeLocationManager位于
之下 -(void)initializeLocationManager
{
if(!self.locationManager)
self.locationManager = [[CLLocationManager alloc] init];
else
[self.locationManager stopUpdatingLocation];
if ((![CLLocationManager locationServicesEnabled])
|| ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusRestricted)
|| ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied))
{
//user has disabled his location
}
else
{
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
[self.locationManager startUpdatingLocation];
}
}
当我在10分钟之后导航回应用程序时,我的计时器将在3分钟停止,这是该应用程序暂停的时间。
应用程序返回前台时的代码如下:
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
//
//Remove the baground task
//
if (self.bgTaskID != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:self.bgTaskID];
self.bgTaskID = UIBackgroundTaskInvalid;
}
[self.locationManager stopUpdatingLocation];
任何帮助?
答案 0 :(得分:0)
应该是这样的。我已经切换到了自己,所以我的目标-c可能并不完美。
- (void)applicationDidEnterBackground:(UIApplication *)application {
[self keepAwakeInBackground ] ;
/// rest of your function to set up timers
}
- (void) keepAwakeInBackground {
//Remove the old background task, if there was one
if (self.bgTaskID != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:self.bgTaskID];
self.bgTaskID = UIBackgroundTaskInvalid;
}
/*
* You probably want something here to decide that the app should really be suspended here
* if ( ) return
*/
// Set up new background task
UIApplication* app = [UIApplication sharedApplication];
self.bgTaskID = [app beginBackgroundTaskWithExpirationHandler:^{
[self keepAwakeInBackground]
}];
}