应用处于后台模式时电池电量级别通知无效

时间:2016-04-28 10:38:46

标签: ios objective-c notifications batterylevel

我已经实施了检查电池状态的本地通知。如果电池电量下降了1%,则会收到本地通知。这适用于两种情况,即应用程序处于前景或后面的iOS版本低于9。 当我将设备操作系统更新到iOS 9时,我在前台收到了本地通知,但无法在应用程序的后台接收通知。 以下是用于实现的代码。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

// Enable monitoring of battery status

**[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];**

// Request to be notified when battery charge or state changes

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBatteryStatus) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkBatteryStatus) name:UIDeviceBatteryStateDidChangeNotification object:nil];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {

        // Request to be notified when battery charge or state changes

    [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

    **[[NSNotificationCenter defaultCenter] postNotificationName:UIDeviceBatteryLevelDidChangeNotification object:nil userInfo:nil];**

    **[[NSNotificationCenter defaultCenter] postNotificationName:UIDeviceBatteryStateDidChangeNotification object:nil userInfo:nil];**

}

- (void)checkBatteryStatus
{
    notifyAlarm = [[UILocalNotification alloc] init];

    notifyAlarm.alertBody = @“battery alert";
    notifyAlarm.soundName = UILocalNotificationDefaultSoundName;
    [[UIApplication sharedApplication] presentLocalNotificationNow:notifyAlarm];
    [self displayNotification];
 }

displayNotification方法中,我们会显示通知。

我还启用了应用的后台模式,即屏幕截图中显示。

enter image description here

任何帮助将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您启用了后台获取模式,这意味着您的应用可以在后台接收远程通知并执行网络请求。

如果不使用可疑和App Store可拒绝的方法,则无法执行您想要的操作。 Apple特别不希望您能够在后台运行您的应用程序,除非您有其批准的用例。