确定准确的iPhone电池电量

时间:2011-06-27 07:53:09

标签: objective-c iphone cocoa-touch

我正在尝试按如下方式获取电池电量/状态:

- (void) viewWillAppear: (BOOL) animated{

    [self viewWillAppear:animated];

    // Battery state 
    [self batteryStatus];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStatus) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStatus) name:UIDeviceBatteryStateDidChangeNotification object:nil];


    }

- (void)batteryStatus
{
    NSArray *batteryStatus = [NSArray arrayWithObjects:
                              @"Battery status is unknown.",
                              @"Battery is in use (discharging).",
                              @"Battery is charging.",
                              @"Battery is fully charged.", nil];
    if ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateUnknown)
    {
        [textViewStatus setText:[batteryStatus objectAtIndex:0]];
        NSLog(@"%@", [batteryStatus objectAtIndex:0]);
    }
    else
    {
        NSString *msg = [NSString stringWithFormat:@"Battery charge level: %0.2f%%\n%@", [[UIDevice currentDevice] batteryLevel] * 100,[batteryStatus objectAtIndex:[[UIDevice currentDevice] batteryState]] ];
        [textViewStatus setText:msg];
        NSLog(@"%@", msg);
    }
}

但是,我没有改变电池电量,而且值并不准确。

- (void) viewWillAppear:(BOOL)animated {
    UIDevice *device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = YES;
    textViewStatus.text = [NSString stringWithFormat:@"%.2f", device.batteryLevel];
    [device addObserver:self forKeyPath:@"batteryLevel" options:0x0 context:nil];
    [super viewWillAppear:animated];
}

- (void) viewDidDisappear:(BOOL)animated {
    UIDevice *device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = NO;
    [device removeObserver:self forKeyPath:@"batteryLevel"];
    [super viewDidDisappear:animated];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    UIDevice *device = [UIDevice currentDevice];
    if ([object isEqual:device] && [keyPath isEqual:@"batteryLevel"]) {
        NSLog(@"Battery level :%f",device.batteryLevel);
        textViewStatus.text = [NSString stringWithFormat:@"%.2f", device.batteryLevel];
    }
}

有什么想法吗?

1 个答案:

答案 0 :(得分:21)

虽然我看不出您的代码有什么特别的错误,但请尝试以下

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIDevice *device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:device];
}

- (void)batteryChanged:(NSNotification *)notification
{
    UIDevice *device = [UIDevice currentDevice];
    NSLog(@"State: %i Charge: %f", device.batteryState, device.batteryLevel);
}

此外,值得注意的是,根据我的经验,通知仅以5%的间隔发射,即当电池电量从100%变为95%和95%变为90%等时