I've got problems monitoring battery. In the foreground I can only get the level once and it seems that I don't get the change in the background either.
If I put a new UIViewController in front of the one monitoring and then get back again the battery level is updated.
-(void)startMonitoringBattery
{
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(batteryStateDidChange:)
name:UIDeviceBatteryStateDidChangeNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(batteryLevelDidChange:)
name:UIDeviceBatteryLevelDidChangeNotification
object:nil];
batteryCheckTimer = [NSTimer scheduledTimerWithTimeInterval:(10.0)
target:self
selector:@selector(batteryCheck)
userInfo:nil
repeats:YES];
}
- (void)batteryStateDidChange:(NSNotification *)notification
{
[self batteryCheck];
}
- (void)batteryLevelDidChange:(NSNotification *)notification
{
[self batteryCheck];
}
When this method is called I want to get the current battery level and not the one that it was when I started monitor.
- (void)batteryCheck
{
float STOP_AT_BATTERY_LEVEL = 50.0;
float currentBatteryLevel = [UIDevice currentDevice].batteryLevel;
if([UIDevice currentDevice].batteryLevel <= STOP_AT_BATTERY_LEVEL)
{
// STOP BATTERY CONSUMING TASK
}
}
Questions:
- Why doesn't batteryStateDidChange and batteryLevelDidChange get called more than once?
- Why can't I get the current battery level, with a timer, from [UIDevice currentDevice].batteryLevel even if I've set batteryMonitoringEnabled to true?
- Is it possible to monitor battery while the app is in background or the phone is locked? The app is running in background because I record GPS data all the time.