1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.settings.fuelgauge.batteryusage;
18 
19 import android.content.Context;
20 import android.os.BatteryStatsManager;
21 import android.os.BatteryUsageStats;
22 import android.os.BatteryUsageStatsQuery;
23 import android.util.Log;
24 
25 import com.android.settingslib.utils.AsyncLoaderCompat;
26 
27 /** Loader to get new {@link BatteryUsageStats} in the background */
28 public class BatteryUsageStatsLoader extends AsyncLoaderCompat<BatteryUsageStats> {
29     private static final String TAG = "BatteryUsageStatsLoader";
30     private final BatteryStatsManager mBatteryStatsManager;
31     private final boolean mIncludeBatteryHistory;
32 
BatteryUsageStatsLoader(Context context, boolean includeBatteryHistory)33     public BatteryUsageStatsLoader(Context context, boolean includeBatteryHistory) {
34         super(context);
35         mBatteryStatsManager = context.getSystemService(BatteryStatsManager.class);
36         mIncludeBatteryHistory = includeBatteryHistory;
37     }
38 
39     @Override
loadInBackground()40     public BatteryUsageStats loadInBackground() {
41         final BatteryUsageStatsQuery.Builder builder = new BatteryUsageStatsQuery.Builder();
42         if (mIncludeBatteryHistory) {
43             builder.includeBatteryHistory();
44         }
45         try {
46             return mBatteryStatsManager.getBatteryUsageStats(
47                     builder.includeProcessStateData().build());
48         } catch (RuntimeException e) {
49             Log.e(TAG, "loadInBackground() for getBatteryUsageStats()", e);
50             // Use default BatteryUsageStats.
51             return new BatteryUsageStats.Builder(new String[0]).build();
52         }
53     }
54 
55     @Override
onDiscardResult(BatteryUsageStats result)56     protected void onDiscardResult(BatteryUsageStats result) {}
57 }
58