17

我在用 :

UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
float batLeft = [myDevice batteryLevel];
int i = [myDevice batteryState];    
int batinfo = batLeft * 100;

查找电池状态。我正在寻找,如何找到充电完成之前的剩余时间。例如:剩余 1 小时 20 分钟。如何以编程方式找到它?

4

1 回答 1

10

我在官方文档中没有找到任何方法,在类转储的私有头UIDevice文件中也没有。

所以我们必须想出一些办法。我目前想到的最佳“解决方案”类似于估计下载时间时采用的方法:计算下载/充电的平均速度,并将剩余量(数据或费用)除以该速度:

[UIDevice currentDevice].batteryMonitoringEnabled = YES;
float prevBatteryLev = [UIDevice currentDevice].batteryLevel;
NSDate *startDate = [NSDate date];

[[NSNotificationCenter defaultCenter]
    addObserver:self
       selector:@selector(batteryCharged)
           name:UIDeviceBatteryLevelDidChangeNotification
         object:nil
];

- (void)batteryCharged
{
    float currBatteryLev = [UIDevice currentDevice].batteryLevel;
    // calculate speed of chargement
    float avgChgSpeed = (prevBatteryLev - currBatteryLev) / [startDate timeIntervalSinceNow];
    // get how much the battery needs to be charged yet
    float remBatteryLev = 1.0 - currBatteryLev;
    // divide the two to obtain the remaining charge time
    NSTimeInterval remSeconds = remBatteryLev / avgChgSpeed;
    // convert/format `remSeconds' as appropriate
}
于 2012-12-16T07:22:53.633 回答