1 /* 2 * Copyright (C) 2024 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.util.SparseArray; 21 22 import androidx.annotation.VisibleForTesting; 23 import androidx.core.util.Pair; 24 25 import com.android.settings.fuelgauge.BatteryOptimizeUtils; 26 import com.android.settingslib.fuelgauge.PowerAllowlistBackend; 27 28 /** A cache to log battery optimization mode of an app */ 29 final class BatteryOptimizationModeCache { 30 private static final String TAG = "BatteryOptimizationModeCache"; 31 32 /* Stores the battery optimization mode and mutable state for each UID. */ 33 @VisibleForTesting 34 final SparseArray<Pair<BatteryOptimizationMode, Boolean>> mBatteryOptimizeModeCache; 35 36 private final Context mContext; 37 BatteryOptimizationModeCache(final Context context)38 BatteryOptimizationModeCache(final Context context) { 39 mContext = context; 40 mBatteryOptimizeModeCache = new SparseArray<>(); 41 PowerAllowlistBackend.getInstance(mContext).refreshList(); 42 } 43 getBatteryOptimizeModeInfo( final int uid, final String packageName)44 Pair<BatteryOptimizationMode, Boolean> getBatteryOptimizeModeInfo( 45 final int uid, final String packageName) { 46 if (!mBatteryOptimizeModeCache.contains(uid)) { 47 final BatteryOptimizeUtils batteryOptimizeUtils = 48 new BatteryOptimizeUtils(mContext, uid, packageName); 49 mBatteryOptimizeModeCache.put( 50 uid, 51 Pair.create( 52 BatteryOptimizationMode.forNumber( 53 batteryOptimizeUtils.getAppOptimizationMode( 54 /* refreshList= */ false, 55 /* ignoreUnknownMode= */ false)), 56 batteryOptimizeUtils.isOptimizeModeMutable())); 57 } 58 final Pair<BatteryOptimizationMode, Boolean> batteryOptimizeModeInfo = 59 mBatteryOptimizeModeCache.get(uid); 60 return batteryOptimizeModeInfo != null 61 ? batteryOptimizeModeInfo 62 : new Pair<>(BatteryOptimizationMode.MODE_UNKNOWN, false); 63 } 64 } 65