2011-11-09 89 views
3

我正在運行一個應用程序,可以在一夜之間對加速度計和陀螺儀數據進行採樣。這是一個非常耗電的操作,我想教我的應用程序識別何時電池電量不足。iPhone4的iOS5電池電量監測我需要添加setBatteryMonitoringEnabled:否定期電池檢查?

這裏是我的原型代碼,檢查電池電量,每10分鐘

NSDate* date = [NSDate date]; 
     if((int)([date timeIntervalSinceReferenceDate])%600 == 0) 
      { 
       UIDevice *myDevice = [UIDevice currentDevice]; 
       [myDevice setBatteryMonitoringEnabled:YES]; 
       float batLeft = [myDevice batteryLevel]; 
       int batinfo=(batLeft*100); 

      [self postStatusMessageWithTitle:nil 
           description:[NSString stringWithFormat:@"%@ battery level: %i",[dateFormat stringFromDate:dateShow],batinfo]]; 
       [myDevice setBatteryMonitoringEnabled:NO]; 
      } 

我的問題是:我是否需要加入這一行代碼的末尾:

[myDevice setBatteryMonitoringEnabled:NO]; 

看來,電池檢查是在那裏執行的,沒有異步委託調用。將該值設置爲「否」可以節省電池,因爲無需在一夜之間監控電池電量?將它設置爲NO會破壞什麼?

感謝您的任何意見!

+0

爲什麼不把它設置爲YES,並讓電話在電池充分耗盡時提醒您的應用程序?這並不是不斷進行的投票。 O.S.是有點優化,應該調用委託方法就好了。 –

回答

11

它通常被認爲是避免輪詢,而是要求通知從系統中,像這樣的最佳實踐:

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; 
[[NSNotificationCenter defaultCenter] 
     addObserver:self 
      selector:@selector(batteryLevelUpdate) 
       name:UIDeviceBatteryLevelDidChangeNotification 
      object:nil]; 

...其中batteryLevelUpdate是這樣的:

- (void)batteryLevelUpdate:(NSNotification *)notification 
{ 
    // do whatever, using: [[UIDevice currentDevice] batteryLevel] 
} 

UIDevice Class Reference

電池電量變化通知ar每分鐘發送次數不超過一次。不要嘗試計算電池排水率或剩餘電池剩餘時間;排水率可能會隨着內置應用程序和應用程序的變化而頻繁變化。

每分鐘一次的頻率比當前正在檢查的頻率高出10倍,而CPU處理器的效率更低。它提供而不是,但是更改的粒度會導致通知 - 要發送的變化爲0.01%,還是需要變化> 1%?

爲了回答您的其他問題,如果你要設置setBatteryMonitoringEnabledNO:如果您使用的通知,而不是手動輪詢電池狀態,那麼答案就是你必須離開它YES,或風險缺少的通知。

Apple's official BatteryStatus Sample Code在電池狀態報告中使用相同的參數。

還有一個UIDeviceBatteryStateDidChangeNotification當設備正在放電(使用中),充電或充滿電時會通知您。