剩余时间直到充电完成,iOS

isc*_*ers 17 iphone cocoa-touch ipad ios

我在用 :

UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
float batLeft = [myDevice batteryLevel];
int i = [myDevice batteryState];    
int batinfo = batLeft * 100;
Run Code Online (Sandbox Code Playgroud)

找到电池状态.我期待找到,如何找到剩余的时间,直到充电完成.例如:剩余1小时20分钟.我怎样才能以编程方式找到它?

小智 8

我没有在官方文档中找到任何方法,也没有在类的类转储,私有标题中找到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
}
Run Code Online (Sandbox Code Playgroud)

  • 这假设充电是线性的 - 事实并非如此.当电池接近满时,充电速度会急剧下降. (4认同)