如何在 ios 中获取我的设备的电池使用情况和电量

how to fetch battery usage and level of my devices in ios

我想从 iPhone 获取电池使用数据。我使用了 UIDevice currentDevice.batteryLevel 代码,但它在 NSLog 值中返回 -1.0000。

有人帮帮我吗?

还有一个问题,我可以在我的应用中获取其他应用的电池使用情况吗?

首先,您必须启用电池状态通知(例如 appDelegate.m):

- (void)applicationDidBecomeActive:(UIApplication *)application {
    ...
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
    // Now, the system will post UIDeviceBatteryStateDidChangeNotification notification when batteryStatus (or connection) will change

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStatusDidChange:) name:UIDeviceBatteryStateDidChangeNotification object:nil];
    ...
}

然后,您可以查看电池电量调用:

[UIDevice currentDevice].batteryLevel;

这将 return 您的值介于 0.0(0% 充电)和 1.0(100% 充电)之间。

如果不先调用 setBatteryMonitoringEnabled,电池状态将 return UIDeviceBatteryStateUnknown 并且此 属性 的值为 –1.0。 (来自文档)。