- (IBAction)buttonPressed:(id)sender
{
UIDevice *device = [UIDevice currentDevice];
device.batteryMonitoringEnabled = YES;
if ([[UIDevice currentDevice] isMultitaskingSupported]) {
[self beingBackgroundUpdateTask];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryStateDidChangeNotification" object:device];
[self currentBatteryState];
}
- (void) beingBackgroundUpdateTask
{
self->backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundUpdateTask];
}];
}
- (void) endBackgroundUpdateTask
{
[[UIApplication sharedApplication] endBackgroundTask: self->backgroundUpdateTask];
self->backgroundUpdateTask = UIBackgroundTaskInvalid;
}由于某些原因,通知没有被遵守。我做错了什么吗?我想在拔下电源后观察10分钟
发布于 2012-07-08 01:45:36
您不应该在buttonPressed:方法中调用endBackgroundUpdateTask,因为这会取消您的后台任务。尝试删除此代码:
if ([[UIDevice currentDevice] isMultitaskingSupported]) {
[self endBackgroundUpdateTask];
}此外,您应该将UIDeviceBatteryLevelDidChangeNotification常量传递给"name“参数,而不是字符串。它应该看起来像这样(注意没有双引号):
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:device];(也有可能UIDevice根本不会在后台发送这些通知。)
发布于 2012-07-08 01:35:28
您是否已将适用的背景代码添加到您的AppDelegate?下面是《iOS编程指南》中的背景instructions
https://stackoverflow.com/questions/11377186
复制相似问题