在我的代号为One的应用程序中,我求助于以下iOS原生代码来了解电池是否正在充电或充满:
-(BOOL)isCharging{
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
if ( ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateCharging)
|| ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateFull) ) {
return YES;
}
else {
return NO;
}
}如果电池正在充电,代号为每1000毫秒轮询一次。它在Android上运行得很好。然而,在iOS上,初始状态(即应用程序启动时)会保持不变,即使电池状态发生变化(插/拔,反之亦然),它也不会更新。
因此,如果我在插入电缆的情况下启动应用程序,isCharging将返回YES (在java中为true),但如果我拔出电缆,isCharging将一直返回YES。如果我关闭应用程序并使用未插入的电缆启动它,当我插入电缆时,isCharging将返回NO,并且永远不会转到YES,尽管左上角的iOS工具栏显示正在充电的电池。
请注意:测试是在iPhone 4上进行的
当电池状态改变时,我该怎么做才能使该方法更新它的值?
感谢您的任何帮助,
发布于 2017-11-03 05:45:33
在iOS中,您可以订阅系统通知。我把我的放在了我的应用程序代理中。
func applicationDidBecomeActive(_ application: UIApplication) {
NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.batteryChangeLevel), name: NSNotification.Name.UIDeviceBatteryLevelDidChange, object: UIDevice.current)
NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.batteryChangeState), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: UIDevice.current)
}从那里你可以相应地检查状态和反应。
UIDevice.current.batteryLevel
UIDevice.current.batteryStateIIRC,它会在每次电源更改%和设备更改插入电源时发送通知。
请务必取消订阅:
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceBatteryLevelDidChange, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil)
}发布于 2017-11-03 17:34:37
感谢你们所有人的回答。事实上,正如Shai指出的那样,本机代码不是在UI线程上运行的。以下代码向UI线程发出信号,表明电池状态检查(在后台块中完成)已结束:
-(BOOL)isCharging{
// The variable will be used in a block
// so it must have the __block in front
__block BOOL charging = NO;
// We run the block on the background thread and then returns to the
// UI thread to tell the check is over.
dispatch_async(dispatch_get_main_queue(), ^{
// If monitoring is already enabled we dont enable it again
if ( ![[UIDevice currentDevice] isBatteryMonitoringEnabled]) {
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
}
if ( ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateCharging)
|| ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateFull) ) {
charging = YES;
}
else {
charging = NO;
}
});
return charging;
}现在应用程序运行正常了!
https://stackoverflow.com/questions/47084884
复制相似问题