2013-04-23 103 views
0

我想在iOS中显示我的设备的电池状态。获取ios中每次更改的电池状态

我在写下面的代码来显示电池状态。

UIDevice *myDevice = [UIDevice currentDevice]; 

[myDevice setBatteryMonitoringEnabled:YES]; 
double batLeft = (float)[myDevice batteryLevel] * 100; 
NSLog(@"%.f",batLeft); 
NSString * levelLabel = [NSString stringWithFormat:@"%.f%%", batLeft]; 
lblLabel.text =levelLabel; 

它在应用程序运行时显示电池状态正常。但是,当应用程序处于后台时,它不会获取更新后的值。我想每次显示设备的电池状态。电池在2%到3%之间死亡时,我也想发出通知。

回答

1

以下是每秒钟检查电池的示例。您需要检查电池状态何时发生变化,但我认为您的当前代码在viewDidLoad中只能读取一次。

- (void)viewDidLoad { 
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(checkBattery) userInfo:nil repeats:YES]; 
} 



- (void)checkBattery { 

    [myDevice setBatteryMonitoringEnabled:YES]; 
    double batLeft = (float)[myDevice batteryLevel] * 100; 
    NSLog(@"%.f",batLeft); 
    NSString * levelLabel = [NSString stringWithFormat:@"%.f%%", batLeft]; 
    lblLabel.text =levelLabel; 

} 
2

为了实现你想要做什么你的应用程序,你需要获得运行背景的权限。应用程序在后台运行的唯一条件是需要播放背景音频的应用程序,如音乐播放器或VOIP客户端。如果这只是一个测试应用程序,并且您不打算通过应用商店发布它,则可以使用AVAudioSession获取后台许可并查询电池状态。如果您打算发布应用程序,则应用程序获取后台许可的场景必须使用户受益。即它必须播放音乐或处理电话。