iOS简单的获取电池电量

最近斗鱼App更新了一个特性.能在播放页面看到自定义控件显示的系统电量…其实是有一些小BUG的.例如对电池状态以及电池电量的监听就没做.这篇文章就简单的介绍一下这个小功能如何实现.

1.proximityMonitoringEnabled

电池监视,

@property(nonatomic,getter=isProximityMonitoringEnabled) BOOL proximityMonitoringEnabled API_AVAILABLE(ios(3.0)); // default is NO

默认为NO.为NO的时候无法获取电池状态,也无法获取电池状态改变的回调.

[UIDevice currentDevice].batteryMonitoringEnabled = YES;

2.batteryState

电池状态

typedef NS_ENUM(NSInteger, UIDeviceBatteryState) {
	/// 未知状态
    UIDeviceBatteryStateUnknown,
    /// 未充电
    UIDeviceBatteryStateUnplugged,   // on battery, discharging
    /// 正在充电.(少于100%电量)
    UIDeviceBatteryStateCharging,    // plugged in, less than 100%
    /// 电池已充满
    UIDeviceBatteryStateFull,        // plugged in, at 100%
} API_UNAVAILABLE(tvos);              // available in iPhone 3.0

如果未设置电池监视为YES,获取的状态就是Unknown

3.batteryLevel

电池电量

@property(nonatomic,readonly) float                         batteryLevel API_AVAILABLE(ios(3.0)) API_UNAVAILABLE(tvos);  // 0 .. 1.0. -1.0 if UIDeviceBatteryStateUnknown

取值范围为0.0-1.0.(PS: batteryMonitoringEnabled为YES的情况下).否则是-1.0

4. UIDeviceBatteryStateDidChangeNotification

电池状态改变通知

注:前提条件是batteryMonitoringEnabled为YES

5. UIDeviceBatteryLevelDidChangeNotification

电量改变通知

注:前提条件是batteryMonitoringEnabled为YES

并且,和一般的通知不同.不是电量一改变就发送通知,而是有个通知最短间隔,并且不会短于一分钟.

/// 通过noti.object可以拿到UIDevice
- (void)deviceBatteryLevelDidChangeNotification:(NSNotification *)noti {
    NSLog(@"deviceBatteryLevelDidChange");
    float batteryLevel = ((UIDevice *)noti.object).batteryLevel;
}

你可能感兴趣的:(iOS小功能)