[英]How to get correct battery level and battery status-ios?
Always [myDevice batteryLevel]
returning -1 and [myDevice batterystate]
returning 0(entering into Default case). 始终
[myDevice batteryLevel]
返回-1并且[myDevice batterystate]
返回0(进入默认情况)。
How can i get the correct values?.Can anyone please help me to solve this?.Below is my code.(Always Printing batteryLeft as "-100%" and Battery Status as "Unknown"). 我怎样才能得到正确的值?。任何人都可以帮我解决这个问题吗?.Below是我的代码。(始终将batteryLeft打印为“-100%”,电池状态为“未知”)。
Code: 码:
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);
Your code looks to be ok, it's the same that I used in one of my app: 你的代码看起来没问题,就像我在我的应用程序中使用的一样:
-(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);
}
Your problem can be that you try this in the simulator, where it can't be work. 您的问题可能是您在模拟器中尝试此操作,它无法正常工作。
Try on one real device. 试试一个真实的设备。
I hope you are not checking it on your simulator :) 我希望你不要在你的模拟器上检查它:)
You will not get exact battery level of your device , its always in multiple of 0.05. 您将无法获得设备的准确电池电量,它始终为0.05的倍数。 That means if your device battery level is 78% then it will show 75%.
这意味着如果您的设备电池电量为78%,那么它将显示75%。
if you want exact battery level indication then you can follow this link : http://blog.coriolis.ch/2009/02/14/reading-the-battery-level-programmatically/ 如果你想要精确的电池电量指示,那么你可以点击这个链接: http : //blog.coriolis.ch/2009/02/14/reading-the-battery-level-programmatically/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.