始终 [myDevice batteryLevel]
返回 -1 和 [myDevice batterystate]
返回 0(进入默认情况)。
我怎样才能得到正确的值?任何人都可以帮我解决这个问题吗?下面是我的代码。(始终将 batteryLeft 打印为“-100%”,将电池状态打印为“未知”)。
代码:
UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
float batLeft = [myDevice batteryLevel]*100;
int status=[myDevice batteryState];
NSLog(@"level:%0.0f",batLeft);
NSString *status_str;
switch (status)
{
case UIDeviceBatteryStateUnplugged:
{
NSLog(@"UnpluggedKey");
status_str=@"UnPlugged";
break;
}
case UIDeviceBatteryStateCharging:
{
NSLog(@"ChargingKey");
status_str=@"Charging";
break;
}
case UIDeviceBatteryStateFull:
{
NSLog(@"FullKey");
status_str=@"BatteryFul";
break;
}
default:
{
NSLog(@"UnknownKey");
status_str=@"Unknown";
break;
}
}
NSLog(@"Battery status:%@",status_str);
最佳答案
您的代码看起来没问题,它与我在我的一个应用程序中使用的代码相同:
-(void) battery
{
UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
int state = [myDevice batteryState];
NSLog(@"battery status: %d",state); // 0 unknown, 1 unplegged, 2 charging, 3 full
double batLeft = (float)[myDevice batteryLevel] * 100;
NSLog(@"battery left: %ld", batLeft);
}
您的问题可能是您在模拟器中尝试了此操作,但它无法正常工作。
在一台真实设备上试用。
关于ios - 如何获得正确的电池电量和电池状态-ios?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30373356/