1
- (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 分钟

4

2 回答 2

1

您不应该调用endBackgroundUpdateTask您的buttonPressed:方法,因为这会取消您的后台任务。尝试删除此代码:

if ([[UIDevice currentDevice] isMultitaskingSupported]) {
    [self endBackgroundUpdateTask];
}

此外,您应该将UIDeviceBatteryLevelDidChangeNotification常量传递给“name”参数,而不是字符串。它应该看起来像这样(注意缺少双引号):

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:device];

(也有可能 UIDevice 根本不会在后台发送这些通知。)

于 2012-07-07T17:45:36.083 回答
0

您是否已将适用的后台代码添加到您的 AppDelegate?以下是iOS 编程指南中的背景说明

于 2012-07-07T17:35:27.833 回答