我们正在寻求开发一个应用程序,如果用户的电池电量低于一定百分比,它将向用户发出警报,但是我们发现我们的应用程序在不活动时不会收到此 NSNotifications。
是否有人有使用 UIDeviceBattery 通知的经验,并知道这是否可能,因为从我从 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 在后台时不会传递到您的应用程序。 因此,除非您的应用程序可以请求某些后台模式权限,否则无法在后台执行该代码。
关于ios - UIDeviceBatteryLevelDidChangeNotification 后台通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28596292/