免费开源的iOS开发学习平台

UIDevice类:2-获取电池信息batteryState

通过UIDevice类,可以获取当前iOS设备电池的相关信息,包括当前电池的状态(充电中、未充电、已充满)以及电池的当前电量。

UIDevice中与电池相关的属性

当需要获取iOS设备的电池信息时,需要首先打开batteryMonitoringEnabled属性,然后就可以通过batteryState以及batteryLevel来获取电池的状态信息。

  • 是否开启电池监控,默认为NO
@property(nonatomic,getter=isBatteryMonitoringEnabled) BOOL batteryMonitoringEnabled ;
  • 电池电量,取值0~1.0
@property(nonatomic,readonly) float  batteryLevel ; 
  • 电池状态。其中,UIDeviceBatteryState有4种状态,分别为UIDeviceBatteryStateUnplugged(未充电)、UIDeviceBatteryStateCharging(充电中)、UIDeviceBatteryStateFull(已充满)、UIDeviceBatteryStateUnknown(未知状态)
@property(nonatomic,readonly) UIDeviceBatteryState  batteryState;

电池状态更新

在UIKit框架中,提供了用于电池状态变更时的通知(UIDeviceBatteryStateDidChangeNotification) , 当电池状态发生变更时,系统会给观察者发送通知。需要注意的是,在使用通知之前,需要预先在通知中心注册。

下方的示例代码,实现了当拔插充电线时,应用会给出对应的提醒。

  • 在控制器视图加载后,注册通知
- (void)viewDidLoad {
    [super viewDidLoad];
    UIDevice *device = [UIDevice currentDevice];
    //开启电池检测
    device.batteryMonitoringEnabled = YES;
    //注册通知,当充电状态改变时调用batteryStateChange方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStateChange) name:UIDeviceBatteryStateDidChangeNotification object:nil];
}
  • 不要忘记在控制器销毁时,移除观察者
-(void)dealloc {
    //移除观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
  • 电池状态发生变更时的处理逻辑
-(void) batteryStateChange {
    UIDevice *device = [UIDevice currentDevice];
    //获取当前电量
    float batteryVolume = device.batteryLevel * 100;
    //计算电池电量百分比
    NSString *batteryVolumeString = [NSString stringWithFormat:@"当前电量:%.0f%%",batteryVolume];
    //根据电池状态切换时,给出提醒
    switch (device.batteryState) {
        case UIDeviceBatteryStateUnplugged:{
            //提醒
            NSString *string = [NSString stringWithFormat:@"未充电,%@",batteryVolumeString];
            [self showAlert:string];
            break;}
        case UIDeviceBatteryStateCharging:{
            NSString *string = [NSString stringWithFormat:@"充电中,%@",batteryVolumeString];
            [self showAlert:string];
            break;
        }
        case UIDeviceBatteryStateFull:{
            NSString *string = [NSString stringWithFormat:@"已充满,%@",batteryVolumeString];
            [self showAlert:string];
            break;
        }
        case UIDeviceBatteryStateUnknown:{
            [self showAlert:@"未知状态"];
            break;
        }       
        default:
            break;
   }    
}
-(void) showAlert:(NSString *) string {
    UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"提示" message:string delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alertview show];
}

示例代码

https://github.com/99ios/17.1.2