1 : // Copyright (c) 2008 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/system_monitor.h"
6 : #include "base/logging.h"
7 : #include "base/message_loop.h"
8 :
9 : namespace base {
10 :
11 : #if defined(ENABLE_BATTERY_MONITORING)
12 : // The amount of time (in ms) to wait before running the initial
13 : // battery check.
14 : static int kDelayedBatteryCheckMs = 10 * 1000;
15 : #endif // defined(ENABLE_BATTERY_MONITORING)
16 :
17 0 : SystemMonitor::SystemMonitor()
18 : : battery_in_use_(false),
19 0 : suspended_(false) {
20 0 : observer_list_ = new ObserverListThreadSafe<PowerObserver>();
21 0 : }
22 :
23 0 : void SystemMonitor::ProcessPowerMessage(PowerEvent event_id) {
24 : // Suppress duplicate notifications. Some platforms may
25 : // send multiple notifications of the same event.
26 0 : switch (event_id) {
27 : case POWER_STATE_EVENT:
28 : {
29 0 : bool on_battery = IsBatteryPower();
30 0 : if (on_battery != battery_in_use_) {
31 0 : battery_in_use_ = on_battery;
32 0 : NotifyPowerStateChange();
33 : }
34 : }
35 0 : break;
36 : case RESUME_EVENT:
37 0 : if (suspended_) {
38 0 : suspended_ = false;
39 0 : NotifyResume();
40 : }
41 0 : break;
42 : case SUSPEND_EVENT:
43 0 : if (!suspended_) {
44 0 : suspended_ = true;
45 0 : NotifySuspend();
46 : }
47 0 : break;
48 : }
49 0 : }
50 :
51 0 : void SystemMonitor::AddObserver(PowerObserver* obs) {
52 0 : observer_list_->AddObserver(obs);
53 0 : }
54 :
55 0 : void SystemMonitor::RemoveObserver(PowerObserver* obs) {
56 0 : observer_list_->RemoveObserver(obs);
57 0 : }
58 :
59 0 : void SystemMonitor::NotifyPowerStateChange() {
60 0 : LOG(INFO) << "PowerStateChange: "
61 0 : << (BatteryPower() ? "On" : "Off") << " battery";
62 0 : observer_list_->Notify(&PowerObserver::OnPowerStateChange, this);
63 0 : }
64 :
65 0 : void SystemMonitor::NotifySuspend() {
66 0 : LOG(INFO) << "Power Suspending";
67 0 : observer_list_->Notify(&PowerObserver::OnSuspend, this);
68 0 : }
69 :
70 0 : void SystemMonitor::NotifyResume() {
71 0 : LOG(INFO) << "Power Resuming";
72 0 : observer_list_->Notify(&PowerObserver::OnResume, this);
73 0 : }
74 :
75 0 : void SystemMonitor::Start() {
76 : #if defined(ENABLE_BATTERY_MONITORING)
77 : DCHECK(MessageLoop::current()); // Can't call start too early.
78 : SystemMonitor* monitor = Get();
79 : monitor->delayed_battery_check_.Start(
80 : TimeDelta::FromMilliseconds(kDelayedBatteryCheckMs), monitor,
81 : &SystemMonitor::BatteryCheck);
82 : #endif // defined(ENABLE_BATTERY_MONITORING)
83 0 : }
84 :
85 0 : void SystemMonitor::BatteryCheck() {
86 0 : ProcessPowerMessage(SystemMonitor::POWER_STATE_EVENT);
87 0 : }
88 :
89 : } // namespace base
|