获取ios中每次更改的电池状态

获取ios中每次更改的电池状态,ios,batterylevel,Ios,Batterylevel,我想在iOS中显示设备的电池状态 我正在编写以下代码以显示电池状态 UIDevice *myDevice = [UIDevice currentDevice]; [myDevice setBatteryMonitoringEnabled:YES]; double batLeft = (float)[myDevice batteryLevel] * 100; NSLog(@"%.f",batLeft); NSString * levelLabel = [NSString stringWithFo

我想在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%之间耗尽时发出通知。

下面是一个每秒检查电池的示例。您需要检查中的电池状态何时更改,但我假定您当前的代码在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;

}

下面是一个每秒检查电池的示例。您需要检查中的电池状态何时更改,但我假定您当前的代码在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;

}

为了实现应用程序的目标,您需要获得运行后台的权限。对于在后台运行的应用程序,唯一的规定是需要播放后台音频的应用程序,如音乐播放器或VOIP客户端。如果这只是一个测试应用程序,而您不打算通过app store发布它,则可以使用AVAudioSession获取后台权限并轮询电池状态。如果您打算发布应用程序,应用程序获得后台权限的场景必须对用户有利。i、 e.它必须播放音乐或处理电话

为了实现应用程序的目标,您需要获得运行后台的权限。对于在后台运行的应用程序,唯一的规定是需要播放后台音频的应用程序,如音乐播放器或VOIP客户端。如果这只是一个测试应用程序,而您不打算通过app store发布它,则可以使用AVAudioSession获取后台权限并轮询电池状态。如果您打算发布应用程序,应用程序获得后台权限的场景必须对用户有利。i、 e.它必须播放音乐或处理电话