1 /* 2 * Copyright (C) 2020 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; 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 /** 28 * Loader to get new {@link BatteryUsageStats} in the background 29 */ 30 public class BatteryUsageStatsLoader extends AsyncLoaderCompat<BatteryUsageStats> { 31 private static final String TAG = "BatteryUsageStatsLoader"; 32 private final BatteryStatsManager mBatteryStatsManager; 33 private final boolean mIncludeBatteryHistory; 34 BatteryUsageStatsLoader(Context context, boolean includeBatteryHistory)35 public BatteryUsageStatsLoader(Context context, boolean includeBatteryHistory) { 36 super(context); 37 mBatteryStatsManager = context.getSystemService(BatteryStatsManager.class); 38 mIncludeBatteryHistory = includeBatteryHistory; 39 } 40 41 @Override loadInBackground()42 public BatteryUsageStats loadInBackground() { 43 final BatteryUsageStatsQuery.Builder builder = new BatteryUsageStatsQuery.Builder(); 44 if (mIncludeBatteryHistory) { 45 builder.includeBatteryHistory(); 46 } 47 try { 48 return mBatteryStatsManager.getBatteryUsageStats(builder.build()); 49 } catch (RuntimeException e) { 50 Log.e(TAG, "loadInBackground() for getBatteryUsageStats()", e); 51 // Use default BatteryUsageStats. 52 return new BatteryUsageStats.Builder( 53 new String[0], /* includePowerModels */ false).build(); 54 } 55 } 56 57 @Override onDiscardResult(BatteryUsageStats result)58 protected void onDiscardResult(BatteryUsageStats result) { 59 } 60 } 61