关闭

IOS中电池变化的监听

57人阅读 评论(0) 收藏 举报
转自:http://my.oschina.net/u/936286/blog/132943



1,电池级别和电池状态监听通知
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBattery:) name:UIDeviceBatteryStateDidChangeNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBattery:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];

2,电池的四种状态:
NSArray *stateArray = [NSArray arrayWithObjects: @"Battery state is Unknown", @"Battery is not plugged into a charging source", @"Battery is charging", @"Battery state is full", nil];

 3,[[UIDevice currentDevice] batteryLevel] * 100];//电池的级别,一般都是0.0--1.0之间;
[[UIDevice currentDevice] batteryState];//电池的状态

完整代码:

- (void) doLog: (NSString *) formatstring, ...
{
	va_list arglist;
	if (!formatstring) return;
	va_start(arglist, formatstring);
	NSString *outstring = [[[NSString alloc] initWithFormat:formatstring arguments:arglist] autorelease];
	va_end(arglist);
	[self.log appendString:outstring];
	[self.log appendString:@"\n"];
	self.textView.text = self.log;
}

- (void) checkBattery: (id) sender
{
	NSArray *stateArray = [NSArray arrayWithObjects: @"Battery state is Unknown", @"Battery is not plugged into a charging source", @"Battery is charging", @"Battery state is full", nil];
	self.log = [NSMutableString string];
	[self doLog:@"Battery level: %0.2f%", [[UIDevice currentDevice] batteryLevel] * 100];
	[self doLog:@"Battery state: %@", [stateArray objectAtIndex:[[UIDevice currentDevice] batteryState]]];
}

- (void) viewDidLoad
{
	self.navigationController.navigationBar.tintColor = COOKBOOK_PURPLE_COLOR;

	// Enable battery monitoring
	[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBattery:) name:UIDeviceBatteryStateDidChangeNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBattery:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];

	// Keep checking
	[NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(checkBattery:) userInfo:nil repeats:YES];
}
0
0

猜你在找
【套餐】Hadoop生态系统零基础入门
【套餐】嵌入式Linux C编程基础
【套餐】2017软考系统集成项目——任铄
【套餐】Android 5.x顶级视频课程——李宁
【套餐】深度学习入门视频课程——唐宇迪
【直播】广义线性模型及其应用——李科
【直播】从0到1 区块链的概念到实践
【直播】计算机视觉原理及实战——屈教授
【直播】机器学习之凸优化——马博士
【直播】机器学习&数据挖掘7周实训--韦玮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:17770次
    • 积分:498
    • 等级:
    • 排名:千里之外
    • 原创:20篇
    • 转载:91篇
    • 译文:0篇
    • 评论:0条