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

You shouldn't be calling endBackgroundUpdateTask in your buttonPressed: method, since that cancels your background task. Try removing this code:

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

Also, you should pass the UIDeviceBatteryLevelDidChangeNotification constant to the "name" parameter, not the string. It should look like this (note the lack of double quotes):

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

(It's also possible that UIDevice simply doesn't send those notifications in the background.)

于 2012-07-07T17:45:36.083 に答える
0

該当するバックグラウンド コードを AppDelegate に追加しましたか? iOS プログラミング ガイドのバックグラウンド設定手順は次のとおりです。

于 2012-07-07T17:35:27.833 に答える