如何实时监听电池状态是否发生改变

dayyyyy0827 2018-07-04 08:06:35
现在的方法是5s钟check一次电池状态,轮询
有什么办法可以在状态发生改变的时候主动通知吗
...全文
368 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Evanchane 2018-07-06
  • 打赏
  • 举报
回复
厉害了的编码了哟
不担心 2018-07-05
  • 打赏
  • 举报
回复
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

UIDeviceBatteryStateDidChangeNotification
UIDeviceBatteryLevelDidChangeNotification

监听这两个消息应该就可以了.
yuhao309 2018-07-05
  • 打赏
  • 举报
回复
通过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]]);

}

29,028

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧