如何让我的应用程序不断更新电池电量?

时间:2012-06-27 13:19:01

标签: ios battery uidevice

我的应用程序中有一个电池电量指示器,我想在电池电量指示器页面上更新它。目前,如果我将我的应用程序打开到该屏幕并且电池电量发生变化(超过5%),则应用程序崩溃。我需要添加到我的代码中才能做到这一点?这是我的代码:

- (void)viewDidLoad {
[super viewDidLoad];

deviceType.text = [[UIDevice currentDevice] model];

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
[[UIDevice currentDevice] batteryLevel];

// Enable monitoring of battery status
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

// Request to be notified when battery charge or state changes
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStatus) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
}

- (void) viewWillAppear:(BOOL)animated {
UIDevice *device = [UIDevice currentDevice];
device.batteryMonitoringEnabled = YES;
LabelBatteryStatus.text = [NSString stringWithFormat:@"%.0f%%", device.batteryLevel * 100];
[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"]) {
    LabelBatteryStatus.text = [NSString stringWithFormat:@"%.0f%%", device.batteryLevel * 100];
}
}

当我加载和卸载页面时,此代码适用于我的应用程序,但我希望它在页面上也能正常工作。

先谢谢你。

0 个答案:

没有答案