xref: /aosp_15_r20/external/cronet/base/power_monitor/power_monitor_device_source_ios.mm (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1// Copyright 2013 The Chromium Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/power_monitor/power_monitor_device_source.h"
6
7#import <UIKit/UIKit.h>
8
9#import "base/power_monitor/power_monitor_features.h"
10
11namespace base {
12
13bool PowerMonitorDeviceSource::IsOnBatteryPower() {
14#if TARGET_IPHONE_SIMULATOR
15  return false;
16#else
17  UIDevice* currentDevice = [UIDevice currentDevice];
18  BOOL isCurrentAppMonitoringBattery = currentDevice.isBatteryMonitoringEnabled;
19  [UIDevice currentDevice].batteryMonitoringEnabled = YES;
20  UIDeviceBatteryState batteryState = [UIDevice currentDevice].batteryState;
21  currentDevice.batteryMonitoringEnabled = isCurrentAppMonitoringBattery;
22  DCHECK(batteryState != UIDeviceBatteryStateUnknown);
23  return batteryState == UIDeviceBatteryStateUnplugged;
24#endif
25}
26
27void PowerMonitorDeviceSource::PlatformInit() {
28  if (FeatureList::IsEnabled(kRemoveIOSPowerEventNotifications)) {
29    return;
30  }
31
32  NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
33  id foreground =
34      [nc addObserverForName:UIApplicationWillEnterForegroundNotification
35                      object:nil
36                       queue:nil
37                  usingBlock:^(NSNotification* notification) {
38                      ProcessPowerEvent(RESUME_EVENT);
39                  }];
40  id background =
41      [nc addObserverForName:UIApplicationDidEnterBackgroundNotification
42                      object:nil
43                       queue:nil
44                  usingBlock:^(NSNotification* notification) {
45                      ProcessPowerEvent(SUSPEND_EVENT);
46                  }];
47  notification_observers_.push_back(foreground);
48  notification_observers_.push_back(background);
49}
50
51void PowerMonitorDeviceSource::PlatformDestroy() {
52  NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
53  for (std::vector<id>::iterator it = notification_observers_.begin();
54       it != notification_observers_.end(); ++it) {
55    [nc removeObserver:*it];
56  }
57  notification_observers_.clear();
58}
59
60}  // namespace base
61