UIDeviceBatteryLevelDidChangeNotification 后台通知?

UIDeviceBatteryLevelDidChangeNotification background notifications?

我们正在寻求开发一款应用程序,如果用户的电池电量低于某个百分比,它会提醒用户,但是我们发现我们的应用程序在不活动时看不到获取此 NSNotifications。

有没有人有使用 UIDeviceBattery Notifications 的经验,并且知道这是否完全可行,从我从 Apple 文档中看到的情况来看,它似乎应该可以工作。

我们基本上是这样做的

-(void)startMonitoring {

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

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

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

[self redirectNSLogToDocuments];
NSLog(@"Starting Monitoring");
}

- (void)redirectNSLogToDocuments
{
    NSArray *allPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [allPaths objectAtIndex:0];
    NSString *pathForLog = [documentsDirectory stringByAppendingPathComponent:@"yourFile.txt"];

    freopen([pathForLog cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
}

- (void)batteryStatus {

    NSLog(@"Battery Status Notification");
}

因此,一旦我们启动电池监控,我们的日志文件就会填充初始消息,然后作为测试,我关闭应用程序并转到主屏幕并断开我的笔记本电脑电源线几次,这应该会触发电池状态日志,但事实并非如此。

提前致谢亚伦

NSNotifications 不会在后台传送到您的应用程序。 因此,除非您的应用可以请求某些后台模式权限,否则无法在后台执行该代码。

看看https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH4-SW4 看看您是否可以使用其中一些模式。