ios - 如何获得正确的电池电量和电池状态-ios?

标签 ios objective-c uidevice

始终 [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/

相关文章:

ios - 如何在 iOS 中获取电池温度详细信息?

ios - 我应该把功能放在哪里?

iphone - iOS app拍照后是否可以避开 "use"/"retake"画面?

iphone - iOS 中的后台 GPS。这可能吗?

ios - 无法打开 xcode,因为它是 future 格式

php - Mysql php 和 Objective c 之间的通信

ios - 无法在 iOS 应用程序中通过谷歌正确转换视频

ios - 如何创建对角线切割 View 以在配置文件屏幕中使用?

ios - 如何从 swift 文件调用用 Objective C 编写的 Web 服务

iphone - 如何检测 iPad 上启动屏幕动画的应用程序启动方向!