电池状态总是无效

时间:2013-06-26 19:42:18

标签: ios uidevice batterylevel

我有以下方法可正确返回电池电量,但无法获得电池状态。它总是返回UNKNOWN。

-(NSString *)batteryStatus
{
UIDevice *device = [UIDevice currentDevice];
NSString *batteryStateString = nil;
switch(device.batteryState)
{
    case UIDeviceBatteryStateUnplugged: batteryStateString = @"Unplugged"; break;
    case UIDeviceBatteryStateCharging: batteryStateString = @"Charging"; break;
    case UIDeviceBatteryStateFull: batteryStateString = @"Full"; break;
    default: batteryStateString = @"Unknown"; break;
}

[device setBatteryMonitoringEnabled:YES];
NSString *statusString = [NSString stringWithFormat:@"Level - %d%% - State - %@",
                          (int)round(device.batteryLevel * 100), batteryStateString];
[device setBatteryMonitoringEnabled:NO];
return statusString;
}

如何从UIDevice返回正确的电池状态?

1 个答案:

答案 0 :(得分:9)

尝试在切换前移动此行。

[device setBatteryMonitoringEnabled:YES];

默认禁用电池监控会阻止您正确读取电池状态。