【问题标题】:Battery level notification not working when app is in background mode当应用程序处于后台模式时,电池电量通知不起作用
【发布时间】:2023-03-23 05:17:01
【问题描述】:

我已实施本地通知来检查电池状态。如果电池电量下降 1%,则会收到本地通知。这适用于两者,即应用程序处于前台或后台,iOS 版本低于 9。 当我将设备操作系统更新到 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 方法中我们显示通知。

我还启用了应用程序的后台模式,即在屏幕截图中显示。

enter image description here

任何帮助将不胜感激。提前致谢。

【问题讨论】:

    标签: ios objective-c notifications batterylevel


    【解决方案1】:

    您已启用后台获取模式,这意味着您的应用可以在后台接收远程通知并执行网络请求。

    如果不使用有问题的和 App Store 拒绝的方法,就不可能做你想做的事。 Apple 特别不希望您能够在后台运行您的应用程序,除非您有他们批准的用例之一。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多