通常认为最好的做法是避免轮询,而是请求系统通知,如下所示:
[[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 类参考 http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIDevice_Class/Reference/UIDevice.html#//apple_ref/doc/uid/TP40006902-CH3-SW20:
电池电量变化通知的发送频率不超过每分钟一次。请勿尝试计算电池消耗率或电池剩余时间;排水率可能会经常变化,具体取决于内置应用程序以及您的应用程序。
每分钟一次的频率比您的代码当前检查的频率高 10 倍,同时在 CPU 方面的工作量要少得多。确实如此not但是请注意,什么粒度的更改会导致通知 - 是要发送 0.01% 的更改,还是需要 >1% 的更改?
要回答您的其他问题,如果您应该设置setBatteryMonitoringEnabled
回到NO
:如果您正在使用通知而不是手动轮询电池状态,那么答案是您必须将其保留在YES
,否则可能会错过通知。
苹果官方BatteryStatus示例代码 http://developer.apple.com/library/ios/#samplecode/BatteryStatus/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008812-Intro-DontLinkElementID_2对电池状态报告使用相同的方法。
还有一个UIDeviceBatteryStateDidChangeNotification
当设备正在放电(使用中)、充电或已充满电时,它会通知您。