New In iPhone 3.0 Tutorial Series, Part 5: Battery Monitoring

By
On July 27, 2009

If you read last week’s New in iPhone 3.0 post on proximity monitoring then this week’s post on battery monitoring is a gimme.

Like proximity monitoring, battery monitoring is enabled by setting to YES a property of the UIDevice singleton:

UIDevice *device = [UIDevice currentDevice];
device.batteryMonitoringEnabled = YES;

iPhone OS provides two type of battery monitoring events, one for when the state changes (e.g., charging, unplugged, full charged) and one that updates when the battery’s charge level changes. As was the case with proximity monitoring, you register callbacks to receive notifications:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:@"UIDeviceBatteryStateDidChangeNotification" object:device];

The battery level notification is apparently triggered at 5% intervals.

To test the behavior, I created a throwaway app (source: github, zip) that writes the battery state and charge level to a table view and the console whenever a notification occurs.

An aside: you can view a limited set of NSLog outputs that are issued while disconnected after you reconnect under the Console tab in Xcode’s Organizer window.

I left the phone unplugged and with the app running and waited for a battery level change notification. The phone only triggered a notice after the battery had drained from full to 95%, and again at 90%.

When I plugged the phone back in the change battery level change notifications occurred at even 5% steps as well.

Seattle Beginning iPhone Programming Workshop: August 20-21. Only $799 with “mo” coupon code and early registration. Hurry: early reg ends Friday!

0 responses to “New In iPhone 3.0 Tutorial Series, Part 5: Battery Monitoring”

  1. Maniacdev says:

    Nice tutorial, very direct, thank you Dan. The 5% thing is unfortunate. I hadn’t looked into this functionality, but saw all the battery monitoring apps in the app store suffer from this condition, and now I know why.

  2. alones says:

    But.. as many developers know, this monitoring is not correct. just proximity. Using IOKit lib is more precise even though the way would not be allowed by Apple.