简体   繁体   English

iPhone4如何查看电源线是否已插入?

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

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"? 一个额外的问题:这是否能够区分真正的USB电源和那些外部“电池组”?

Thank you! 谢谢!

Use UIDevice property batteryState : 使用UIDevice属性batteryState

[[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateCharging

From UIDevice Docs : 来自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. 我不相信你可以确定电池组和壁式充电器之间的任何区别,因为上述UIDeviceBatteryState标志是设备电池可以报告的唯一“状态”。 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). 所以无论电池组和壁式充电器将表现为任一UIDeviceBatteryStateChargingUIDeviceBatteryStateFull (或UIDeviceBatteryStateUnplugged如果电池组中,但出汁堵塞)。

I had to include the line, 我不得不包括这条线,

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

or else batteryState only returns UIDeviceBatteryStateUnknown. 或者batteryState只返回UIDeviceBatteryStateUnknown。 Perhaps this became necessary since this question was initially asked and answered. 也许这是必要的,因为这个问题最初是被问到和回答的。 I found the tip here: Determine accurate iPhone battery level . 我在这里找到了提示: 确定准确的iPhone电池电量

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. 您可以检测电池是否正在充电,但这与现有API一样接近 - 没有办法检测电源“来自哪里”,可以这么说。

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

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

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