Calculating battery life in iOS

后端 未结 1 708
攒了一身酷
攒了一身酷 2020-11-27 05:36

Wondering if there are references beyond the Apple tech stats for calculating battery life. I\'ve tried comparing some existing battery apps (battery % left * Apple\'s figur

相关标签:
1条回答
  • 2020-11-27 06:26

    The API allows you to register to receive notifications for changes to the battery level. It only reports a change at 5% increments up or down, but you can use a timer and measure the time between two changes (or initial battery level and first change). Here's how you register for the notifications:

    // Use this call to get the current battery level as a float
    // [[UIDevice currentDevice] batteryLevel]
    
    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(batteryStateDidChange:)
                                                 name:UIDeviceBatteryStateDidChangeNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(batteryLevelDidChange:)
                                                 name:UIDeviceBatteryLevelDidChangeNotification
                                               object:nil];
    

    The first notification tells you the current state, e.g. unplugged, charging, or full. The second will get triggered whenever a 5% increment is reached.

    Seems to me that if all you're given is change notifications at 5% changes up or down, accuracy is not something you can calculate very well or quickly. A 5% change could take a very long time if the device isn't doing anything.

    Maybe you can monitor [[UIDevice currentDevice] batteryLevel] with a timer, however, while I haven't tried it I think it only gets updated at this same 5% increment.

    0 讨论(0)
提交回复
热议问题