在我的Codename One应用程序中,我使用以下iOS本机代码来了解电池是充电还是已满:
-(BOOL)isCharging{
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
if ( ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateCharging)
|| ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateFull) ) {
return YES;
}
else {
return NO;
}
}
I Codename One部分我每1000毫秒轮询一次,如果电池正在充电。它在Android上完美运行。但是在iOS上,保持初始状态(即启动应用程序时)并且即使电池状态发生变化也不会更新(插入/拔出插头,反之亦然)。
因此,如果我使用插入的电缆启动应用isCharging
,则返回YES
(在java中为true)但如果我拔出电缆,isCharging
会一直返回YES
。如果我关闭应用并使用已拔下的电缆启动它,isCharging
将返回NO
,当我插入电缆时永远不会转到YES
,尽管左上角的iOS工具栏显示充电电池。
请注意:测试是在iPhone 4上进行的
如果电池状态发生变化,该怎么让方法更新?
任何帮助表示赞赏,
答案 0 :(得分:1)
在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.batteryState
IIRC,它会在每次更换功率时发送通知,并且每当设备更换时都会发送电源。
请务必取消订阅:
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)
}
答案 1 :(得分:0)
谢谢大家的答案。事实上,正如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;
}
现在应用程序运行正常!