分享

如何获取iPhone电池的状态和当前的电量

 叹落花 2015-04-08
  1. - (void)batteryMoniter {  
  2.     UIDevice *device = [UIDevice currentDevice];  
  3.     device.batteryMonitoringEnabled = YES;  
  4.     if (device.batteryState == UIDeviceBatteryStateUnknown) {  
  5.         NSLog(@"UnKnow");  
  6.     }else if (device.batteryState == UIDeviceBatteryStateUnplugged){  
  7.         NSLog(@"Unplugged");  
  8.     }else if (device.batteryState == UIDeviceBatteryStateCharging){  
  9.         NSLog(@"Charging");  
  10.     }else if (device.batteryState == UIDeviceBatteryStateFull){  
  11.         NSLog(@"Full");  
  12.     }     
  13.     NSLog(@"%f",device.batteryLevel);  
  14. }  
  15.   
  16. NSLog(@"%f",device.batteryLevel);//简单的这句就是了。  
  17.   
  18. ################################################  
  19.   
  20. Having said that, I would not use a timer event for this, it is pretty inefficient. You want to use KVO instead:  
  21.   
  22. - (void) viewWillAppear:(BOOL)animated {  
  23.   UIDevice *device = [UIDevice currentDevice];  
  24.   device.batteryMonitoringEnabled = YES;  
  25.   currentCharge.text = [NSString stringWithFormat:@"%.2f", device.batteryLevel];  
  26.   [device addObserver:self forKeyPath:@"batteryLevel" options:0x0 context:nil];  
  27.   [super viewWillAppear:animated];  
  28. }  
  29.   
  30. - (void) viewDidDisappear:(BOOL)animated {  
  31.   UIDevice *device = [UIDevice currentDevice];  
  32.   device.batteryMonitoringEnabled = NO;  
  33.   [device removeObserver:self forKeyPath:@"batteryLevel"];  
  34.   [super viewDidDisappear:animated];  
  35. }  
  36.   
  37. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(voidvoid *)context {  
  38.   UIDevice *device = [UIDevice currentDevice];  
  39.   if ([object isEqual:device] && [keyPath isEqual:@"batteryLevel"]) {  
  40.     currentCharge.text = [NSString stringWithFormat:@"%.2f", device.batteryLevel];  
  41.   }  
  42. }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多