iPhone4 how to find out if the power cable is plugged in?

こ雲淡風輕ζ 提交于 2019-12-04 13:34:25

问题


I would like to know if my app is running with an external power cable attached. Is it possible to find out this state at runtime?

An extra question: would this be able to differentiate between true USB power and those external "battery packs"?

Thank you!


回答1:


Use UIDevice property batteryState:

[[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateCharging

From UIDevice Docs:

typedef enum {
    UIDeviceBatteryStateUnknown,
    UIDeviceBatteryStateUnplugged,
    UIDeviceBatteryStateCharging,
    UIDeviceBatteryStateFull,
} UIDeviceBatteryState;

As for your 2nd question. I don't believe you can determine any difference between a battery pack and a wall charger since the above UIDeviceBatteryState flags are the only "states" a device battery can report. So both a battery pack and wall charger would appear as either UIDeviceBatteryStateCharging or UIDeviceBatteryStateFull (or UIDeviceBatteryStateUnplugged if the battery pack is plugged in but out of juice).




回答2:


You can detect whether the battery is charging, but that's as close as you can get with existing APIs – there's no way to detect where the power is "coming from", so to speak.

UIDeviceBatteryState batteryState = [UIDevice currentDevice].batteryState;
if (batteryState == UIDeviceBatteryStateCharging) {
    // Your code here
}



回答3:


I had to include the line,

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

or else batteryState only returns UIDeviceBatteryStateUnknown. Perhaps this became necessary since this question was initially asked and answered. I found the tip here: Determine accurate iPhone battery level.



来源:https://stackoverflow.com/questions/7924368/iphone4-how-to-find-out-if-the-power-cable-is-plugged-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!