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 base::Singleton
<
32 base::LeakySingletonTraits
<BatteryStatusService
>>::get();
35 scoped_ptr
<BatteryStatusService::BatteryUpdateSubscription
>
36 BatteryStatusService::AddCallback(const BatteryUpdateCallback
& callback
) {
37 DCHECK(main_thread_task_runner_
->BelongsToCurrentThread());
38 DCHECK(!is_shutdown_
);
40 if (!battery_fetcher_
)
41 battery_fetcher_
= BatteryStatusManager::Create(update_callback_
);
43 if (callback_list_
.empty()) {
44 bool success
= battery_fetcher_
->StartListeningBatteryChange();
45 // On failure pass the default values back.
47 callback
.Run(BatteryStatus());
50 if (status_updated_
) {
51 // Send recent status to the new callback if already available.
52 callback
.Run(status_
);
55 return callback_list_
.Add(callback
);
58 void BatteryStatusService::ConsumersChanged() {
62 if (callback_list_
.empty()) {
63 battery_fetcher_
->StopListeningBatteryChange();
64 status_updated_
= false;
68 void BatteryStatusService::NotifyConsumers(const BatteryStatus
& status
) {
69 DCHECK(!is_shutdown_
);
71 main_thread_task_runner_
->PostTask(FROM_HERE
, base::Bind(
72 &BatteryStatusService::NotifyConsumersOnMainThread
,
73 base::Unretained(this),
77 void BatteryStatusService::NotifyConsumersOnMainThread(
78 const BatteryStatus
& status
) {
79 DCHECK(main_thread_task_runner_
->BelongsToCurrentThread());
80 if (callback_list_
.empty())
84 status_updated_
= true;
85 callback_list_
.Notify(status_
);
88 void BatteryStatusService::Shutdown() {
89 if (!callback_list_
.empty())
90 battery_fetcher_
->StopListeningBatteryChange();
91 battery_fetcher_
.reset();
95 const BatteryStatusService::BatteryUpdateCallback
&
96 BatteryStatusService::GetUpdateCallbackForTesting() const {
97 return update_callback_
;
100 void BatteryStatusService::SetBatteryManagerForTesting(
101 scoped_ptr
<BatteryStatusManager
> test_battery_manager
) {
102 battery_fetcher_
= test_battery_manager
.Pass();
103 status_
= BatteryStatus();
104 status_updated_
= false;
107 } // namespace device