IOS 电池状态监控

通过UIDevice获取电池用量和状态转换。

    UIDevice *device = [UIDevice currentDevice];


    device.batteryMonitoringEnabled = YES;

    //开启了监视电池状态的功能


    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryLevelChanged:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStateChanged:) name:@"UIDeviceBatteryStateDidChangeNotification" object:device];


- (void)batteryLevelChanged:(id)sender

{

    UIDevice *myDevice = [UIDevice currentDevice];

    [myDevice setBatteryMonitoringEnabled:YES];

    float batteryLevel = [myDevice batteryLevel];

    NSLog(@"电池剩余比例:%@", [NSString stringWithFormat:@"%f",batteryLevel*100]);

}


-(void)batteryStateChanged:(id)sender

{

    NSArray *stateArray = [NSArray arrayWithObjects:@"未开启监视电池状态",@"电池未充电状态",@"电池充电状态",@"电池充电完成",nil];

    NSLog(@"电池状态:%@", [stateArray objectAtIndex:[[UIDevice currentDevice] batteryState]]);

}


你可能感兴趣的:(IOS 电池状态监控)