2013-04-23 105 views
0

我想在iOS中顯示我的設備的電池狀態。獲取ios中每次更改的電池狀態

我在寫下面的代碼來顯示電池狀態。

UIDevice *myDevice = [UIDevice currentDevice]; 

[myDevice setBatteryMonitoringEnabled:YES]; 
double batLeft = (float)[myDevice batteryLevel] * 100; 
NSLog(@"%.f",batLeft); 
NSString * levelLabel = [NSString stringWithFormat:@"%.f%%", batLeft]; 
lblLabel.text =levelLabel; 

它在應用程序運行時顯示電池狀態正常。但是,當應用程序處於後臺時,它不會獲取更新後的值。我想每次顯示設備的電池狀態。電池在2%到3%之間死亡時,我也想發出通知。

回答

1

以下是每秒鐘檢查電池的示例。您需要檢查電池狀態何時發生變化,但我認爲您的當前代碼在viewDidLoad中只能讀取一次。

- (void)viewDidLoad { 
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(checkBattery) userInfo:nil repeats:YES]; 
} 



- (void)checkBattery { 

    [myDevice setBatteryMonitoringEnabled:YES]; 
    double batLeft = (float)[myDevice batteryLevel] * 100; 
    NSLog(@"%.f",batLeft); 
    NSString * levelLabel = [NSString stringWithFormat:@"%.f%%", batLeft]; 
    lblLabel.text =levelLabel; 

} 
2

爲了實現你想要做什麼你的應用程序,你需要獲得運行背景的權限。應用程序在後臺運行的唯一條件是需要播放背景音頻的應用程序,如音樂播放器或VOIP客戶端。如果這只是一個測試應用程序,並且您不打算通過應用商店發佈它,則可以使用AVAudioSession獲取後臺許可並查詢電池狀態。如果您打算髮布應用程序,則應用程序獲取後臺許可的場景必須使用戶受益。即它必須播放音樂或處理電話。