我按照https://developer.apple.com/library/ios/samplecode/BatteryStatus/Introduction/Intro.html中的示例为我的VOIP应用程序构建了一个电池监视器。
开始:
// Subscribe to battery level and battery state changes
CFNotificationCenterAddObserver( CFNotificationCenterGetLocalCenter( ), // center
this, // observer
&NotificationHandler, // callback
(CFStringRef)UIDeviceBatteryLevelDidChangeNotification, // name
NULL, // object
CFNotificationSuspensionBehaviorDeliverImmediately ); // suspensionBehavior
CFNotificationCenterAddObserver( CFNotificationCenterGetLocalCenter( ), // center
this, // observer
&NotificationHandler, // callback
(CFStringRef)UIDeviceBatteryStateDidChangeNotification, // name
NULL, // object
CFNotificationSuspensionBehaviorDeliverImmediately ); // suspensionBehavior
// Enable battery monitoring. This is required to fetch battery state and level.
dispatch_async(dispatch_get_main_queue(), ^{
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
});
停止:
// Disable battery monitoring
dispatch_async(dispatch_get_main_queue(), ^{
[[UIDevice currentDevice] setBatteryMonitoringEnabled:NO];
});
// Unsubscribe from battery level and battery state changes
CFNotificationCenterRemoveObserver( CFNotificationCenterGetLocalCenter( ), // center
this, // observer
(CFStringRef)UIDeviceBatteryLevelDidChangeNotification, // name
NULL ); // object
CFNotificationCenterRemoveObserver( CFNotificationCenterGetLocalCenter( ), // center
this, // observer
(CFStringRef)UIDeviceBatteryStateDidChangeNotification, // name
NULL ); // object
我在不同时间启动/停止电池监视器。有时我发现,如果我在启用电池监视器后立即查询电池状态,我将获得未知状态和电池电量为-1%。
BatteryState batteryState = BATTERY_STATE_UNKNOWN;
switch ( nativeBatteryState )
{
case UIDeviceBatteryStateUnplugged:
batteryState = BATTERY_STATE_UNPLUGGED;
break;
case UIDeviceBatteryStateCharging:
batteryState = BATTERY_STATE_CHARGING;
break;
case UIDeviceBatteryStateFull:
batteryState = BATTERY_STATE_FULL;
break;
case UIDeviceBatteryStateUnknown:
default:
PEX_ASSERT_MSG(nativeBatteryState == UIDeviceBatteryStateUnknown, STREAM_ADHOC( nativeBatteryState ) );
break;
}
// Map native battery level to unsigned short
unsigned short batteryLevel = 0;
if ( batteryState != BATTERY_STATE_UNKNOWN )
{
// Only read battery level if state is known ...
// The native battery level ranges from 0.0 (fully discharged) to 1.0 (100% charged).
// If battery monitoring is not enabled, battery level is –1.0.
float nativeBatteryLevel = [[UIDevice currentDevice] batteryLevel];
PEX_ASSERT_MSG( nativeBatteryLevel >= 0.0 && nativeBatteryLevel <= 1.0, STREAM_ADHOC( nativeBatteryLevel ) );
batteryLevel = static_cast<unsigned short>( nativeBatteryLevel * 100 );
}
在查询实际电池值之前需要一段时间吗?此外,当我的应用程序在后台时,我会更频繁地看到这一点。我有一个VOIP应用程序,我已根据需要在info.plist中启用它。
答案 0 :(得分:0)
问题是由于:
dispatch_async(dispatch_get_main_queue(),^ { [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; });
是异步的。在我将其同步后,它的表现正如预期的那样。