电池电量增加5%时间

时间:2012-11-26 20:28:45

标签: objective-c nstimer battery batterylevel

我想知道是否有办法让电池增加5%时间。例如,我怎么知道60%到65%之间经过了多长时间?我想我可以用NSTimer做到这一点,但我无法做到这一点,有人可以帮助我吗? 非常感谢。

1 个答案:

答案 0 :(得分:1)

如果你是为Mac做这个,请检查this question如何在Mac中获得电池续航时间;

如果您是在iOS上这样做,请查看this question了解如何在iOS中获得电池续航时间。

只需使用NSTimer触发功能即可每隔x秒获取一次电池续航时间,当达到60%时,使用NSDate捕获时间戳,然后当达到65%时,捕获另一个时间戳并进行比较获取时差的两个时间戳:SO question: how to get time between 2 NSDate objects

祝你好运。

编辑:

获取电池百分比的所有方法都在基于您的平台的第一个或第二个链接中。如果您希望它确定从现在开始到5%上/下的时间:

//both percent and date should be properties or instance variables (NSDate and float, respectively)
//You should probably also make the timer one as well, so you can stop it in any method with [tmr invalidate];
date = [NSDate date];
percent = [self getBatteryPercent];

NSTimer* tmr = [NSTimer scheduledTimerWithInterval:1 target:self selector:@selector(someMethod) userInfo:nil repeats:YES];

- (float)getBatteryPercent
{
    //You'll have to get this code from one of those methods (first or second link)
}

- (void)someMethod
{
    float newPercent = [self getBatteryPercent];
    if(percent - newPercent == 5.0 || percent - newPercent == -5.0)
    {
        //Get the time between timestamps
        NSDate* newDate = [NSDate date];
        //See third link for how to get the time difference between date and newDate
    }
}

其余由你决定。