检测设备是否正在充电

ada*_*dam 30 iphone

我用我最喜欢的工具找不到任何明确的东西,但是我想我会把它放在这里......

有没有办法,使用iPhone SDK,应用程序检测设备是否处于接收电源状态(充电,停靠等)?

我希望能够在设备接通电源时自动禁用idleTimer(否则它是用户指定的设置).

Bra*_*rad 44

你最好使用:

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

if ([[UIDevice currentDevice] batteryState] != UIDeviceBatteryStateUnplugged) {
      [UIApplication sharedApplication].idleTimerDisabled=YES;
    }
Run Code Online (Sandbox Code Playgroud)

这是因为您必须关注 两种不同的状态 - 一种是电池正在充电,另一种是充满电时.

如果您真的想完成它 - 您将注册接收电池监控通知,因此如果用户断开主电源等,您可以重新启用空闲计时器.


Ala*_*art 35

是的,UIDevice能够告诉你:

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

if ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateCharging) {
    NSLog(@"Device is charging.");
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息以及batteryState的其他值,请参阅文档中的UIDevice参考.


Ode*_*gev 7

斯威夫特4

UIDevice.current.isBatteryMonitoringEnabled = true

if (UIDevice.current.batteryState != .unplugged) {
    print("Device is charging.")
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特3

UIDevice.currentDevice().batteryMonitoringEnabled = true;

if (UIDevice.currentDevice().batteryState != .Unplugged) {
    print("Device is charging.");
}
Run Code Online (Sandbox Code Playgroud)


UpS*_*ler 6

斯威夫特3:

UIDevice.current.isBatteryMonitoringEnabled = true
let state = UIDevice.current.batteryState

if state == .charging || state == .full {
    print("Device plugged in.")
}
Run Code Online (Sandbox Code Playgroud)