【发布时间】:2013-04-08 12:12:00
【问题描述】:
我正试图让我的应用程序在后台运行超过 10 分钟,根据这个和我下面的好处。 (我想使用长时间后台运行来跟踪位置,我这里的代码只是使用计数器进行测试) 任何人都可以帮助指出问题所在?
实现长时间运行的后台任务
对于需要更多执行时间来执行的任务,您必须 请求特定权限以在后台运行它们,而无需 他们被停职。在 iOS 中,只允许特定的应用类型 在后台运行:
在后台向用户播放可听内容的应用, 比如音乐播放器应用
让用户随时了解其位置的应用,例如 一个导航应用
支持互联网协议语音 (VoIP) 的应用
需要下载和处理新内容的报亭应用程序 接收来自外部附件的定期更新
实现这些服务的应用必须声明它们所使用的服务 支持和使用系统框架来实现相关方面 那些服务。声明服务让系统知道哪个 您使用的服务,但在某些情况下,它是系统框架 实际上可以防止您的应用程序被暂停。
- (void)viewDidLoad {
[super viewDidLoad];
counterTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:^{
}];
count=0;
theTimer=[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(countUp)
userInfo:nil
repeats:YES];
}
- (void)countUp {
{
count++;
NSString *currentCount;
currentCount=[[NSString alloc] initWithFormat:@"%ld",count];
theCount.text=currentCount;
[currentCount release];
}
}
另一个问题:我可以让 iOS 应用在后台永远运行吗?
----添加位置的编辑代码,仍然没有运行超过10分钟,对我做错了什么有帮助吗?
- (void)viewDidLoad {
[super viewDidLoad];
count=0;
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
counterTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:^{
// If you're worried about exceeding 10 minutes, handle it here
[locationManager startUpdatingLocation];
}];
theTimer=[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(countUp)
userInfo:nil
repeats:YES];
}
(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(@"OldLocation %f %f", oldLocation.coordinate.latitude, oldLocation.coordinate.longitude); NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
count++; NSString *currentCount;
currentCount=[[NSString alloc] initWithFormat:@"%ld",count];
theCount.text=currentCount; [currentCount release];
}
(void)countUp { [locationManager startUpdatingLocation];
{ count++; NSString *currentCount;
currentCount=[[NSString alloc] initWithFormat:@"%ld",count];
theCount.text=currentCount;
[currentCount release]; } }
【问题讨论】:
-
如果您的应用程序不属于这些类别之一,那么您已经指定了可以在后台运行的应用程序,那么如果运气好的话,您就出局了。不是没有办法让你的应用程序永远在后台运行。 Apple 不会允许这样做,因为它会缩短电池寿命。作为用户,我也不想要这样的应用程序。为什么你的应用需要一直运行???
-
当我测试代码后台任务仅停留 10 分钟时,它确实属于特定类别(让用户始终了解其位置的应用程序,例如导航应用程序),我应该也使用该位置进行测试,而不仅仅是计数器?
-
如果你的应用在后台使用位置,你应该启动
CLLocationManager来接收主要的位置变化。然后,当用户更改位置时,您的应用会收到通知。 -
谢谢,现在测试一下,告诉你会发生什么
-
rckoenes,我用包含 cllocation 的新代码编辑了问题,请帮助我做错了什么,谢谢
标签: ios objective-c background background-process