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
方法我們顯示通知。
我還啓用了應用程序的背景模式,即在屏幕截圖中顯示。
任何幫助,將不勝感激。提前致謝。