ios - UIDeviceBatteryLevelDidChangeNotification 后台通知?

标签 ios objective-c nsnotificationcenter uidevice

我们正在寻求开发一个应用程序,如果用户的电池电量低于一定百分比,它将向用户发出警报,但是我们发现我们的应用程序在不活动时不会收到此 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 在后台时不会传递到您的应用程序。 因此,除非您的应用程序可以请求某些后台模式权限,否则无法在后台执行该代码。

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

关于ios - UIDeviceBatteryLevelDidChangeNotification 后台通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28596292/

相关文章:

ios - CLLocationManager 是如何获取位置的?

ios - Firebase 通知 Swift 3

ios - 分段控件索引更改 Swift 时取消查询

iphone - 如何将 subview (其边缘的小 ImageView )添加到使用控件中的 segment-1

ios - Swift:使用 UIPageController 或屏幕边缘平移手势识别器导航 ViewController

objective-c - `id`这个类型是写Objective C程序经常用到的吗?

ios - 发布 nsnotification 但观察者没有听到

ios - 使用同一对象 NSNotificationCenter 释放调用两次

iphone - NSNotification addObserver :? 中的参数 `object` 是什么

ios - 在 iOS 中发送通知有哪些可能性