简体   繁体   English

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

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

I want to get battery usage data from my iPhone. 我想从iPhone中获取电池使用情况数据。 I used UIDevice currentDevice.batteryLevel code, but its returning -1.0000 in NSLog value. 我使用了UIDevice currentDevice.batteryLevel代码,但其NSLog值返回-1.0000。

Anyone please help me? 有人帮我吗

One more question, can I able to fetch other app battery usages in my app? 还有一个问题,我可以在我的应用程序中获取其他应用程序的电池使用情况吗?

First, you must enable batteryStatus notification (in appDelegate.m for instance): 首先,您必须启用batteryStatus通知(例如,在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];
    ...
}

Then, you can check battery level calling: 然后,您可以检查电池电量调用:

[UIDevice currentDevice].batteryLevel;

that will return you a value between 0.0 (0% chareg) and 1.0 (100% charge). 这将为您返回0.0(0%字符)和1.0(100%电荷)之间的值。

Without calling first setBatteryMonitoringEnabled , battery state will return UIDeviceBatteryStateUnknown and the value of this property is –1.0. 如果不先调用setBatteryMonitoringEnabled ,则电池状态将返回UIDeviceBatteryStateUnknown并且此属性的值为–1.0。 (from docs). (来自docs)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM