1// Copyright 2013 The Chromium Authors. All rights reserved.
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
9namespace base {
10
11bool PowerMonitorDeviceSource::IsOnBatteryPowerImpl() {
12#if TARGET_IPHONE_SIMULATOR
13  return false;
14#else
15  UIDevice* currentDevice = [UIDevice currentDevice];
16  BOOL isCurrentAppMonitoringBattery = currentDevice.isBatteryMonitoringEnabled;
17  [UIDevice currentDevice].batteryMonitoringEnabled = YES;
18  UIDeviceBatteryState batteryState = [UIDevice currentDevice].batteryState;
19  currentDevice.batteryMonitoringEnabled = isCurrentAppMonitoringBattery;
20  DCHECK(batteryState != UIDeviceBatteryStateUnknown);
21  return batteryState == UIDeviceBatteryStateUnplugged;
22#endif
23}
24
25void PowerMonitorDeviceSource::PlatformInit() {
26  NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
27  id foreground =
28      [nc addObserverForName:UIApplicationWillEnterForegroundNotification
29                      object:nil
30                       queue:nil
31                  usingBlock:^(NSNotification* notification) {
32                      ProcessPowerEvent(RESUME_EVENT);
33                  }];
34  id background =
35      [nc addObserverForName:UIApplicationDidEnterBackgroundNotification
36                      object:nil
37                       queue:nil
38                  usingBlock:^(NSNotification* notification) {
39                      ProcessPowerEvent(SUSPEND_EVENT);
40                  }];
41  notification_observers_.push_back(foreground);
42  notification_observers_.push_back(background);
43}
44
45void PowerMonitorDeviceSource::PlatformDestroy() {
46  NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
47  for (std::vector<id>::iterator it = notification_observers_.begin();
48       it != notification_observers_.end(); ++it) {
49    [nc removeObserver:*it];
50  }
51  notification_observers_.clear();
52}
53
54}  // namespace base
55