iOS如何检测电源线是否堵塞

Coc*_*Dev 4 notifications push-notification nsnotificationcenter ios5

我正在制作GPS应用程序,并且根据电源是否可用而改变准确性(即车载充电器)

有没有办法在后台运行一些不断检查设备是否正在接收电源的东西?

我知道如何检查电源是否已连接.但问题是如果用户在家并且已连接.他拔掉设备以便跑出去.然后决定出去玩.我的应用程序在启动时检查电池状态.我怎样才能一次又一次地检查它.我不想耗尽他的电池,因为他正在使用我的应用程序!

我们计划仅支持iOS 5及更高版本(无需向后兼容iOS 4和3)

谢谢

Abi*_*ern 17

看看UIDevice课程参考.

有一个叫做batteryState返回a 的属性UIDeviceBatteryState.因此,要查看设备是否正在充电或已插入并已满.

UIDeviceBatteryState currentState = [[UIDevice currentDevice] batteryState];
if (currentState == UIDeviceBatteryStateCharging || currentState == UIDeviceBatteryStateFull) {
    // The battery is either charging, or connected to a charger and is fully charged
}
Run Code Online (Sandbox Code Playgroud)

编辑添加

如果您想持续监控状态,请查看batteryMonitoringEnabled属性,然后处理UIDeviceBatteryStateDidChangeNotification以更新您想要的任何内容.

iOS是事件驱动的.检查while循环中某些内容的状态是您很少需要做的事情.

  • 请注意,根据[文档](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDevice_Class/Reference/UIDevice.html#//apple_ref/doc/uid/TP40006902-CH3-SW21 ),`batteryState`方法将始终只返回`UIDeviceBatteryStateUnknown`,除非你设置了[`batteryMonitoringEnabled`属性](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDevice_Class/Reference/ UIDevice.html#// apple_ref/doc/uid/TP40006902-CH3-SW39)为"是".(这可能是你遇到@CocoaDev的问题) (4认同)