2012-07-07 110 views
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分鐘iOS MultiTasking無法正常工作

回答

1

您不應該在buttonPressed:方法中調用endBackgroundUpdateTask,因爲這會取消您的後臺任務。嘗試刪除此代碼:

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

此外,你應該在UIDeviceBatteryLevelDidChangeNotification不斷傳遞到「名」參數,而不是字符串。它應該是這樣的(注意沒有雙引號):

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

(這也有可能是的UIDevice根本不會在後臺發送的通知。)

+0

如何確定UIDevice是否在後臺發送通知? – 2012-07-07 17:52:09

+0

我會嘗試修復我先建議的兩件事,然後測試以查看這些通知是否在後臺到達。 – 2012-07-07 17:53:43

+0

我根據您的建議修改了代碼。它似乎沒有工作 – 2012-07-07 17:54:36

0

您是否已將適用的後臺代碼添加到AppDelegate?這裏有背景知識在iOS編程指南中使用instructions

+0

我看到的文件,並沒有明白它。我在AppDelegate中做什麼,以及如何將其鏈接到ViewController中的方法? – 2012-07-07 17:53:13