1
我已经实施了本地通知以检查电池状态。如果电池电量下降1%,则会收到本地通知。这适用于iOS版本低于9的iOS应用程序在前台或后台。 当我将设备操作系统更新到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
方法我们显示通知。
我还启用了应用程序的背景模式,即在屏幕截图中显示。
任何帮助,将不胜感激。提前致谢。