1 // Copyright 2014 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.
5 #include "device/battery/battery_status_service.h"
8 #include "base/message_loop/message_loop.h"
9 #include "base/single_thread_task_runner.h"
10 #include "device/battery/battery_monitor_impl.h"
11 #include "device/battery/battery_status_manager.h"
15 BatteryStatusService::BatteryStatusService()
16 : main_thread_task_runner_(base::MessageLoop::current()->task_runner()),
17 update_callback_(base::Bind(&BatteryStatusService::NotifyConsumers
,
18 base::Unretained(this))),
19 status_updated_(false),
21 callback_list_
.set_removal_callback(
22 base::Bind(&BatteryStatusService::ConsumersChanged
,
23 base::Unretained(this)));
26 BatteryStatusService::~BatteryStatusService() {
29 BatteryStatusService
* BatteryStatusService::GetInstance() {
30 return Singleton
<BatteryStatusService
,
31 LeakySingletonTraits
<BatteryStatusService
> >::get();
34 scoped_ptr
<BatteryStatusService::BatteryUpdateSubscription
>
35 BatteryStatusService::AddCallback(const BatteryUpdateCallback
& callback
) {
36 DCHECK(main_thread_task_runner_
->BelongsToCurrentThread());
37 DCHECK(!is_shutdown_
);
39 if (!battery_fetcher_
)
40 battery_fetcher_
= BatteryStatusManager::Create(update_callback_
);
42 if (callback_list_
.empty()) {
43 bool success
= battery_fetcher_
->StartListeningBatteryChange();
44 // On failure pass the default values back.
46 callback
.Run(BatteryStatus());
49 if (status_updated_
) {
50 // Send recent status to the new callback if already available.
51 callback
.Run(status_
);
54 return callback_list_
.Add(callback
);
57 void BatteryStatusService::ConsumersChanged() {
61 if (callback_list_
.empty()) {
62 battery_fetcher_
->StopListeningBatteryChange();
63 status_updated_
= false;
67 void BatteryStatusService::NotifyConsumers(const BatteryStatus
& status
) {
68 DCHECK(!is_shutdown_
);
70 main_thread_task_runner_
->PostTask(FROM_HERE
, base::Bind(
71 &BatteryStatusService::NotifyConsumersOnMainThread
,
72 base::Unretained(this),
76 void BatteryStatusService::NotifyConsumersOnMainThread(
77 const BatteryStatus
& status
) {
78 DCHECK(main_thread_task_runner_
->BelongsToCurrentThread());
79 if (callback_list_
.empty())
83 status_updated_
= true;
84 callback_list_
.Notify(status_
);
87 void BatteryStatusService::Shutdown() {
88 if (!callback_list_
.empty())
89 battery_fetcher_
->StopListeningBatteryChange();
90 battery_fetcher_
.reset();
94 const BatteryStatusService::BatteryUpdateCallback
&
95 BatteryStatusService::GetUpdateCallbackForTesting() const {
96 return update_callback_
;
99 void BatteryStatusService::SetBatteryManagerForTesting(
100 scoped_ptr
<BatteryStatusManager
> test_battery_manager
) {
101 battery_fetcher_
= test_battery_manager
.Pass();
102 status_
= BatteryStatus();
103 status_updated_
= false;
106 } // namespace device