OGeek|极客世界-中国程序员成长平台

标题: ios - UIDeviceBatteryLevelDidChangeNotification 后台通知? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 14:20
标题: ios - UIDeviceBatteryLevelDidChangeNotification 后台通知?

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

有没有人有任何使用 UIDeviceBattery 通知的经验,并且知道这是否可能,因为我从 Apple 文档中看到它似乎应该可以工作。

我们基本上是这样做的

-(void)startMonitoring {

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

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

    [[NSNotificationCenter defaultCenter] addObserver:self selectorselector(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");
}

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

提前感谢亚伦



Best Answer-推荐答案


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

看看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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4