Monitoring iPhone4 iOS5 battery level I need to add setBatteryMonitoringEnabled: NO to periodic battery checks?

I have launched an application that shows the data of the accelerometer and gyroscope in one night. This is a very intensive battery operation, and I would like to teach my application to recognize when the battery is running low.

Here is my prototype code that checks the battery level every 10 minutes

NSDate* date = [NSDate date]; if((int)([date timeIntervalSinceReferenceDate])%600 == 0) { UIDevice *myDevice = [UIDevice currentDevice]; [myDevice setBatteryMonitoringEnabled:YES]; float batLeft = [myDevice batteryLevel]; int batinfo=(batLeft*100); [self postStatusMessageWithTitle:nil description:[NSString stringWithFormat:@"%@ battery level: %i",[dateFormat stringFromDate:dateShow],batinfo]]; [myDevice setBatteryMonitoringEnabled:NO]; } 

My question is this: do I need to add this line to the end of the code:

 [myDevice setBatteryMonitoringEnabled:NO]; 

It seems that the battery check is done right there, there are no asynchronous delegate calls. Will it set NO without any battery saving if you don't control the battery level during the night? Will I break something by setting it to NO?

Thanks for any input!

+3
source share
1 answer

It is generally believed that it is better to avoid polling and instead request notifications from the system, for example:

 [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryLevelUpdate) name:UIDeviceBatteryLevelDidChangeNotification object:nil]; 

... where batteryLevelUpdate will look like this:

 - (void)batteryLevelUpdate:(NSNotification *)notification { // do whatever, using: [[UIDevice currentDevice] batteryLevel] } 

From the Link to the UIDevice class :

Notifications about changes in battery level are sent no more than once per minute. Do not try to calculate the drainage rate of the battery or the remaining battery life; drainage speed can often change depending on the built-in applications, as well as on your application.

Once a minute, 10 times more often than your code currently checks with less CPU time. It is not mentioned, however, what degree of detail of the changes will lead to notifications - is this a change of 0.01% for sending or is a change of 1% required?

To answer another question, if you have to set setBatteryMonitoringEnabled back to NO : if you use notifications, rather than manually polling for the setBatteryMonitoringEnabled battery, then the answer is that you should leave it in YES or the risk of Missing notifications.

Apple's official BatteryStatus sample uses the same battery status report.

There is also a UIDeviceBatteryStateDidChangeNotification that will notify you when the device is discharged (in use), charged or fully charged.

+11
source

All Articles