Move battery usage files to a separate folder.

Bug: 202118250
Test: presubmit
Change-Id: I21aa58ebc02327849ed2161dbbafcdc806c007f2
This commit is contained in:
xuezaiyue
2022-06-08 21:53:23 +08:00
committed by YK Hung
parent 23eecdc87d
commit ac7318419a
49 changed files with 1126 additions and 1028 deletions

View File

@@ -2846,7 +2846,7 @@
<category android:name="com.android.settings.SHORTCUT" /> <category android:name="com.android.settings.SHORTCUT" />
</intent-filter> </intent-filter>
<meta-data android:name="com.android.settings.FRAGMENT_CLASS" <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
android:value="com.android.settings.fuelgauge.PowerUsageSummary" /> android:value="com.android.settings.fuelgauge.batteryusage.PowerUsageSummary" />
<meta-data android:name="com.android.settings.HIGHLIGHT_MENU_KEY" <meta-data android:name="com.android.settings.HIGHLIGHT_MENU_KEY"
android:value="@string/menu_key_battery"/> android:value="@string/menu_key_battery"/>
</activity> </activity>

View File

@@ -31,7 +31,7 @@
android:textColor="?android:attr/textColorSecondary" android:textColor="?android:attr/textColorSecondary"
android:text="@string/battery_usage_chart_graph_hint" /> android:text="@string/battery_usage_chart_graph_hint" />
<com.android.settings.fuelgauge.BatteryChartView <com.android.settings.fuelgauge.batteryusage.BatteryChartView
android:id="@+id/battery_chart" android:id="@+id/battery_chart"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="170dp" android:layout_height="170dp"

View File

@@ -21,7 +21,7 @@
android:title="@string/advanced_battery_title" android:title="@string/advanced_battery_title"
settings:keywords="@string/keywords_battery_usage"> settings:keywords="@string/keywords_battery_usage">
<com.android.settings.fuelgauge.BatteryHistoryPreference <com.android.settings.fuelgauge.batteryusage.BatteryHistoryPreference
android:key="battery_graph"/> android:key="battery_graph"/>
<PreferenceCategory <PreferenceCategory

View File

@@ -39,7 +39,7 @@
settings:controller="com.android.settings.fuelgauge.batterytip.BatteryTipPreferenceController" /> settings:controller="com.android.settings.fuelgauge.batterytip.BatteryTipPreferenceController" />
<Preference <Preference
android:fragment="com.android.settings.fuelgauge.PowerUsageAdvanced" android:fragment="com.android.settings.fuelgauge.batteryusage.PowerUsageAdvanced"
android:key="battery_usage_summary" android:key="battery_usage_summary"
android:title="@string/advanced_battery_preference_title" android:title="@string/advanced_battery_preference_title"
settings:keywords="@string/keywords_battery_usage" /> settings:keywords="@string/keywords_battery_usage" />

View File

@@ -59,7 +59,7 @@
settings:highlightableMenuKey="@string/menu_key_notifications"/> settings:highlightableMenuKey="@string/menu_key_notifications"/>
<com.android.settings.widget.HomepagePreference <com.android.settings.widget.HomepagePreference
android:fragment="com.android.settings.fuelgauge.PowerUsageSummary" android:fragment="com.android.settings.fuelgauge.batteryusage.PowerUsageSummary"
android:icon="@drawable/ic_settings_battery_white" android:icon="@drawable/ic_settings_battery_white"
android:key="top_level_battery" android:key="top_level_battery"
android:order="-110" android:order="-110"

View File

@@ -38,12 +38,12 @@ import com.android.settings.R;
import com.android.settings.Utils; import com.android.settings.Utils;
import com.android.settings.core.BasePreferenceController; import com.android.settings.core.BasePreferenceController;
import com.android.settings.fuelgauge.AdvancedPowerUsageDetail; import com.android.settings.fuelgauge.AdvancedPowerUsageDetail;
import com.android.settings.fuelgauge.BatteryChartPreferenceController;
import com.android.settings.fuelgauge.BatteryDiffEntry;
import com.android.settings.fuelgauge.BatteryEntry;
import com.android.settings.fuelgauge.BatteryUsageStatsLoader;
import com.android.settings.fuelgauge.BatteryUtils; import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.fuelgauge.PowerUsageFeatureProvider; import com.android.settings.fuelgauge.PowerUsageFeatureProvider;
import com.android.settings.fuelgauge.batteryusage.BatteryChartPreferenceController;
import com.android.settings.fuelgauge.batteryusage.BatteryDiffEntry;
import com.android.settings.fuelgauge.batteryusage.BatteryEntry;
import com.android.settings.fuelgauge.batteryusage.BatteryUsageStatsLoader;
import com.android.settings.overlay.FeatureFactory; import com.android.settings.overlay.FeatureFactory;
import com.android.settingslib.applications.AppUtils; import com.android.settingslib.applications.AppUtils;
import com.android.settingslib.core.lifecycle.Lifecycle; import com.android.settingslib.core.lifecycle.Lifecycle;

View File

@@ -99,9 +99,9 @@ import com.android.settings.display.darkmode.DarkModeSettingsFragment;
import com.android.settings.dream.DreamSettings; import com.android.settings.dream.DreamSettings;
import com.android.settings.enterprise.EnterprisePrivacySettings; import com.android.settings.enterprise.EnterprisePrivacySettings;
import com.android.settings.fuelgauge.AdvancedPowerUsageDetail; import com.android.settings.fuelgauge.AdvancedPowerUsageDetail;
import com.android.settings.fuelgauge.PowerUsageSummary;
import com.android.settings.fuelgauge.batterysaver.BatterySaverScheduleSettings; import com.android.settings.fuelgauge.batterysaver.BatterySaverScheduleSettings;
import com.android.settings.fuelgauge.batterysaver.BatterySaverSettings; import com.android.settings.fuelgauge.batterysaver.BatterySaverSettings;
import com.android.settings.fuelgauge.batteryusage.PowerUsageSummary;
import com.android.settings.gestures.AssistGestureSettings; import com.android.settings.gestures.AssistGestureSettings;
import com.android.settings.gestures.ButtonNavigationSettingsFragment; import com.android.settings.gestures.ButtonNavigationSettingsFragment;
import com.android.settings.gestures.DoubleTapPowerSettings; import com.android.settings.gestures.DoubleTapPowerSettings;

View File

@@ -31,9 +31,9 @@ import com.android.settings.deviceinfo.aboutphone.MyDeviceInfoFragment;
import com.android.settings.display.NightDisplaySettings; import com.android.settings.display.NightDisplaySettings;
import com.android.settings.emergency.EmergencyDashboardFragment; import com.android.settings.emergency.EmergencyDashboardFragment;
import com.android.settings.enterprise.EnterprisePrivacySettings; import com.android.settings.enterprise.EnterprisePrivacySettings;
import com.android.settings.fuelgauge.PowerUsageSummary;
import com.android.settings.fuelgauge.SmartBatterySettings; import com.android.settings.fuelgauge.SmartBatterySettings;
import com.android.settings.fuelgauge.batterysaver.BatterySaverSettings; import com.android.settings.fuelgauge.batterysaver.BatterySaverSettings;
import com.android.settings.fuelgauge.batteryusage.PowerUsageSummary;
import com.android.settings.gestures.GestureSettings; import com.android.settings.gestures.GestureSettings;
import com.android.settings.homepage.TopLevelSettings; import com.android.settings.homepage.TopLevelSettings;
import com.android.settings.language.LanguageAndInputSettings; import com.android.settings.language.LanguageAndInputSettings;

View File

@@ -45,6 +45,9 @@ import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.fuelgauge.batterytip.BatteryTipPreferenceController; import com.android.settings.fuelgauge.batterytip.BatteryTipPreferenceController;
import com.android.settings.fuelgauge.batterytip.tips.BatteryTip; import com.android.settings.fuelgauge.batterytip.tips.BatteryTip;
import com.android.settings.overlay.FeatureFactory; import com.android.settings.overlay.FeatureFactory;
import com.android.settings.fuelgauge.batteryusage.BatteryDiffEntry;
import com.android.settings.fuelgauge.batteryusage.BatteryEntry;
import com.android.settings.fuelgauge.batteryusage.BatteryHistEntry;
import com.android.settings.widget.EntityHeaderController; import com.android.settings.widget.EntityHeaderController;
import com.android.settingslib.HelpUtils; import com.android.settingslib.HelpUtils;
import com.android.settingslib.applications.AppUtils; import com.android.settingslib.applications.AppUtils;

View File

@@ -190,7 +190,7 @@ public class BatteryUtils {
* Returns true if the specified battery consumer should be excluded from * Returns true if the specified battery consumer should be excluded from
* battery consumption lists, either short or full. * battery consumption lists, either short or full.
*/ */
boolean shouldHideUidBatteryConsumerUnconditionally(UidBatteryConsumer consumer, public boolean shouldHideUidBatteryConsumerUnconditionally(UidBatteryConsumer consumer,
String[] packages) { String[] packages) {
final int uid = consumer.getUid(); final int uid = consumer.getUid();
return uid == UID_TETHERING return uid == UID_TETHERING

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2016 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@ import android.content.Intent;
import android.net.Uri; import android.net.Uri;
import android.util.SparseIntArray; import android.util.SparseIntArray;
import com.android.settings.fuelgauge.batteryusage.BatteryHistEntry;
import com.android.settingslib.fuelgauge.Estimate; import com.android.settingslib.fuelgauge.Estimate;
import java.util.Map; import java.util.Map;
@@ -73,6 +74,7 @@ public interface PowerUsageFeatureProvider {
/** /**
* Returns an improved projection curve for future battery level. * Returns an improved projection curve for future battery level.
*
* @param zeroTime timestamps (array keys) are shifted by this amount * @param zeroTime timestamps (array keys) are shifted by this amount
*/ */
SparseIntArray getEnhancedBatteryPredictionCurve(Context context, long zeroTime); SparseIntArray getEnhancedBatteryPredictionCurve(Context context, long zeroTime);
@@ -84,21 +86,20 @@ public interface PowerUsageFeatureProvider {
/** /**
* Checks whether debugging should be enabled for battery estimates. * Checks whether debugging should be enabled for battery estimates.
* @return
*/ */
boolean isEstimateDebugEnabled(); boolean isEstimateDebugEnabled();
/** /**
* Converts the provided string containing the remaining time into a debug string for enhanced * Converts the provided string containing the remaining time into a debug string for enhanced
* estimates. * estimates.
* @param timeRemaining *
* @return A string containing the estimate and a label indicating it is an enhanced estimate * @return A string containing the estimate and a label indicating it is an enhanced estimate
*/ */
String getEnhancedEstimateDebugString(String timeRemaining); String getEnhancedEstimateDebugString(String timeRemaining);
/** /**
* Converts the provided string containing the remaining time into a debug string. * Converts the provided string containing the remaining time into a debug string.
* @param timeRemaining *
* @return A string containing the estimate and a label indicating it is a normal estimate * @return A string containing the estimate and a label indicating it is a normal estimate
*/ */
String getOldEstimateDebugString(String timeRemaining); String getOldEstimateDebugString(String timeRemaining);
@@ -114,7 +115,7 @@ public interface PowerUsageFeatureProvider {
* to their next charging time. * to their next charging time.
* *
* @param id Optional string used to identify the caller for metrics. Usually the class name of * @param id Optional string used to identify the caller for metrics. Usually the class name of
* the caller * the caller
*/ */
boolean getEarlyWarningSignal(Context context, String id); boolean getEarlyWarningSignal(Context context, String id);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2017 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -26,11 +26,13 @@ import android.util.SparseIntArray;
import com.android.internal.util.ArrayUtils; import com.android.internal.util.ArrayUtils;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.fuelgauge.batteryusage.BatteryHistEntry;
import com.android.settingslib.fuelgauge.Estimate; import com.android.settingslib.fuelgauge.Estimate;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
/** Implementation of {@code PowerUsageFeatureProvider} */
public class PowerUsageFeatureProviderImpl implements PowerUsageFeatureProvider { public class PowerUsageFeatureProviderImpl implements PowerUsageFeatureProvider {
private static final String PACKAGE_CALENDAR_PROVIDER = "com.android.providers.calendar"; private static final String PACKAGE_CALENDAR_PROVIDER = "com.android.providers.calendar";

View File

@@ -21,12 +21,13 @@ import android.os.Parcel;
import androidx.annotation.VisibleForTesting; import androidx.annotation.VisibleForTesting;
import com.android.settings.fuelgauge.AdvancedPowerUsageDetail;
import com.android.settings.fuelgauge.batterytip.AppInfo; import com.android.settings.fuelgauge.batterytip.AppInfo;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider; import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
/** /**
* Tip to suggest user to remove app restriction. This is the empty tip and it is only used in * Tip to suggest user to remove app restriction. This is the empty tip and it is only used in
* {@link com.android.settings.fuelgauge.AdvancedPowerUsageDetail} to create dialog. * {@link AdvancedPowerUsageDetail} to create dialog.
*/ */
public class UnrestrictAppTip extends BatteryTip { public class UnrestrictAppTip extends BatteryTip {
private AppInfo mAppInfo; private AppInfo mAppInfo;

View File

@@ -1,5 +1,6 @@
/* /*
* Copyright (C) 2017 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
@@ -11,11 +12,9 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*
*
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import android.app.Activity; import android.app.Activity;
import android.content.Context; import android.content.Context;
@@ -35,8 +34,8 @@ import android.os.UserManager;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.format.DateUtils; import android.text.format.DateUtils;
import android.util.ArrayMap; import android.util.ArrayMap;
import android.util.SparseArray;
import android.util.Log; import android.util.Log;
import android.util.SparseArray;
import androidx.annotation.VisibleForTesting; import androidx.annotation.VisibleForTesting;
import androidx.preference.Preference; import androidx.preference.Preference;
@@ -48,6 +47,8 @@ import com.android.settings.R;
import com.android.settings.SettingsActivity; import com.android.settings.SettingsActivity;
import com.android.settings.core.InstrumentedPreferenceFragment; import com.android.settings.core.InstrumentedPreferenceFragment;
import com.android.settings.core.PreferenceControllerMixin; import com.android.settings.core.PreferenceControllerMixin;
import com.android.settings.fuelgauge.AdvancedPowerUsageDetail;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.overlay.FeatureFactory; import com.android.settings.overlay.FeatureFactory;
import com.android.settingslib.core.AbstractPreferenceController; import com.android.settingslib.core.AbstractPreferenceController;
import com.android.settingslib.core.lifecycle.Lifecycle; import com.android.settingslib.core.lifecycle.Lifecycle;
@@ -72,6 +73,7 @@ public class BatteryAppListPreferenceController extends AbstractPreferenceContro
private static final int MAX_ITEMS_TO_LIST = USE_FAKE_DATA ? 30 : 20; private static final int MAX_ITEMS_TO_LIST = USE_FAKE_DATA ? 30 : 20;
private static final int MIN_AVERAGE_POWER_THRESHOLD_MILLI_AMP = 10; private static final int MIN_AVERAGE_POWER_THRESHOLD_MILLI_AMP = 10;
private static final String MEDIASERVER_PACKAGE_NAME = "mediaserver"; private static final String MEDIASERVER_PACKAGE_NAME = "mediaserver";
private static final String NOT_AVAILABLE = "not_available";
@VisibleForTesting @VisibleForTesting
PreferenceGroup mAppListGroup; PreferenceGroup mAppListGroup;
@@ -230,7 +232,7 @@ public class BatteryAppListPreferenceController extends AbstractPreferenceContro
if (sConfig.shouldShowBatteryAttributionList(mContext)) { if (sConfig.shouldShowBatteryAttributionList(mContext)) {
final int dischargePercentage = getDischargePercentage(batteryUsageStats); final int dischargePercentage = getDischargePercentage(batteryUsageStats);
final List<BatteryEntry> usageList = final List<BatteryEntry> usageList =
getCoalescedUsageList(showAllApps, /*loadDataInBackground=*/ true); getCoalescedUsageList(showAllApps, /*loadDataInBackground=*/ true);
final double totalPower = batteryUsageStats.getConsumedPower(); final double totalPower = batteryUsageStats.getConsumedPower();
final int numSippers = usageList.size(); final int numSippers = usageList.size();
for (int i = 0; i < numSippers; i++) { for (int i = 0; i < numSippers; i++) {
@@ -292,7 +294,7 @@ public class BatteryAppListPreferenceController extends AbstractPreferenceContro
} }
final int dischargePercentage = getDischargePercentage(batteryUsageStats); final int dischargePercentage = getDischargePercentage(batteryUsageStats);
final List<BatteryEntry> usageList = final List<BatteryEntry> usageList =
getCoalescedUsageList(showAllApps, /*loadDataInBackground=*/ false); getCoalescedUsageList(showAllApps, /*loadDataInBackground=*/ false);
final double totalPower = batteryUsageStats.getConsumedPower(); final double totalPower = batteryUsageStats.getConsumedPower();
for (int i = 0; i < usageList.size(); i++) { for (int i = 0; i < usageList.size(); i++) {
final BatteryEntry entry = usageList.get(i); final BatteryEntry entry = usageList.get(i);
@@ -458,8 +460,8 @@ public class BatteryAppListPreferenceController extends AbstractPreferenceContro
private void cacheRemoveAllPrefs(PreferenceGroup group) { private void cacheRemoveAllPrefs(PreferenceGroup group) {
mPreferenceCache = new ArrayMap<>(); mPreferenceCache = new ArrayMap<>();
final int N = group.getPreferenceCount(); final int n = group.getPreferenceCount();
for (int i = 0; i < N; i++) { for (int i = 0; i < n; i++) {
Preference p = group.getPreference(i); Preference p = group.getPreference(i);
if (TextUtils.isEmpty(p.getKey())) { if (TextUtils.isEmpty(p.getKey())) {
continue; continue;
@@ -563,7 +565,6 @@ public class BatteryAppListPreferenceController extends AbstractPreferenceContro
} }
private void addNotAvailableMessage() { private void addNotAvailableMessage() {
final String NOT_AVAILABLE = "not_available";
Preference notAvailable = getCachedPreference(NOT_AVAILABLE); Preference notAvailable = getCachedPreference(NOT_AVAILABLE);
if (notAvailable == null) { if (notAvailable == null) {
notAvailable = new Preference(mPrefContext); notAvailable = new Preference(mPrefContext);

View File

@@ -1,5 +1,6 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
@@ -11,10 +12,9 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import android.app.settings.SettingsEnums; import android.app.settings.SettingsEnums;
import android.content.Context; import android.content.Context;
@@ -38,6 +38,8 @@ import com.android.settings.R;
import com.android.settings.SettingsActivity; import com.android.settings.SettingsActivity;
import com.android.settings.core.InstrumentedPreferenceFragment; import com.android.settings.core.InstrumentedPreferenceFragment;
import com.android.settings.core.PreferenceControllerMixin; import com.android.settings.core.PreferenceControllerMixin;
import com.android.settings.fuelgauge.AdvancedPowerUsageDetail;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.overlay.FeatureFactory; import com.android.settings.overlay.FeatureFactory;
import com.android.settingslib.core.AbstractPreferenceController; import com.android.settingslib.core.AbstractPreferenceController;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider; import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
@@ -60,8 +62,8 @@ import java.util.Map;
/** Controls the update for chart graph and the list items. */ /** Controls the update for chart graph and the list items. */
public class BatteryChartPreferenceController extends AbstractPreferenceController public class BatteryChartPreferenceController extends AbstractPreferenceController
implements PreferenceControllerMixin, LifecycleObserver, OnCreate, OnDestroy, implements PreferenceControllerMixin, LifecycleObserver, OnCreate, OnDestroy,
OnSaveInstanceState, BatteryChartView.OnSelectListener, OnResume, OnSaveInstanceState, BatteryChartView.OnSelectListener, OnResume,
ExpandDividerPreference.OnExpandListener { ExpandDividerPreference.OnExpandListener {
private static final String TAG = "BatteryChartPreferenceController"; private static final String TAG = "BatteryChartPreferenceController";
private static final String KEY_FOOTER_PREF = "battery_graph_footer"; private static final String KEY_FOOTER_PREF = "battery_graph_footer";
private static final String PACKAGE_NAME_NONE = "none"; private static final String PACKAGE_NAME_NONE = "none";
@@ -82,16 +84,25 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
@VisibleForTesting @VisibleForTesting
Map<Integer, List<BatteryDiffEntry>> mBatteryIndexedMap; Map<Integer, List<BatteryDiffEntry>> mBatteryIndexedMap;
@VisibleForTesting Context mPrefContext; @VisibleForTesting
@VisibleForTesting BatteryUtils mBatteryUtils; Context mPrefContext;
@VisibleForTesting PreferenceGroup mAppListPrefGroup; @VisibleForTesting
@VisibleForTesting BatteryChartView mBatteryChartView; BatteryUtils mBatteryUtils;
@VisibleForTesting ExpandDividerPreference mExpandDividerPreference; @VisibleForTesting
PreferenceGroup mAppListPrefGroup;
@VisibleForTesting
BatteryChartView mBatteryChartView;
@VisibleForTesting
ExpandDividerPreference mExpandDividerPreference;
@VisibleForTesting boolean mIsExpanded = false; @VisibleForTesting
@VisibleForTesting int[] mBatteryHistoryLevels; boolean mIsExpanded = false;
@VisibleForTesting long[] mBatteryHistoryKeys; @VisibleForTesting
@VisibleForTesting int mTrapezoidIndex = BatteryChartView.SELECTED_INDEX_INVALID; int[] mBatteryHistoryLevels;
@VisibleForTesting
long[] mBatteryHistoryKeys;
@VisibleForTesting
int mTrapezoidIndex = BatteryChartView.SELECTED_INDEX_INVALID;
private boolean mIs24HourFormat = false; private boolean mIs24HourFormat = false;
private boolean mIsFooterPrefAdded = false; private boolean mIsFooterPrefAdded = false;
@@ -122,15 +133,15 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
mPreferenceKey = preferenceKey; mPreferenceKey = preferenceKey;
mIs24HourFormat = DateFormat.is24HourFormat(context); mIs24HourFormat = DateFormat.is24HourFormat(context);
mMetricsFeatureProvider = mMetricsFeatureProvider =
FeatureFactory.getFactory(mContext).getMetricsFeatureProvider(); FeatureFactory.getFactory(mContext).getMetricsFeatureProvider();
mNotAllowShowEntryPackages = mNotAllowShowEntryPackages =
FeatureFactory.getFactory(context) FeatureFactory.getFactory(context)
.getPowerUsageFeatureProvider(context) .getPowerUsageFeatureProvider(context)
.getHideApplicationEntries(context); .getHideApplicationEntries(context);
mNotAllowShowSummaryPackages = mNotAllowShowSummaryPackages =
FeatureFactory.getFactory(context) FeatureFactory.getFactory(context)
.getPowerUsageFeatureProvider(context) .getPowerUsageFeatureProvider(context)
.getHideApplicationSummary(context); .getHideApplicationSummary(context);
if (lifecycle != null) { if (lifecycle != null) {
lifecycle.addObserver(this); lifecycle.addObserver(this);
} }
@@ -142,18 +153,18 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
return; return;
} }
mTrapezoidIndex = mTrapezoidIndex =
savedInstanceState.getInt(KEY_CURRENT_TIME_SLOT, mTrapezoidIndex); savedInstanceState.getInt(KEY_CURRENT_TIME_SLOT, mTrapezoidIndex);
mIsExpanded = mIsExpanded =
savedInstanceState.getBoolean(KEY_EXPAND_SYSTEM_INFO, mIsExpanded); savedInstanceState.getBoolean(KEY_EXPAND_SYSTEM_INFO, mIsExpanded);
Log.d(TAG, String.format("onCreate() slotIndex=%d isExpanded=%b", Log.d(TAG, String.format("onCreate() slotIndex=%d isExpanded=%b",
mTrapezoidIndex, mIsExpanded)); mTrapezoidIndex, mIsExpanded));
} }
@Override @Override
public void onResume() { public void onResume() {
final int currentUiMode = final int currentUiMode =
mContext.getResources().getConfiguration().uiMode mContext.getResources().getConfiguration().uiMode
& Configuration.UI_MODE_NIGHT_MASK; & Configuration.UI_MODE_NIGHT_MASK;
if (sUiMode != currentUiMode) { if (sUiMode != currentUiMode) {
sUiMode = currentUiMode; sUiMode = currentUiMode;
BatteryDiffEntry.clearCache(); BatteryDiffEntry.clearCache();
@@ -171,7 +182,7 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
savedInstance.putInt(KEY_CURRENT_TIME_SLOT, mTrapezoidIndex); savedInstance.putInt(KEY_CURRENT_TIME_SLOT, mTrapezoidIndex);
savedInstance.putBoolean(KEY_EXPAND_SYSTEM_INFO, mIsExpanded); savedInstance.putBoolean(KEY_EXPAND_SYSTEM_INFO, mIsExpanded);
Log.d(TAG, String.format("onSaveInstanceState() slotIndex=%d isExpanded=%b", Log.d(TAG, String.format("onSaveInstanceState() slotIndex=%d isExpanded=%b",
mTrapezoidIndex, mIsExpanded)); mTrapezoidIndex, mIsExpanded));
} }
@Override @Override
@@ -194,7 +205,7 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
mAppListPrefGroup = screen.findPreference(mPreferenceKey); mAppListPrefGroup = screen.findPreference(mPreferenceKey);
mAppListPrefGroup.setOrderingAsAdded(false); mAppListPrefGroup.setOrderingAsAdded(false);
mAppListPrefGroup.setTitle( mAppListPrefGroup.setTitle(
mPrefContext.getString(R.string.battery_app_usage_for_past_24)); mPrefContext.getString(R.string.battery_app_usage_for_past_24));
mFooterPreference = screen.findPreference(KEY_FOOTER_PREF); mFooterPreference = screen.findPreference(KEY_FOOTER_PREF);
// Removes footer first until usage data is loaded to avoid flashing. // Removes footer first until usage data is loaded to avoid flashing.
if (mFooterPreference != null) { if (mFooterPreference != null) {
@@ -243,19 +254,19 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
Log.d(TAG, "onChartSelect:" + trapezoidIndex); Log.d(TAG, "onChartSelect:" + trapezoidIndex);
refreshUi(trapezoidIndex, /*isForce=*/ false); refreshUi(trapezoidIndex, /*isForce=*/ false);
mMetricsFeatureProvider.action( mMetricsFeatureProvider.action(
mPrefContext, mPrefContext,
trapezoidIndex == BatteryChartView.SELECTED_INDEX_ALL trapezoidIndex == BatteryChartView.SELECTED_INDEX_ALL
? SettingsEnums.ACTION_BATTERY_USAGE_SHOW_ALL ? SettingsEnums.ACTION_BATTERY_USAGE_SHOW_ALL
: SettingsEnums.ACTION_BATTERY_USAGE_TIME_SLOT); : SettingsEnums.ACTION_BATTERY_USAGE_TIME_SLOT);
} }
@Override @Override
public void onExpand(boolean isExpanded) { public void onExpand(boolean isExpanded) {
mIsExpanded = isExpanded; mIsExpanded = isExpanded;
mMetricsFeatureProvider.action( mMetricsFeatureProvider.action(
mPrefContext, mPrefContext,
SettingsEnums.ACTION_BATTERY_USAGE_EXPAND_ITEM, SettingsEnums.ACTION_BATTERY_USAGE_EXPAND_ITEM,
isExpanded); isExpanded);
refreshExpandUi(); refreshExpandUi();
} }
@@ -276,7 +287,7 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
final Map<String, BatteryHistEntry> entryMap = batteryHistoryMap.get(timestamp); final Map<String, BatteryHistEntry> entryMap = batteryHistoryMap.get(timestamp);
if (entryMap == null || entryMap.isEmpty()) { if (entryMap == null || entryMap.isEmpty()) {
Log.e(TAG, "abnormal entry list in the timestamp:" Log.e(TAG, "abnormal entry list in the timestamp:"
+ ConvertUtils.utcToLocalTime(mPrefContext, timestamp)); + ConvertUtils.utcToLocalTime(mPrefContext, timestamp));
continue; continue;
} }
// Averages the battery level in each time slot to avoid corner conditions. // Averages the battery level in each time slot to avoid corner conditions.
@@ -285,15 +296,15 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
batteryLevelCounter += entry.mBatteryLevel; batteryLevelCounter += entry.mBatteryLevel;
} }
mBatteryHistoryLevels[index] = mBatteryHistoryLevels[index] =
Math.round(batteryLevelCounter / entryMap.size()); Math.round(batteryLevelCounter / entryMap.size());
} }
forceRefreshUi(); forceRefreshUi();
Log.d(TAG, String.format( Log.d(TAG, String.format(
"setBatteryHistoryMap() size=%d key=%s\nlevels=%s", "setBatteryHistoryMap() size=%d key=%s\nlevels=%s",
batteryHistoryMap.size(), batteryHistoryMap.size(),
ConvertUtils.utcToLocalTime(mPrefContext, ConvertUtils.utcToLocalTime(mPrefContext,
mBatteryHistoryKeys[mBatteryHistoryKeys.length - 1]), mBatteryHistoryKeys[mBatteryHistoryKeys.length - 1]),
Arrays.toString(mBatteryHistoryLevels))); Arrays.toString(mBatteryHistoryLevels)));
// Loads item icon and label in the background. // Loads item icon and label in the background.
new LoadAllItemsInfoTask(batteryHistoryMap).execute(); new LoadAllItemsInfoTask(batteryHistoryMap).execute();
@@ -313,9 +324,9 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
private void forceRefreshUi() { private void forceRefreshUi() {
final int refreshIndex = final int refreshIndex =
mTrapezoidIndex == BatteryChartView.SELECTED_INDEX_INVALID mTrapezoidIndex == BatteryChartView.SELECTED_INDEX_INVALID
? BatteryChartView.SELECTED_INDEX_ALL ? BatteryChartView.SELECTED_INDEX_ALL
: mTrapezoidIndex; : mTrapezoidIndex;
if (mBatteryChartView != null) { if (mBatteryChartView != null) {
mBatteryChartView.setLevels(mBatteryHistoryLevels); mBatteryChartView.setLevels(mBatteryHistoryLevels);
mBatteryChartView.setSelectedIndex(refreshIndex); mBatteryChartView.setSelectedIndex(refreshIndex);
@@ -333,7 +344,7 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
return false; return false;
} }
Log.d(TAG, String.format("refreshUi: index=%d size=%d isForce:%b", Log.d(TAG, String.format("refreshUi: index=%d size=%d isForce:%b",
trapezoidIndex, mBatteryIndexedMap.size(), isForce)); trapezoidIndex, mBatteryIndexedMap.size(), isForce));
mTrapezoidIndex = trapezoidIndex; mTrapezoidIndex = trapezoidIndex;
mHandler.post(() -> { mHandler.post(() -> {
@@ -349,7 +360,7 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
private void addAllPreferences() { private void addAllPreferences() {
final List<BatteryDiffEntry> entries = final List<BatteryDiffEntry> entries =
mBatteryIndexedMap.get(Integer.valueOf(mTrapezoidIndex)); mBatteryIndexedMap.get(Integer.valueOf(mTrapezoidIndex));
addFooterPreferenceIfNeeded(entries != null && !entries.isEmpty()); addFooterPreferenceIfNeeded(entries != null && !entries.isEmpty());
if (entries == null) { if (entries == null) {
Log.w(TAG, "cannot find BatteryDiffEntry for:" + mTrapezoidIndex); Log.w(TAG, "cannot find BatteryDiffEntry for:" + mTrapezoidIndex);
@@ -377,7 +388,7 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
Collections.sort(appEntries, BatteryDiffEntry.COMPARATOR); Collections.sort(appEntries, BatteryDiffEntry.COMPARATOR);
Collections.sort(mSystemEntries, BatteryDiffEntry.COMPARATOR); Collections.sort(mSystemEntries, BatteryDiffEntry.COMPARATOR);
Log.d(TAG, String.format("addAllPreferences() app=%d system=%d", Log.d(TAG, String.format("addAllPreferences() app=%d system=%d",
appEntries.size(), mSystemEntries.size())); appEntries.size(), mSystemEntries.size()));
// Adds app entries to the list if it is not empty. // Adds app entries to the list if it is not empty.
if (!appEntries.isEmpty()) { if (!appEntries.isEmpty()) {
@@ -391,7 +402,7 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
mExpandDividerPreference.setIsExpanded(mIsExpanded); mExpandDividerPreference.setIsExpanded(mIsExpanded);
} }
mExpandDividerPreference.setOrder( mExpandDividerPreference.setOrder(
mAppListPrefGroup.getPreferenceCount()); mAppListPrefGroup.getPreferenceCount());
mAppListPrefGroup.addPreference(mExpandDividerPreference); mAppListPrefGroup.addPreference(mExpandDividerPreference);
} }
refreshExpandUi(); refreshExpandUi();
@@ -479,11 +490,11 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
Log.d(TAG, String.format("refreshCategoryTitle:%s", slotInformation)); Log.d(TAG, String.format("refreshCategoryTitle:%s", slotInformation));
if (mAppListPrefGroup != null) { if (mAppListPrefGroup != null) {
mAppListPrefGroup.setTitle( mAppListPrefGroup.setTitle(
getSlotInformation(/*isApp=*/ true, slotInformation)); getSlotInformation(/*isApp=*/ true, slotInformation));
} }
if (mExpandDividerPreference != null) { if (mExpandDividerPreference != null) {
mExpandDividerPreference.setTitle( mExpandDividerPreference.setTitle(
getSlotInformation(/*isApp=*/ false, slotInformation)); getSlotInformation(/*isApp=*/ false, slotInformation));
} }
} }
@@ -491,12 +502,12 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
// Null means we show all information without a specific time slot. // Null means we show all information without a specific time slot.
if (slotInformation == null) { if (slotInformation == null) {
return isApp return isApp
? mPrefContext.getString(R.string.battery_app_usage_for_past_24) ? mPrefContext.getString(R.string.battery_app_usage_for_past_24)
: mPrefContext.getString(R.string.battery_system_usage_for_past_24); : mPrefContext.getString(R.string.battery_system_usage_for_past_24);
} else { } else {
return isApp return isApp
? mPrefContext.getString(R.string.battery_app_usage_for, slotInformation) ? mPrefContext.getString(R.string.battery_app_usage_for, slotInformation)
: mPrefContext.getString(R.string.battery_system_usage_for ,slotInformation); : mPrefContext.getString(R.string.battery_system_usage_for, slotInformation);
} }
} }
@@ -505,12 +516,12 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
return null; return null;
} }
final String fromHour = ConvertUtils.utcToLocalTimeHour(mPrefContext, final String fromHour = ConvertUtils.utcToLocalTimeHour(mPrefContext,
mBatteryHistoryKeys[mTrapezoidIndex * 2], mIs24HourFormat); mBatteryHistoryKeys[mTrapezoidIndex * 2], mIs24HourFormat);
final String toHour = ConvertUtils.utcToLocalTimeHour(mPrefContext, final String toHour = ConvertUtils.utcToLocalTimeHour(mPrefContext,
mBatteryHistoryKeys[(mTrapezoidIndex + 1) * 2], mIs24HourFormat); mBatteryHistoryKeys[(mTrapezoidIndex + 1) * 2], mIs24HourFormat);
return mIs24HourFormat return mIs24HourFormat
? String.format("%s%s", fromHour, toHour) ? String.format("%s%s", fromHour, toHour)
: String.format("%s %s", fromHour, toHour); : String.format("%s %s", fromHour, toHour);
} }
@VisibleForTesting @VisibleForTesting
@@ -528,10 +539,10 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
// Not shows summary for some system components without usage time. // Not shows summary for some system components without usage time.
if (totalUsageTimeInMs == 0) { if (totalUsageTimeInMs == 0) {
preference.setSummary(null); preference.setSummary(null);
// Shows background summary only if we don't have foreground usage time. // Shows background summary only if we don't have foreground usage time.
} else if (foregroundUsageTimeInMs == 0 && backgroundUsageTimeInMs != 0) { } else if (foregroundUsageTimeInMs == 0 && backgroundUsageTimeInMs != 0) {
usageTimeSummary = buildUsageTimeInfo(backgroundUsageTimeInMs, true); usageTimeSummary = buildUsageTimeInfo(backgroundUsageTimeInMs, true);
// Shows total usage summary only if total usage time is small. // Shows total usage summary only if total usage time is small.
} else if (totalUsageTimeInMs < DateUtils.MINUTE_IN_MILLIS) { } else if (totalUsageTimeInMs < DateUtils.MINUTE_IN_MILLIS) {
usageTimeSummary = buildUsageTimeInfo(totalUsageTimeInMs, false); usageTimeSummary = buildUsageTimeInfo(totalUsageTimeInMs, false);
} else { } else {
@@ -539,7 +550,7 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
// Shows background usage time if it is larger than a minute. // Shows background usage time if it is larger than a minute.
if (backgroundUsageTimeInMs > 0) { if (backgroundUsageTimeInMs > 0) {
usageTimeSummary += usageTimeSummary +=
"\n" + buildUsageTimeInfo(backgroundUsageTimeInMs, true); "\n" + buildUsageTimeInfo(backgroundUsageTimeInMs, true);
} }
} }
preference.setSummary(usageTimeSummary); preference.setSummary(usageTimeSummary);
@@ -548,17 +559,17 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
private String buildUsageTimeInfo(long usageTimeInMs, boolean isBackground) { private String buildUsageTimeInfo(long usageTimeInMs, boolean isBackground) {
if (usageTimeInMs < DateUtils.MINUTE_IN_MILLIS) { if (usageTimeInMs < DateUtils.MINUTE_IN_MILLIS) {
return mPrefContext.getString( return mPrefContext.getString(
isBackground isBackground
? R.string.battery_usage_background_less_than_one_minute ? R.string.battery_usage_background_less_than_one_minute
: R.string.battery_usage_total_less_than_one_minute); : R.string.battery_usage_total_less_than_one_minute);
} }
final CharSequence timeSequence = final CharSequence timeSequence =
StringUtil.formatElapsedTime(mPrefContext, usageTimeInMs, StringUtil.formatElapsedTime(mPrefContext, usageTimeInMs,
/*withSeconds=*/ false, /*collapseTimeUnit=*/ false); /*withSeconds=*/ false, /*collapseTimeUnit=*/ false);
final int resourceId = final int resourceId =
isBackground isBackground
? R.string.battery_usage_for_background_time ? R.string.battery_usage_for_background_time
: R.string.battery_usage_for_total_time; : R.string.battery_usage_for_total_time;
return mPrefContext.getString(resourceId, timeSequence); return mPrefContext.getString(resourceId, timeSequence);
} }
@@ -578,7 +589,7 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
return; return;
} }
final long latestTimestamp = final long latestTimestamp =
mBatteryHistoryKeys[mBatteryHistoryKeys.length - 1]; mBatteryHistoryKeys[mBatteryHistoryKeys.length - 1];
mBatteryChartView.setLatestTimestamp(latestTimestamp); mBatteryChartView.setLatestTimestamp(latestTimestamp);
} }
@@ -588,9 +599,9 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
} }
mIsFooterPrefAdded = true; mIsFooterPrefAdded = true;
mFooterPreference.setTitle(mPrefContext.getString( mFooterPreference.setTitle(mPrefContext.getString(
containAppItems containAppItems
? R.string.battery_usage_screen_footer ? R.string.battery_usage_screen_footer
: R.string.battery_usage_screen_footer_empty)); : R.string.battery_usage_screen_footer_empty));
mHandler.post(() -> mPreferenceScreen.addPreference(mFooterPreference)); mHandler.post(() -> mPreferenceScreen.addPreference(mFooterPreference));
} }
@@ -623,21 +634,21 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
public static List<BatteryDiffEntry> getBatteryLast24HrUsageData(Context context) { public static List<BatteryDiffEntry> getBatteryLast24HrUsageData(Context context) {
final long start = System.currentTimeMillis(); final long start = System.currentTimeMillis();
final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap = final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap =
FeatureFactory.getFactory(context) FeatureFactory.getFactory(context)
.getPowerUsageFeatureProvider(context) .getPowerUsageFeatureProvider(context)
.getBatteryHistory(context); .getBatteryHistory(context);
if (batteryHistoryMap == null || batteryHistoryMap.isEmpty()) { if (batteryHistoryMap == null || batteryHistoryMap.isEmpty()) {
return null; return null;
} }
Log.d(TAG, String.format("getBatteryLast24HrData() size=%d time=&d/ms", Log.d(TAG, String.format("getBatteryLast24HrData() size=%d time=&d/ms",
batteryHistoryMap.size(), (System.currentTimeMillis() - start))); batteryHistoryMap.size(), (System.currentTimeMillis() - start)));
final Map<Integer, List<BatteryDiffEntry>> batteryIndexedMap = final Map<Integer, List<BatteryDiffEntry>> batteryIndexedMap =
ConvertUtils.getIndexedUsageMap( ConvertUtils.getIndexedUsageMap(
context, context,
/*timeSlotSize=*/ CHART_LEVEL_ARRAY_SIZE - 1, /*timeSlotSize=*/ CHART_LEVEL_ARRAY_SIZE - 1,
getBatteryHistoryKeys(batteryHistoryMap), getBatteryHistoryKeys(batteryHistoryMap),
batteryHistoryMap, batteryHistoryMap,
/*purgeLowPercentageAndFakeData=*/ true); /*purgeLowPercentageAndFakeData=*/ true);
return batteryIndexedMap.get(BatteryChartView.SELECTED_INDEX_ALL); return batteryIndexedMap.get(BatteryChartView.SELECTED_INDEX_ALL);
} }
@@ -666,7 +677,7 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
private static long[] getBatteryHistoryKeys( private static long[] getBatteryHistoryKeys(
final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap) { final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap) {
final List<Long> batteryHistoryKeyList = final List<Long> batteryHistoryKeyList =
new ArrayList<>(batteryHistoryMap.keySet()); new ArrayList<>(batteryHistoryMap.keySet());
Collections.sort(batteryHistoryKeyList); Collections.sort(batteryHistoryKeyList);
final long[] batteryHistoryKeys = new long[CHART_KEY_ARRAY_SIZE]; final long[] batteryHistoryKeys = new long[CHART_KEY_ARRAY_SIZE];
for (int index = 0; index < CHART_KEY_ARRAY_SIZE; index++) { for (int index = 0; index < CHART_KEY_ARRAY_SIZE; index++) {
@@ -695,16 +706,16 @@ public class BatteryChartPreferenceController extends AbstractPreferenceControll
} }
final long startTime = System.currentTimeMillis(); final long startTime = System.currentTimeMillis();
final Map<Integer, List<BatteryDiffEntry>> indexedUsageMap = final Map<Integer, List<BatteryDiffEntry>> indexedUsageMap =
ConvertUtils.getIndexedUsageMap( ConvertUtils.getIndexedUsageMap(
mPrefContext, /*timeSlotSize=*/ CHART_LEVEL_ARRAY_SIZE - 1, mPrefContext, /*timeSlotSize=*/ CHART_LEVEL_ARRAY_SIZE - 1,
mBatteryHistoryKeysCache, mBatteryHistoryMap, mBatteryHistoryKeysCache, mBatteryHistoryMap,
/*purgeLowPercentageAndFakeData=*/ true); /*purgeLowPercentageAndFakeData=*/ true);
// Pre-loads each BatteryDiffEntry relative icon and label for all slots. // Pre-loads each BatteryDiffEntry relative icon and label for all slots.
for (List<BatteryDiffEntry> entries : indexedUsageMap.values()) { for (List<BatteryDiffEntry> entries : indexedUsageMap.values()) {
entries.forEach(entry -> entry.loadLabelAndIcon()); entries.forEach(entry -> entry.loadLabelAndIcon());
} }
Log.d(TAG, String.format("execute LoadAllItemsInfoTask in %d/ms", Log.d(TAG, String.format("execute LoadAllItemsInfoTask in %d/ms",
(System.currentTimeMillis() - startTime))); (System.currentTimeMillis() - startTime)));
return indexedUsageMap; return indexedUsageMap;
} }

View File

@@ -1,22 +1,24 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * Licensed under the Apache License, Version 2.0 (the "License");
* except in compliance with the License. You may obtain a copy of the License at * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software distributed under the * Unless required by applicable law or agreed to in writing, software
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * distributed under the License is distributed on an "AS IS" BASIS,
* KIND, either express or implied. See the License for the specific language governing * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* permissions and limitations under the License. * See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static java.lang.Math.round;
import static com.android.settings.Utils.formatPercentage; import static com.android.settings.Utils.formatPercentage;
import static java.lang.Math.round;
import android.accessibilityservice.AccessibilityServiceInfo; import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.Context; import android.content.Context;
import android.content.res.Resources; import android.content.res.Resources;
@@ -37,8 +39,8 @@ import android.view.View;
import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityManager;
import android.widget.TextView; import android.widget.TextView;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.annotation.VisibleForTesting; import androidx.annotation.VisibleForTesting;
import androidx.appcompat.widget.AppCompatImageView;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.overlay.FeatureFactory; import com.android.settings.overlay.FeatureFactory;
@@ -54,7 +56,7 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
AccessibilityManager.AccessibilityStateChangeListener { AccessibilityManager.AccessibilityStateChangeListener {
private static final String TAG = "BatteryChartView"; private static final String TAG = "BatteryChartView";
private static final List<String> ACCESSIBILITY_SERVICE_NAMES = private static final List<String> ACCESSIBILITY_SERVICE_NAMES =
Arrays.asList("SwitchAccessService", "TalkBackService", "JustSpeakService"); Arrays.asList("SwitchAccessService", "TalkBackService", "JustSpeakService");
private static final int DEFAULT_TRAPEZOID_COUNT = 12; private static final int DEFAULT_TRAPEZOID_COUNT = 12;
private static final int DEFAULT_TIMESTAMP_COUNT = 4; private static final int DEFAULT_TIMESTAMP_COUNT = 4;
@@ -68,6 +70,7 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
/** A callback listener for selected group index is updated. */ /** A callback listener for selected group index is updated. */
public interface OnSelectListener { public interface OnSelectListener {
/** The callback function for selected group index is updated. */
void onSelect(int trapezoidIndex); void onSelect(int trapezoidIndex);
} }
@@ -79,9 +82,12 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
private boolean mIsSlotsClickabled; private boolean mIsSlotsClickabled;
private String[] mPercentages = getPercentages(); private String[] mPercentages = getPercentages();
@VisibleForTesting int mHoveredIndex = SELECTED_INDEX_INVALID; @VisibleForTesting
@VisibleForTesting int mSelectedIndex = SELECTED_INDEX_INVALID; int mHoveredIndex = SELECTED_INDEX_INVALID;
@VisibleForTesting String[] mTimestamps; @VisibleForTesting
int mSelectedIndex = SELECTED_INDEX_INVALID;
@VisibleForTesting
String[] mTimestamps;
// Colors for drawing the trapezoid shape and dividers. // Colors for drawing the trapezoid shape and dividers.
private int mTrapezoidColor; private int mTrapezoidColor;
@@ -91,10 +97,10 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
private int mTextPadding; private int mTextPadding;
private final Rect mIndent = new Rect(); private final Rect mIndent = new Rect();
private final Rect[] mPercentageBounds = private final Rect[] mPercentageBounds =
new Rect[] {new Rect(), new Rect(), new Rect()}; new Rect[]{new Rect(), new Rect(), new Rect()};
// For drawing the timestamp information. // For drawing the timestamp information.
private final Rect[] mTimestampsBounds = private final Rect[] mTimestampsBounds =
new Rect[] {new Rect(), new Rect(), new Rect(), new Rect()}; new Rect[]{new Rect(), new Rect(), new Rect(), new Rect()};
@VisibleForTesting @VisibleForTesting
Handler mHandler = new Handler(); Handler mHandler = new Handler();
@@ -202,14 +208,15 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
mTimestamps = new String[DEFAULT_TIMESTAMP_COUNT]; mTimestamps = new String[DEFAULT_TIMESTAMP_COUNT];
} }
final long timeSlotOffset = final long timeSlotOffset =
DateUtils.HOUR_IN_MILLIS * (/*total 24 hours*/ 24 / TIMESTAMP_GAPS_COUNT); DateUtils.HOUR_IN_MILLIS * (/*total 24 hours*/ 24 / TIMESTAMP_GAPS_COUNT);
final boolean is24HourFormat = DateFormat.is24HourFormat(getContext()); final boolean is24HourFormat = DateFormat.is24HourFormat(getContext());
for (int index = 0; index < DEFAULT_TIMESTAMP_COUNT; index++) { for (int index = 0; index < DEFAULT_TIMESTAMP_COUNT; index++) {
mTimestamps[index] = mTimestamps[index] =
ConvertUtils.utcToLocalTimeHour( ConvertUtils.utcToLocalTimeHour(
getContext(), getContext(),
latestTimestamp - (TIMESTAMP_GAPS_COUNT - index) * timeSlotOffset, latestTimestamp - (TIMESTAMP_GAPS_COUNT - index)
is24HourFormat); * timeSlotOffset,
is24HourFormat);
} }
requestLayout(); requestLayout();
} }
@@ -221,8 +228,8 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
if (mTextPaint != null) { if (mTextPaint != null) {
for (int index = 0; index < mPercentages.length; index++) { for (int index = 0; index < mPercentages.length; index++) {
mTextPaint.getTextBounds( mTextPaint.getTextBounds(
mPercentages[index], 0, mPercentages[index].length(), mPercentages[index], 0, mPercentages[index].length(),
mPercentageBounds[index]); mPercentageBounds[index]);
} }
// Updates the indent configurations. // Updates the indent configurations.
mIndent.top = mPercentageBounds[0].height(); mIndent.top = mPercentageBounds[0].height();
@@ -232,8 +239,8 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
int maxHeight = 0; int maxHeight = 0;
for (int index = 0; index < DEFAULT_TIMESTAMP_COUNT; index++) { for (int index = 0; index < DEFAULT_TIMESTAMP_COUNT; index++) {
mTextPaint.getTextBounds( mTextPaint.getTextBounds(
mTimestamps[index], 0, mTimestamps[index].length(), mTimestamps[index], 0, mTimestamps[index].length(),
mTimestampsBounds[index]); mTimestampsBounds[index]);
maxHeight = Math.max(maxHeight, mTimestampsBounds[index].height()); maxHeight = Math.max(maxHeight, mTimestampsBounds[index].height());
} }
mIndent.bottom = maxHeight + round(mTextPadding * 1.5f); mIndent.bottom = maxHeight + round(mTextPadding * 1.5f);
@@ -318,14 +325,14 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
super.onAttachedToWindow(); super.onAttachedToWindow();
updateClickableState(); updateClickableState();
mContext.getSystemService(AccessibilityManager.class) mContext.getSystemService(AccessibilityManager.class)
.addAccessibilityStateChangeListener(/*listener=*/ this); .addAccessibilityStateChangeListener(/*listener=*/ this);
} }
@Override @Override
public void onDetachedFromWindow() { public void onDetachedFromWindow() {
super.onDetachedFromWindow(); super.onDetachedFromWindow();
mContext.getSystemService(AccessibilityManager.class) mContext.getSystemService(AccessibilityManager.class)
.removeAccessibilityStateChangeListener(/*listener=*/ this); .removeAccessibilityStateChangeListener(/*listener=*/ this);
mHandler.removeCallbacks(mUpdateClickableStateRun); mHandler.removeCallbacks(mUpdateClickableStateRun);
} }
@@ -336,16 +343,16 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
// We should delay it a while since accessibility manager will spend // We should delay it a while since accessibility manager will spend
// some times to bind with new enabled accessibility services. // some times to bind with new enabled accessibility services.
mHandler.postDelayed( mHandler.postDelayed(
mUpdateClickableStateRun, UPDATE_STATE_DELAYED_TIME); mUpdateClickableStateRun, UPDATE_STATE_DELAYED_TIME);
} }
private void updateClickableState() { private void updateClickableState() {
final Context context = mContext; final Context context = mContext;
mIsSlotsClickabled = mIsSlotsClickabled =
FeatureFactory.getFactory(context) FeatureFactory.getFactory(context)
.getPowerUsageFeatureProvider(context) .getPowerUsageFeatureProvider(context)
.isChartGraphSlotsEnabled(context) .isChartGraphSlotsEnabled(context)
&& !isAccessibilityEnabled(context); && !isAccessibilityEnabled(context);
Log.d(TAG, "isChartGraphSlotsEnabled:" + mIsSlotsClickabled); Log.d(TAG, "isChartGraphSlotsEnabled:" + mIsSlotsClickabled);
setClickable(isClickable()); setClickable(isClickable());
// Initializes the trapezoid curve paint for non-clickable case. // Initializes the trapezoid curve paint for non-clickable case.
@@ -378,7 +385,7 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
mTrapezoidSolidColor = Utils.getColorAccentDefaultColor(context); mTrapezoidSolidColor = Utils.getColorAccentDefaultColor(context);
mTrapezoidColor = Utils.getDisabled(context, mTrapezoidSolidColor); mTrapezoidColor = Utils.getDisabled(context, mTrapezoidSolidColor);
mTrapezoidHoverColor = Utils.getColorAttrDefaultColor(context, mTrapezoidHoverColor = Utils.getColorAttrDefaultColor(context,
com.android.internal.R.attr.colorAccentSecondaryVariant); com.android.internal.R.attr.colorAccentSecondaryVariant);
// Initializes the divider line paint. // Initializes the divider line paint.
final Resources resources = getContext().getResources(); final Resources resources = getContext().getResources();
mDividerWidth = resources.getDimensionPixelSize(R.dimen.chartview_divider_width); mDividerWidth = resources.getDimensionPixelSize(R.dimen.chartview_divider_width);
@@ -398,8 +405,8 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
mTrapezoidPaint.setColor(mTrapezoidSolidColor); mTrapezoidPaint.setColor(mTrapezoidSolidColor);
mTrapezoidPaint.setStyle(Paint.Style.FILL); mTrapezoidPaint.setStyle(Paint.Style.FILL);
mTrapezoidPaint.setPathEffect( mTrapezoidPaint.setPathEffect(
new CornerPathEffect( new CornerPathEffect(
resources.getDimensionPixelSize(R.dimen.chartview_trapezoid_radius))); resources.getDimensionPixelSize(R.dimen.chartview_trapezoid_radius)));
// Initializes for drawing text information. // Initializes for drawing text information.
mTextPadding = resources.getDimensionPixelSize(R.dimen.chartview_text_padding); mTextPadding = resources.getDimensionPixelSize(R.dimen.chartview_text_padding);
} }
@@ -414,7 +421,7 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
// Draws the center divider line for 50% curve. // Draws the center divider line for 50% curve.
final float availableSpace = final float availableSpace =
height - mDividerWidth * 2 - mTrapezoidVOffset - mDividerHeight; height - mDividerWidth * 2 - mTrapezoidVOffset - mDividerHeight;
offsetY = mIndent.top + mDividerWidth + availableSpace * .5f; offsetY = mIndent.top + mDividerWidth + availableSpace * .5f;
canvas.drawLine(0, offsetY, width, offsetY, mDividerPaint); canvas.drawLine(0, offsetY, width, offsetY, mDividerPaint);
drawPercentage(canvas, /*index=*/ 1, offsetY); drawPercentage(canvas, /*index=*/ 1, offsetY);
@@ -428,10 +435,11 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
private void drawPercentage(Canvas canvas, int index, float offsetY) { private void drawPercentage(Canvas canvas, int index, float offsetY) {
if (mTextPaint != null) { if (mTextPaint != null) {
canvas.drawText( canvas.drawText(
mPercentages[index], mPercentages[index],
getWidth() - mPercentageBounds[index].width() - mPercentageBounds[index].left, getWidth() - mPercentageBounds[index].width()
offsetY + mPercentageBounds[index].height() *.5f, - mPercentageBounds[index].left,
mTextPaint); offsetY + mPercentageBounds[index].height() * .5f,
mTextPaint);
} }
} }
@@ -471,31 +479,32 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
private void drawTimestamp(Canvas canvas, float[] xOffsets) { private void drawTimestamp(Canvas canvas, float[] xOffsets) {
// Draws the 1st timestamp info. // Draws the 1st timestamp info.
canvas.drawText( canvas.drawText(
mTimestamps[0], mTimestamps[0],
xOffsets[0] - mTimestampsBounds[0].left, xOffsets[0] - mTimestampsBounds[0].left,
getTimestampY(0), mTextPaint); getTimestampY(0), mTextPaint);
final int latestIndex = DEFAULT_TIMESTAMP_COUNT - 1; final int latestIndex = DEFAULT_TIMESTAMP_COUNT - 1;
// Draws the last timestamp info. // Draws the last timestamp info.
canvas.drawText( canvas.drawText(
mTimestamps[latestIndex], mTimestamps[latestIndex],
xOffsets[latestIndex] - mTimestampsBounds[latestIndex].width() xOffsets[latestIndex] - mTimestampsBounds[latestIndex].width()
- mTimestampsBounds[latestIndex].left, - mTimestampsBounds[latestIndex].left,
getTimestampY(latestIndex), mTextPaint); getTimestampY(latestIndex), mTextPaint);
// Draws the rest of timestamp info since it is located in the center. // Draws the rest of timestamp info since it is located in the center.
for (int index = 1; index <= DEFAULT_TIMESTAMP_COUNT - 2; index++) { for (int index = 1; index <= DEFAULT_TIMESTAMP_COUNT - 2; index++) {
canvas.drawText( canvas.drawText(
mTimestamps[index], mTimestamps[index],
xOffsets[index] - xOffsets[index]
(mTimestampsBounds[index].width() - mTimestampsBounds[index].left) * .5f, - (mTimestampsBounds[index].width() - mTimestampsBounds[index].left)
getTimestampY(index), mTextPaint); * .5f,
getTimestampY(index), mTextPaint);
} }
} }
private int getTimestampY(int index) { private int getTimestampY(int index) {
return getHeight() - mTimestampsBounds[index].height() return getHeight() - mTimestampsBounds[index].height()
+ (mTimestampsBounds[index].height() + mTimestampsBounds[index].top) + (mTimestampsBounds[index].height() + mTimestampsBounds[index].top)
+ round(mTextPadding * 1.5f); + round(mTextPadding * 1.5f);
} }
private void drawTrapezoids(Canvas canvas) { private void drawTrapezoids(Canvas canvas) {
@@ -504,8 +513,8 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
return; return;
} }
final float trapezoidBottom = final float trapezoidBottom =
getHeight() - mIndent.bottom - mDividerHeight - mDividerWidth getHeight() - mIndent.bottom - mDividerHeight - mDividerWidth
- mTrapezoidVOffset; - mTrapezoidVOffset;
final float availableSpace = trapezoidBottom - mDividerWidth * .5f - mIndent.top; final float availableSpace = trapezoidBottom - mDividerWidth * .5f - mIndent.top;
final float unitHeight = availableSpace / 100f; final float unitHeight = availableSpace / 100f;
// Draws all trapezoid shapes into the canvas. // Draws all trapezoid shapes into the canvas.
@@ -522,12 +531,12 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
} }
// Configures the trapezoid paint color. // Configures the trapezoid paint color.
final int trapezoidColor = final int trapezoidColor =
!mIsSlotsClickabled !mIsSlotsClickabled
? mTrapezoidColor ? mTrapezoidColor
: mSelectedIndex == index || mSelectedIndex == SELECTED_INDEX_ALL : mSelectedIndex == index || mSelectedIndex == SELECTED_INDEX_ALL
? mTrapezoidSolidColor : mTrapezoidColor; ? mTrapezoidSolidColor : mTrapezoidColor;
final boolean isHoverState = final boolean isHoverState =
mIsSlotsClickabled && mHoveredIndex == index && isValidToDraw(mHoveredIndex); mIsSlotsClickabled && mHoveredIndex == index && isValidToDraw(mHoveredIndex);
mTrapezoidPaint.setColor(isHoverState ? mTrapezoidHoverColor : trapezoidColor); mTrapezoidPaint.setColor(isHoverState ? mTrapezoidHoverColor : trapezoidColor);
final float leftTop = round(trapezoidBottom - mLevels[index] * unitHeight); final float leftTop = round(trapezoidBottom - mLevels[index] * unitHeight);
@@ -546,7 +555,7 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
// Generates path for non-clickable trapezoid curve. // Generates path for non-clickable trapezoid curve.
if (mTrapezoidCurvePaint != null) { if (mTrapezoidCurvePaint != null) {
if (trapezoidCurvePath == null) { if (trapezoidCurvePath == null) {
trapezoidCurvePath= new Path(); trapezoidCurvePath = new Path();
trapezoidCurvePath.moveTo(mTrapezoidSlots[index].mLeft, leftTop); trapezoidCurvePath.moveTo(mTrapezoidSlots[index].mLeft, leftTop);
} else { } else {
trapezoidCurvePath.lineTo(mTrapezoidSlots[index].mLeft, leftTop); trapezoidCurvePath.lineTo(mTrapezoidSlots[index].mLeft, leftTop);
@@ -582,23 +591,23 @@ public class BatteryChartView extends AppCompatImageView implements View.OnClick
} }
private static String[] getPercentages() { private static String[] getPercentages() {
return new String[] { return new String[]{
formatPercentage(/*percentage=*/ 100, /*round=*/ true), formatPercentage(/*percentage=*/ 100, /*round=*/ true),
formatPercentage(/*percentage=*/ 50, /*round=*/ true), formatPercentage(/*percentage=*/ 50, /*round=*/ true),
formatPercentage(/*percentage=*/ 0, /*round=*/ true)}; formatPercentage(/*percentage=*/ 0, /*round=*/ true)};
} }
@VisibleForTesting @VisibleForTesting
static boolean isAccessibilityEnabled(Context context) { static boolean isAccessibilityEnabled(Context context) {
final AccessibilityManager accessibilityManager = final AccessibilityManager accessibilityManager =
context.getSystemService(AccessibilityManager.class); context.getSystemService(AccessibilityManager.class);
if (!accessibilityManager.isEnabled()) { if (!accessibilityManager.isEnabled()) {
return false; return false;
} }
final List<AccessibilityServiceInfo> serviceInfoList = final List<AccessibilityServiceInfo> serviceInfoList =
accessibilityManager.getEnabledAccessibilityServiceList( accessibilityManager.getEnabledAccessibilityServiceList(
AccessibilityServiceInfo.FEEDBACK_SPOKEN AccessibilityServiceInfo.FEEDBACK_SPOKEN
| AccessibilityServiceInfo.FEEDBACK_GENERIC); | AccessibilityServiceInfo.FEEDBACK_GENERIC);
for (AccessibilityServiceInfo info : serviceInfoList) { for (AccessibilityServiceInfo info : serviceInfoList) {
for (String serviceName : ACCESSIBILITY_SERVICE_NAMES) { for (String serviceName : ACCESSIBILITY_SERVICE_NAMES) {
final String serviceId = info.getId(); final String serviceId = info.getId();

View File

@@ -1,17 +1,19 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * Licensed under the Apache License, Version 2.0 (the "License");
* except in compliance with the License. You may obtain a copy of the License at * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software distributed under the * Unless required by applicable law or agreed to in writing, software
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * distributed under the License is distributed on an "AS IS" BASIS,
* KIND, either express or implied. See the License for the specific language governing * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* permissions and limitations under the License. * See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import android.content.Context; import android.content.Context;
import android.content.pm.ApplicationInfo; import android.content.pm.ApplicationInfo;
@@ -26,6 +28,7 @@ import android.util.Log;
import androidx.annotation.VisibleForTesting; import androidx.annotation.VisibleForTesting;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settingslib.utils.StringUtil; import com.android.settingslib.utils.StringUtil;
import java.util.Comparator; import java.util.Comparator;
@@ -61,11 +64,16 @@ public class BatteryDiffEntry {
private UserManager mUserManager; private UserManager mUserManager;
private String mDefaultPackageName = null; private String mDefaultPackageName = null;
@VisibleForTesting int mAppIconId; @VisibleForTesting
@VisibleForTesting String mAppLabel = null; int mAppIconId;
@VisibleForTesting Drawable mAppIcon = null; @VisibleForTesting
@VisibleForTesting boolean mIsLoaded = false; String mAppLabel = null;
@VisibleForTesting boolean mValidForRestriction = true; @VisibleForTesting
Drawable mAppIcon = null;
@VisibleForTesting
boolean mIsLoaded = false;
@VisibleForTesting
boolean mValidForRestriction = true;
public BatteryDiffEntry( public BatteryDiffEntry(
Context context, Context context,
@@ -85,7 +93,7 @@ public class BatteryDiffEntry {
public void setTotalConsumePower(double totalConsumePower) { public void setTotalConsumePower(double totalConsumePower) {
mTotalConsumePower = totalConsumePower; mTotalConsumePower = totalConsumePower;
mPercentOfTotal = totalConsumePower == 0 mPercentOfTotal = totalConsumePower == 0
? 0 : (mConsumePower / mTotalConsumePower) * 100.0; ? 0 : (mConsumePower / mTotalConsumePower) * 100.0;
} }
/** Gets the percentage of total consumed power. */ /** Gets the percentage of total consumed power. */
@@ -96,11 +104,11 @@ public class BatteryDiffEntry {
/** Clones a new instance. */ /** Clones a new instance. */
public BatteryDiffEntry clone() { public BatteryDiffEntry clone() {
return new BatteryDiffEntry( return new BatteryDiffEntry(
this.mContext, this.mContext,
this.mForegroundUsageTimeInMs, this.mForegroundUsageTimeInMs,
this.mBackgroundUsageTimeInMs, this.mBackgroundUsageTimeInMs,
this.mConsumePower, this.mConsumePower,
this.mBatteryHistEntry /*same instance*/); this.mBatteryHistEntry /*same instance*/);
} }
/** Gets the app label name for this entry. */ /** Gets the app label name for this entry. */
@@ -108,8 +116,8 @@ public class BatteryDiffEntry {
loadLabelAndIcon(); loadLabelAndIcon();
// Returns default applicationn label if we cannot find it. // Returns default applicationn label if we cannot find it.
return mAppLabel == null || mAppLabel.length() == 0 return mAppLabel == null || mAppLabel.length() == 0
? mBatteryHistEntry.mAppLabel ? mBatteryHistEntry.mAppLabel
: mAppLabel; : mAppLabel;
} }
/** Gets the app icon {@link Drawable} for this entry. */ /** Gets the app icon {@link Drawable} for this entry. */
@@ -129,15 +137,15 @@ public class BatteryDiffEntry {
/** Gets the searching package name for UID battery type. */ /** Gets the searching package name for UID battery type. */
public String getPackageName() { public String getPackageName() {
final String packageName = mDefaultPackageName != null final String packageName = mDefaultPackageName != null
? mDefaultPackageName : mBatteryHistEntry.mPackageName; ? mDefaultPackageName : mBatteryHistEntry.mPackageName;
if (packageName == null) { if (packageName == null) {
return packageName; return packageName;
} }
// Removes potential appended process name in the PackageName. // Removes potential appended process name in the PackageName.
// From "com.opera.browser:privileged_process0" to "com.opera.browser" // From "com.opera.browser:privileged_process0" to "com.opera.browser"
final String[] splittedPackageNames = packageName.split(":"); final String[] splitPackageNames = packageName.split(":");
return splittedPackageNames != null && splittedPackageNames.length > 0 return splitPackageNames != null && splitPackageNames.length > 0
? splittedPackageNames[0] : packageName; ? splitPackageNames[0] : packageName;
} }
/** Whether this item is valid for users to launch restriction page? */ /** Whether this item is valid for users to launch restriction page? */
@@ -196,20 +204,20 @@ public class BatteryDiffEntry {
switch (mBatteryHistEntry.mConsumerType) { switch (mBatteryHistEntry.mConsumerType) {
case ConvertUtils.CONSUMER_TYPE_USER_BATTERY: case ConvertUtils.CONSUMER_TYPE_USER_BATTERY:
final BatteryEntry.NameAndIcon nameAndIconForUser = final BatteryEntry.NameAndIcon nameAndIconForUser =
BatteryEntry.getNameAndIconFromUserId( BatteryEntry.getNameAndIconFromUserId(
mContext, (int) mBatteryHistEntry.mUserId); mContext, (int) mBatteryHistEntry.mUserId);
if (nameAndIconForUser != null) { if (nameAndIconForUser != null) {
mAppIcon = nameAndIconForUser.mIcon; mAppIcon = nameAndIconForUser.mIcon;
mAppLabel = nameAndIconForUser.mName; mAppLabel = nameAndIconForUser.mName;
sResourceCache.put( sResourceCache.put(
getKey(), getKey(),
new BatteryEntry.NameAndIcon(mAppLabel, mAppIcon, /*iconId=*/ 0)); new BatteryEntry.NameAndIcon(mAppLabel, mAppIcon, /*iconId=*/ 0));
} }
break; break;
case ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY: case ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY:
final BatteryEntry.NameAndIcon nameAndIconForSystem = final BatteryEntry.NameAndIcon nameAndIconForSystem =
BatteryEntry.getNameAndIconFromPowerComponent( BatteryEntry.getNameAndIconFromPowerComponent(
mContext, mBatteryHistEntry.mDrainType); mContext, mBatteryHistEntry.mDrainType);
if (nameAndIconForSystem != null) { if (nameAndIconForSystem != null) {
mAppLabel = nameAndIconForSystem.mName; mAppLabel = nameAndIconForSystem.mName;
if (nameAndIconForSystem.mIconId != 0) { if (nameAndIconForSystem.mIconId != 0) {
@@ -217,8 +225,8 @@ public class BatteryDiffEntry {
mAppIcon = mContext.getDrawable(nameAndIconForSystem.mIconId); mAppIcon = mContext.getDrawable(nameAndIconForSystem.mIconId);
} }
sResourceCache.put( sResourceCache.put(
getKey(), getKey(),
new BatteryEntry.NameAndIcon(mAppLabel, mAppIcon, mAppIconId)); new BatteryEntry.NameAndIcon(mAppLabel, mAppIcon, mAppIconId));
} }
break; break;
case ConvertUtils.CONSUMER_TYPE_UID_BATTERY: case ConvertUtils.CONSUMER_TYPE_UID_BATTERY:
@@ -231,8 +239,8 @@ public class BatteryDiffEntry {
mAppIcon = getBadgeIconForUser(mAppIcon); mAppIcon = getBadgeIconForUser(mAppIcon);
if (mAppLabel != null || mAppIcon != null) { if (mAppLabel != null || mAppIcon != null) {
sResourceCache.put( sResourceCache.put(
getKey(), getKey(),
new BatteryEntry.NameAndIcon(mAppLabel, mAppIcon, /*iconId=*/ 0)); new BatteryEntry.NameAndIcon(mAppLabel, mAppIcon, /*iconId=*/ 0));
} }
break; break;
} }
@@ -251,23 +259,23 @@ public class BatteryDiffEntry {
} }
final boolean isValidPackage = final boolean isValidPackage =
BatteryUtils.getInstance(mContext).getPackageUid(getPackageName()) BatteryUtils.getInstance(mContext).getPackageUid(getPackageName())
!= BatteryUtils.UID_NULL; != BatteryUtils.UID_NULL;
if (!isValidPackage) { if (!isValidPackage) {
mValidForRestriction = false; mValidForRestriction = false;
return; return;
} }
try { try {
mValidForRestriction = mValidForRestriction =
mContext.getPackageManager().getPackageInfo( mContext.getPackageManager().getPackageInfo(
getPackageName(), getPackageName(),
PackageManager.MATCH_DISABLED_COMPONENTS PackageManager.MATCH_DISABLED_COMPONENTS
| PackageManager.MATCH_ANY_USER | PackageManager.MATCH_ANY_USER
| PackageManager.GET_SIGNATURES | PackageManager.GET_SIGNATURES
| PackageManager.GET_PERMISSIONS) | PackageManager.GET_PERMISSIONS)
!= null; != null;
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, String.format("getPackageInfo() error %s for package=%s", Log.e(TAG, String.format("getPackageInfo() error %s for package=%s",
e.getCause(), getPackageName())); e.getCause(), getPackageName()));
mValidForRestriction = false; mValidForRestriction = false;
} }
} }
@@ -276,7 +284,7 @@ public class BatteryDiffEntry {
final Locale locale = Locale.getDefault(); final Locale locale = Locale.getDefault();
if (sCurrentLocale != locale) { if (sCurrentLocale != locale) {
Log.d(TAG, String.format("clearCache() locale is changed from %s to %s", Log.d(TAG, String.format("clearCache() locale is changed from %s to %s",
sCurrentLocale, locale)); sCurrentLocale, locale));
sCurrentLocale = locale; sCurrentLocale = locale;
clearCache(); clearCache();
} }
@@ -290,7 +298,7 @@ public class BatteryDiffEntry {
if (packageName != null && packageName.length() != 0) { if (packageName != null && packageName.length() != 0) {
try { try {
final ApplicationInfo appInfo = final ApplicationInfo appInfo =
packageManager.getApplicationInfo(packageName, /*no flags*/ 0); packageManager.getApplicationInfo(packageName, /*no flags*/ 0);
if (appInfo != null) { if (appInfo != null) {
mAppLabel = packageManager.getApplicationLabel(appInfo).toString(); mAppLabel = packageManager.getApplicationLabel(appInfo).toString();
mAppIcon = packageManager.getApplicationIcon(appInfo); mAppIcon = packageManager.getApplicationIcon(appInfo);
@@ -310,15 +318,15 @@ public class BatteryDiffEntry {
// Loads special defined application label and icon if available. // Loads special defined application label and icon if available.
if (packages == null || packages.length == 0) { if (packages == null || packages.length == 0) {
final BatteryEntry.NameAndIcon nameAndIcon = final BatteryEntry.NameAndIcon nameAndIcon =
BatteryEntry.getNameAndIconFromUid(mContext, mAppLabel, uid); BatteryEntry.getNameAndIconFromUid(mContext, mAppLabel, uid);
mAppLabel = nameAndIcon.mName; mAppLabel = nameAndIcon.mName;
mAppIcon = nameAndIcon.mIcon; mAppIcon = nameAndIcon.mIcon;
} }
final BatteryEntry.NameAndIcon nameAndIcon = final BatteryEntry.NameAndIcon nameAndIcon =
BatteryEntry.loadNameAndIcon( BatteryEntry.loadNameAndIcon(
mContext, uid, /*handler=*/ null, /*batteryEntry=*/ null, mContext, uid, /*handler=*/ null, /*batteryEntry=*/ null,
packageName, mAppLabel, mAppIcon); packageName, mAppLabel, mAppIcon);
// Clears BatteryEntry internal cache since we will have another one. // Clears BatteryEntry internal cache since we will have another one.
BatteryEntry.clearUidCache(); BatteryEntry.clearUidCache();
if (nameAndIcon != null) { if (nameAndIcon != null) {
@@ -328,7 +336,7 @@ public class BatteryDiffEntry {
if (mDefaultPackageName != null if (mDefaultPackageName != null
&& !mDefaultPackageName.equals(nameAndIcon.mPackageName)) { && !mDefaultPackageName.equals(nameAndIcon.mPackageName)) {
Log.w(TAG, String.format("found different package: %s | %s", Log.w(TAG, String.format("found different package: %s | %s",
mDefaultPackageName, nameAndIcon.mPackageName)); mDefaultPackageName, nameAndIcon.mPackageName));
} }
} }
} }
@@ -336,19 +344,19 @@ public class BatteryDiffEntry {
@Override @Override
public String toString() { public String toString() {
final StringBuilder builder = new StringBuilder() final StringBuilder builder = new StringBuilder()
.append("BatteryDiffEntry{") .append("BatteryDiffEntry{")
.append(String.format("\n\tname=%s restrictable=%b", .append(String.format("\n\tname=%s restrictable=%b",
mAppLabel, mValidForRestriction)) mAppLabel, mValidForRestriction))
.append(String.format("\n\tconsume=%.2f%% %f/%f", .append(String.format("\n\tconsume=%.2f%% %f/%f",
mPercentOfTotal, mConsumePower, mTotalConsumePower)) mPercentOfTotal, mConsumePower, mTotalConsumePower))
.append(String.format("\n\tforeground:%s background:%s", .append(String.format("\n\tforeground:%s background:%s",
StringUtil.formatElapsedTime(mContext, mForegroundUsageTimeInMs, StringUtil.formatElapsedTime(mContext, mForegroundUsageTimeInMs,
/*withSeconds=*/ true, /*collapseTimeUnit=*/ false), /*withSeconds=*/ true, /*collapseTimeUnit=*/ false),
StringUtil.formatElapsedTime(mContext, mBackgroundUsageTimeInMs, StringUtil.formatElapsedTime(mContext, mBackgroundUsageTimeInMs,
/*withSeconds=*/ true, /*collapseTimeUnit=*/ false))) /*withSeconds=*/ true, /*collapseTimeUnit=*/ false)))
.append(String.format("\n\tpackage:%s|%s uid:%d userId:%d", .append(String.format("\n\tpackage:%s|%s uid:%d userId:%d",
mBatteryHistEntry.mPackageName, getPackageName(), mBatteryHistEntry.mPackageName, getPackageName(),
mBatteryHistEntry.mUid, mBatteryHistEntry.mUserId)); mBatteryHistEntry.mUid, mBatteryHistEntry.mUserId));
return builder.toString(); return builder.toString();
} }
@@ -361,7 +369,7 @@ public class BatteryDiffEntry {
private Drawable getBadgeIconForUser(Drawable icon) { private Drawable getBadgeIconForUser(Drawable icon) {
final int userId = UserHandle.getUserId((int) mBatteryHistEntry.mUid); final int userId = UserHandle.getUserId((int) mBatteryHistEntry.mUid);
return userId == UserHandle.USER_OWNER ? icon : return userId == UserHandle.USER_OWNER ? icon :
mUserManager.getBadgedIconForUser(icon, new UserHandle(userId)); mUserManager.getBadgedIconForUser(icon, new UserHandle(userId));
} }
private static boolean isSystemUid(int uid) { private static boolean isSystemUid(int uid) {

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2014 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import android.app.AppGlobals; import android.app.AppGlobals;
import android.content.Context; import android.content.Context;
@@ -36,9 +36,8 @@ import android.os.UserManager;
import android.util.DebugUtils; import android.util.DebugUtils;
import android.util.Log; import android.util.Log;
import androidx.annotation.NonNull;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settingslib.Utils; import com.android.settingslib.Utils;
import java.util.ArrayList; import java.util.ArrayList;
@@ -52,6 +51,7 @@ import java.util.Locale;
*/ */
public class BatteryEntry { public class BatteryEntry {
/** The app name and icon in app list. */
public static final class NameAndIcon { public static final class NameAndIcon {
public final String mName; public final String mName;
public final String mPackageName; public final String mPackageName;
@@ -84,10 +84,10 @@ public class BatteryEntry {
static Locale sCurrentLocale = null; static Locale sCurrentLocale = null;
static private class NameAndIconLoader extends Thread { private static class NameAndIconLoader extends Thread {
private boolean mAbort = false; private boolean mAbort = false;
public NameAndIconLoader() { NameAndIconLoader() {
super("BatteryUsage Icon Loader"); super("BatteryUsage Icon Loader");
} }
@@ -109,9 +109,9 @@ public class BatteryEntry {
be = sRequestQueue.remove(0); be = sRequestQueue.remove(0);
} }
final NameAndIcon nameAndIcon = final NameAndIcon nameAndIcon =
BatteryEntry.loadNameAndIcon( BatteryEntry.loadNameAndIcon(
be.mContext, be.getUid(), sHandler, be, be.mContext, be.getUid(), sHandler, be,
be.mDefaultPackageName, be.mName, be.mIcon); be.mDefaultPackageName, be.mName, be.mIcon);
if (nameAndIcon != null) { if (nameAndIcon != null) {
be.mIcon = nameAndIcon.mIcon; be.mIcon = nameAndIcon.mIcon;
be.mName = nameAndIcon.mName; be.mName = nameAndIcon.mName;
@@ -121,35 +121,38 @@ public class BatteryEntry {
} }
} }
private static NameAndIconLoader mRequestThread; private static NameAndIconLoader sRequestThread;
/** Starts the request queue. */
public static void startRequestQueue() { public static void startRequestQueue() {
if (sHandler != null) { if (sHandler != null) {
synchronized (sRequestQueue) { synchronized (sRequestQueue) {
if (!sRequestQueue.isEmpty()) { if (!sRequestQueue.isEmpty()) {
if (mRequestThread != null) { if (sRequestThread != null) {
mRequestThread.abort(); sRequestThread.abort();
} }
mRequestThread = new NameAndIconLoader(); sRequestThread = new NameAndIconLoader();
mRequestThread.setPriority(Thread.MIN_PRIORITY); sRequestThread.setPriority(Thread.MIN_PRIORITY);
mRequestThread.start(); sRequestThread.start();
sRequestQueue.notify(); sRequestQueue.notify();
} }
} }
} }
} }
/** Stops the request queue. */
public static void stopRequestQueue() { public static void stopRequestQueue() {
synchronized (sRequestQueue) { synchronized (sRequestQueue) {
if (mRequestThread != null) { if (sRequestThread != null) {
mRequestThread.abort(); sRequestThread.abort();
mRequestThread = null; sRequestThread = null;
sRequestQueue.clear(); sRequestQueue.clear();
sHandler = null; sHandler = null;
} }
} }
} }
/** Clears the UID cache. */
public static void clearUidCache() { public static void clearUidCache() {
sUidCache.clear(); sUidCache.clear();
} }
@@ -252,14 +255,14 @@ public class BatteryEntry {
mIsHidden = false; mIsHidden = false;
mPowerComponentId = powerComponentId; mPowerComponentId = powerComponentId;
mConsumedPower = mConsumedPower =
powerComponentId == BatteryConsumer.POWER_COMPONENT_SCREEN powerComponentId == BatteryConsumer.POWER_COMPONENT_SCREEN
? devicePowerMah ? devicePowerMah
: devicePowerMah - appsPowerMah; : devicePowerMah - appsPowerMah;
mUsageDurationMs = usageDurationMs; mUsageDurationMs = usageDurationMs;
mConsumerType = ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY; mConsumerType = ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY;
final NameAndIcon nameAndIcon = final NameAndIcon nameAndIcon =
getNameAndIconFromPowerComponent(context, powerComponentId); getNameAndIconFromPowerComponent(context, powerComponentId);
mIconId = nameAndIcon.mIconId; mIconId = nameAndIcon.mIconId;
mName = nameAndIcon.mName; mName = nameAndIcon.mName;
if (mIconId != 0) { if (mIconId != 0) {
@@ -280,9 +283,9 @@ public class BatteryEntry {
mIcon = context.getDrawable(mIconId); mIcon = context.getDrawable(mIconId);
mName = powerComponentName; mName = powerComponentName;
mConsumedPower = mConsumedPower =
powerComponentId == BatteryConsumer.POWER_COMPONENT_SCREEN powerComponentId == BatteryConsumer.POWER_COMPONENT_SCREEN
? devicePowerMah ? devicePowerMah
: devicePowerMah - appsPowerMah; : devicePowerMah - appsPowerMah;
mConsumerType = ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY; mConsumerType = ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY;
} }
@@ -354,7 +357,7 @@ public class BatteryEntry {
final PackageManager pm = context.getPackageManager(); final PackageManager pm = context.getPackageManager();
final String[] packages = isSystemUid(uid) final String[] packages = isSystemUid(uid)
? new String[] {PACKAGE_SYSTEM} : pm.getPackagesForUid(uid); ? new String[]{PACKAGE_SYSTEM} : pm.getPackagesForUid(uid);
if (packages != null) { if (packages != null) {
final String[] packageLabels = new String[packages.length]; final String[] packageLabels = new String[packages.length];
System.arraycopy(packages, 0, packageLabels, 0, packages.length); System.arraycopy(packages, 0, packageLabels, 0, packages.length);
@@ -552,8 +555,8 @@ public class BatteryEntry {
name = context.getResources().getString(R.string.process_network_tethering); name = context.getResources().getString(R.string.process_network_tethering);
} else if ("mediaserver".equals(name)) { } else if ("mediaserver".equals(name)) {
name = context.getResources().getString(R.string.process_mediaserver_label); name = context.getResources().getString(R.string.process_mediaserver_label);
} else if ("dex2oat".equals(name) || "dex2oat32".equals(name) || } else if ("dex2oat".equals(name) || "dex2oat32".equals(name)
"dex2oat64".equals(name)) { || "dex2oat64".equals(name)) {
name = context.getResources().getString(R.string.process_dex2oat_label); name = context.getResources().getString(R.string.process_dex2oat_label);
} }
return new NameAndIcon(name, icon, 0 /* iconId */); return new NameAndIcon(name, icon, 0 /* iconId */);
@@ -612,7 +615,8 @@ public class BatteryEntry {
return new NameAndIcon(name, null /* icon */, iconId); return new NameAndIcon(name, null /* icon */, iconId);
} }
static boolean isSystemUid(int uid) { /** Whether the uid is system uid. */
public static boolean isSystemUid(int uid) {
return uid == Process.SYSTEM_UID; return uid == Process.SYSTEM_UID;
} }
} }

View File

@@ -1,17 +1,19 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * Licensed under the Apache License, Version 2.0 (the "License");
* except in compliance with the License. You may obtain a copy of the License at * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software distributed under the * Unless required by applicable law or agreed to in writing, software
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * distributed under the License is distributed on an "AS IS" BASIS,
* KIND, either express or implied. See the License for the specific language governing * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* permissions and limitations under the License. * See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import android.content.ContentValues; import android.content.ContentValues;
import android.database.Cursor; import android.database.Cursor;
@@ -117,14 +119,14 @@ public class BatteryHistEntry {
} }
private BatteryHistEntry( private BatteryHistEntry(
BatteryHistEntry fromEntry, BatteryHistEntry fromEntry,
long bootTimestamp, long bootTimestamp,
long timestamp, long timestamp,
double totalPower, double totalPower,
double consumePower, double consumePower,
long foregroundUsageTimeInMs, long foregroundUsageTimeInMs,
long backgroundUsageTimeInMs, long backgroundUsageTimeInMs,
int batteryLevel) { int batteryLevel) {
mUid = fromEntry.mUid; mUid = fromEntry.mUid;
mUserId = fromEntry.mUserId; mUserId = fromEntry.mUserId;
mAppLabel = fromEntry.mAppLabel; mAppLabel = fromEntry.mAppLabel;
@@ -186,28 +188,28 @@ public class BatteryHistEntry {
@Override @Override
public String toString() { public String toString() {
final String recordAtDateTime = final String recordAtDateTime =
ConvertUtils.utcToLocalTime(/*context=*/ null, mTimestamp); ConvertUtils.utcToLocalTime(/*context=*/ null, mTimestamp);
final StringBuilder builder = new StringBuilder() final StringBuilder builder = new StringBuilder()
.append("\nBatteryHistEntry{") .append("\nBatteryHistEntry{")
.append(String.format("\n\tpackage=%s|label=%s|uid=%d|userId=%d|isHidden=%b", .append(String.format("\n\tpackage=%s|label=%s|uid=%d|userId=%d|isHidden=%b",
mPackageName, mAppLabel, mUid, mUserId, mIsHidden)) mPackageName, mAppLabel, mUid, mUserId, mIsHidden))
.append(String.format("\n\ttimestamp=%s|zoneId=%s|bootTimestamp=%d", .append(String.format("\n\ttimestamp=%s|zoneId=%s|bootTimestamp=%d",
recordAtDateTime, mZoneId, Duration.ofMillis(mBootTimestamp).getSeconds())) recordAtDateTime, mZoneId, Duration.ofMillis(mBootTimestamp).getSeconds()))
.append(String.format("\n\tusage=%f|total=%f|consume=%f|elapsedTime=%d|%d", .append(String.format("\n\tusage=%f|total=%f|consume=%f|elapsedTime=%d|%d",
mPercentOfTotal, mTotalPower, mConsumePower, mPercentOfTotal, mTotalPower, mConsumePower,
Duration.ofMillis(mForegroundUsageTimeInMs).getSeconds(), Duration.ofMillis(mForegroundUsageTimeInMs).getSeconds(),
Duration.ofMillis(mBackgroundUsageTimeInMs).getSeconds())) Duration.ofMillis(mBackgroundUsageTimeInMs).getSeconds()))
.append(String.format("\n\tdrainType=%d|consumerType=%d", .append(String.format("\n\tdrainType=%d|consumerType=%d",
mDrainType, mConsumerType)) mDrainType, mConsumerType))
.append(String.format("\n\tbattery=%d|status=%d|health=%d\n}", .append(String.format("\n\tbattery=%d|status=%d|health=%d\n}",
mBatteryLevel, mBatteryStatus, mBatteryHealth)); mBatteryLevel, mBatteryStatus, mBatteryHealth));
return builder.toString(); return builder.toString();
} }
private int getInteger(ContentValues values, String key) { private int getInteger(ContentValues values, String key) {
if (values != null && values.containsKey(key)) { if (values != null && values.containsKey(key)) {
return values.getAsInteger(key); return values.getAsInteger(key);
}; }
mIsValidEntry = false; mIsValidEntry = false;
return 0; return 0;
} }
@@ -298,21 +300,21 @@ public class BatteryHistEntry {
BatteryHistEntry lowerHistEntry, BatteryHistEntry lowerHistEntry,
BatteryHistEntry upperHistEntry) { BatteryHistEntry upperHistEntry) {
final double totalPower = interpolate( final double totalPower = interpolate(
lowerHistEntry == null ? 0 : lowerHistEntry.mTotalPower, lowerHistEntry == null ? 0 : lowerHistEntry.mTotalPower,
upperHistEntry.mTotalPower, upperHistEntry.mTotalPower,
ratio); ratio);
final double consumePower = interpolate( final double consumePower = interpolate(
lowerHistEntry == null ? 0 : lowerHistEntry.mConsumePower, lowerHistEntry == null ? 0 : lowerHistEntry.mConsumePower,
upperHistEntry.mConsumePower, upperHistEntry.mConsumePower,
ratio); ratio);
final double foregroundUsageTimeInMs = interpolate( final double foregroundUsageTimeInMs = interpolate(
lowerHistEntry == null ? 0 : lowerHistEntry.mForegroundUsageTimeInMs, lowerHistEntry == null ? 0 : lowerHistEntry.mForegroundUsageTimeInMs,
upperHistEntry.mForegroundUsageTimeInMs, upperHistEntry.mForegroundUsageTimeInMs,
ratio); ratio);
final double backgroundUsageTimeInMs = interpolate( final double backgroundUsageTimeInMs = interpolate(
lowerHistEntry == null ? 0 : lowerHistEntry.mBackgroundUsageTimeInMs, lowerHistEntry == null ? 0 : lowerHistEntry.mBackgroundUsageTimeInMs,
upperHistEntry.mBackgroundUsageTimeInMs, upperHistEntry.mBackgroundUsageTimeInMs,
ratio); ratio);
// Checks whether there is any abnoaml cases! // Checks whether there is any abnoaml cases!
if (upperHistEntry.mConsumePower < consumePower if (upperHistEntry.mConsumePower < consumePower
|| upperHistEntry.mForegroundUsageTimeInMs < foregroundUsageTimeInMs || upperHistEntry.mForegroundUsageTimeInMs < foregroundUsageTimeInMs
@@ -324,22 +326,22 @@ public class BatteryHistEntry {
} }
} }
final double batteryLevel = final double batteryLevel =
lowerHistEntry == null lowerHistEntry == null
? upperHistEntry.mBatteryLevel ? upperHistEntry.mBatteryLevel
: interpolate( : interpolate(
lowerHistEntry.mBatteryLevel, lowerHistEntry.mBatteryLevel,
upperHistEntry.mBatteryLevel, upperHistEntry.mBatteryLevel,
ratio); ratio);
return new BatteryHistEntry( return new BatteryHistEntry(
upperHistEntry, upperHistEntry,
/*bootTimestamp=*/ upperHistEntry.mBootTimestamp /*bootTimestamp=*/ upperHistEntry.mBootTimestamp
- (upperTimestamp - slotTimestamp), - (upperTimestamp - slotTimestamp),
/*timestamp=*/ slotTimestamp, /*timestamp=*/ slotTimestamp,
totalPower, totalPower,
consumePower, consumePower,
Math.round(foregroundUsageTimeInMs), Math.round(foregroundUsageTimeInMs),
Math.round(backgroundUsageTimeInMs), Math.round(backgroundUsageTimeInMs),
(int) Math.round(batteryLevel)); (int) Math.round(batteryLevel));
} }
private static double interpolate(double v1, double v2, double ratio) { private static double interpolate(double v1, double v2, double ratio) {

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,10 +13,11 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import android.content.Context; import android.content.Context;
import com.android.settings.fuelgauge.PowerUsageFeatureProvider;
import com.android.settings.overlay.FeatureFactory; import com.android.settings.overlay.FeatureFactory;
import com.android.settingslib.utils.AsyncLoaderCompat; import com.android.settingslib.utils.AsyncLoaderCompat;
@@ -41,7 +42,7 @@ public class BatteryHistoryLoader
@Override @Override
public Map<Long, Map<String, BatteryHistEntry>> loadInBackground() { public Map<Long, Map<String, BatteryHistEntry>> loadInBackground() {
final PowerUsageFeatureProvider powerUsageFeatureProvider = final PowerUsageFeatureProvider powerUsageFeatureProvider =
FeatureFactory.getFactory(mContext).getPowerUsageFeatureProvider(mContext); FeatureFactory.getFactory(mContext).getPowerUsageFeatureProvider(mContext);
return powerUsageFeatureProvider.getBatteryHistory(mContext); return powerUsageFeatureProvider.getBatteryHistory(mContext);
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2010 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import android.content.Context; import android.content.Context;
import android.os.BatteryUsageStats; import android.os.BatteryUsageStats;
@@ -29,6 +29,8 @@ import androidx.preference.Preference;
import androidx.preference.PreferenceViewHolder; import androidx.preference.PreferenceViewHolder;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.fuelgauge.BatteryInfo;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.overlay.FeatureFactory; import com.android.settings.overlay.FeatureFactory;
import com.android.settings.widget.UsageView; import com.android.settings.widget.UsageView;
@@ -38,8 +40,10 @@ import com.android.settings.widget.UsageView;
public class BatteryHistoryPreference extends Preference { public class BatteryHistoryPreference extends Preference {
private static final String TAG = "BatteryHistoryPreference"; private static final String TAG = "BatteryHistoryPreference";
@VisibleForTesting boolean mHideSummary; @VisibleForTesting
@VisibleForTesting BatteryInfo mBatteryInfo; boolean mHideSummary;
@VisibleForTesting
BatteryInfo mBatteryInfo;
private boolean mIsChartGraphEnabled; private boolean mIsChartGraphEnabled;
@@ -51,16 +55,17 @@ public class BatteryHistoryPreference extends Preference {
public BatteryHistoryPreference(Context context, AttributeSet attrs) { public BatteryHistoryPreference(Context context, AttributeSet attrs) {
super(context, attrs); super(context, attrs);
mIsChartGraphEnabled = mIsChartGraphEnabled =
FeatureFactory.getFactory(context).getPowerUsageFeatureProvider(context) FeatureFactory.getFactory(context).getPowerUsageFeatureProvider(context)
.isChartGraphEnabled(context); .isChartGraphEnabled(context);
Log.i(TAG, "isChartGraphEnabled: " + mIsChartGraphEnabled); Log.i(TAG, "isChartGraphEnabled: " + mIsChartGraphEnabled);
setLayoutResource( setLayoutResource(
mIsChartGraphEnabled mIsChartGraphEnabled
? R.layout.battery_chart_graph ? R.layout.battery_chart_graph
: R.layout.battery_usage_graph); : R.layout.battery_usage_graph);
setSelectable(false); setSelectable(false);
} }
/** Sets the text of bottom summary. */
public void setBottomSummary(CharSequence text) { public void setBottomSummary(CharSequence text) {
mSummaryContent = text; mSummaryContent = text;
if (mSummaryView != null) { if (mSummaryView != null) {
@@ -70,6 +75,7 @@ public class BatteryHistoryPreference extends Preference {
mHideSummary = false; mHideSummary = false;
} }
/** Hides the bottom summary. */
public void hideBottomSummary() { public void hideBottomSummary() {
if (mSummaryView != null) { if (mSummaryView != null) {
mSummaryView.setVisibility(View.GONE); mSummaryView.setVisibility(View.GONE);
@@ -101,7 +107,7 @@ public class BatteryHistoryPreference extends Preference {
if (mIsChartGraphEnabled) { if (mIsChartGraphEnabled) {
mBatteryChartView = (BatteryChartView) view.findViewById(R.id.battery_chart); mBatteryChartView = (BatteryChartView) view.findViewById(R.id.battery_chart);
mBatteryChartView.setCompanionTextView( mBatteryChartView.setCompanionTextView(
(TextView) view.findViewById(R.id.companion_text)); (TextView) view.findViewById(R.id.companion_text));
if (mChartPreferenceController != null) { if (mChartPreferenceController != null) {
mChartPreferenceController.setBatteryChartView(mBatteryChartView); mChartPreferenceController.setBatteryChartView(mBatteryChartView);
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2020 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import android.content.Context; import android.content.Context;
import android.os.BatteryStatsManager; import android.os.BatteryStatsManager;

View File

@@ -1,17 +1,19 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * Licensed under the Apache License, Version 2.0 (the "License");
* except in compliance with the License. You may obtain a copy of the License at * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software distributed under the * Unless required by applicable law or agreed to in writing, software
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * distributed under the License is distributed on an "AS IS" BASIS,
* KIND, either express or implied. See the License for the specific language governing * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* permissions and limitations under the License. * See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import android.annotation.IntDef; import android.annotation.IntDef;
import android.content.ContentValues; import android.content.ContentValues;
@@ -46,7 +48,7 @@ public final class ConvertUtils {
private static final String TAG = "ConvertUtils"; private static final String TAG = "ConvertUtils";
private static final Map<String, BatteryHistEntry> EMPTY_BATTERY_MAP = new HashMap<>(); private static final Map<String, BatteryHistEntry> EMPTY_BATTERY_MAP = new HashMap<>();
private static final BatteryHistEntry EMPTY_BATTERY_HIST_ENTRY = private static final BatteryHistEntry EMPTY_BATTERY_HIST_ENTRY =
new BatteryHistEntry(new ContentValues()); new BatteryHistEntry(new ContentValues());
// Maximum total time value for each slot cumulative data at most 2 hours. // Maximum total time value for each slot cumulative data at most 2 hours.
private static final float TOTAL_TIME_THRESHOLD = DateUtils.HOUR_IN_MILLIS * 2; private static final float TOTAL_TIME_THRESHOLD = DateUtils.HOUR_IN_MILLIS * 2;
@@ -64,21 +66,24 @@ public final class ConvertUtils {
public static final String FAKE_PACKAGE_NAME = "fake_package"; public static final String FAKE_PACKAGE_NAME = "fake_package";
@IntDef(prefix = {"CONSUMER_TYPE"}, value = { @IntDef(prefix = {"CONSUMER_TYPE"}, value = {
CONSUMER_TYPE_UNKNOWN, CONSUMER_TYPE_UNKNOWN,
CONSUMER_TYPE_UID_BATTERY, CONSUMER_TYPE_UID_BATTERY,
CONSUMER_TYPE_USER_BATTERY, CONSUMER_TYPE_USER_BATTERY,
CONSUMER_TYPE_SYSTEM_BATTERY, CONSUMER_TYPE_SYSTEM_BATTERY,
}) })
@Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.SOURCE)
public static @interface ConsumerType {} public static @interface ConsumerType {
}
public static final int CONSUMER_TYPE_UNKNOWN = 0; public static final int CONSUMER_TYPE_UNKNOWN = 0;
public static final int CONSUMER_TYPE_UID_BATTERY = 1; public static final int CONSUMER_TYPE_UID_BATTERY = 1;
public static final int CONSUMER_TYPE_USER_BATTERY = 2; public static final int CONSUMER_TYPE_USER_BATTERY = 2;
public static final int CONSUMER_TYPE_SYSTEM_BATTERY = 3; public static final int CONSUMER_TYPE_SYSTEM_BATTERY = 3;
private ConvertUtils() {} private ConvertUtils() {
}
/** Converts to content values */
public static ContentValues convert( public static ContentValues convert(
BatteryEntry entry, BatteryEntry entry,
BatteryUsageStats batteryUsageStats, BatteryUsageStats batteryUsageStats,
@@ -91,25 +96,25 @@ public final class ConvertUtils {
if (entry != null && batteryUsageStats != null) { if (entry != null && batteryUsageStats != null) {
values.put(BatteryHistEntry.KEY_UID, Long.valueOf(entry.getUid())); values.put(BatteryHistEntry.KEY_UID, Long.valueOf(entry.getUid()));
values.put(BatteryHistEntry.KEY_USER_ID, values.put(BatteryHistEntry.KEY_USER_ID,
Long.valueOf(UserHandle.getUserId(entry.getUid()))); Long.valueOf(UserHandle.getUserId(entry.getUid())));
values.put(BatteryHistEntry.KEY_APP_LABEL, entry.getLabel()); values.put(BatteryHistEntry.KEY_APP_LABEL, entry.getLabel());
values.put(BatteryHistEntry.KEY_PACKAGE_NAME, values.put(BatteryHistEntry.KEY_PACKAGE_NAME,
entry.getDefaultPackageName()); entry.getDefaultPackageName());
values.put(BatteryHistEntry.KEY_IS_HIDDEN, Boolean.valueOf(entry.isHidden())); values.put(BatteryHistEntry.KEY_IS_HIDDEN, Boolean.valueOf(entry.isHidden()));
values.put(BatteryHistEntry.KEY_TOTAL_POWER, values.put(BatteryHistEntry.KEY_TOTAL_POWER,
Double.valueOf(batteryUsageStats.getConsumedPower())); Double.valueOf(batteryUsageStats.getConsumedPower()));
values.put(BatteryHistEntry.KEY_CONSUME_POWER, values.put(BatteryHistEntry.KEY_CONSUME_POWER,
Double.valueOf(entry.getConsumedPower())); Double.valueOf(entry.getConsumedPower()));
values.put(BatteryHistEntry.KEY_PERCENT_OF_TOTAL, values.put(BatteryHistEntry.KEY_PERCENT_OF_TOTAL,
Double.valueOf(entry.mPercent)); Double.valueOf(entry.mPercent));
values.put(BatteryHistEntry.KEY_FOREGROUND_USAGE_TIME, values.put(BatteryHistEntry.KEY_FOREGROUND_USAGE_TIME,
Long.valueOf(entry.getTimeInForegroundMs())); Long.valueOf(entry.getTimeInForegroundMs()));
values.put(BatteryHistEntry.KEY_BACKGROUND_USAGE_TIME, values.put(BatteryHistEntry.KEY_BACKGROUND_USAGE_TIME,
Long.valueOf(entry.getTimeInBackgroundMs())); Long.valueOf(entry.getTimeInBackgroundMs()));
values.put(BatteryHistEntry.KEY_DRAIN_TYPE, values.put(BatteryHistEntry.KEY_DRAIN_TYPE,
Integer.valueOf(entry.getPowerComponentId())); Integer.valueOf(entry.getPowerComponentId()));
values.put(BatteryHistEntry.KEY_CONSUMER_TYPE, values.put(BatteryHistEntry.KEY_CONSUMER_TYPE,
Integer.valueOf(entry.getConsumerType())); Integer.valueOf(entry.getConsumerType()));
} else { } else {
values.put(BatteryHistEntry.KEY_PACKAGE_NAME, FAKE_PACKAGE_NAME); values.put(BatteryHistEntry.KEY_PACKAGE_NAME, FAKE_PACKAGE_NAME);
} }
@@ -126,7 +131,7 @@ public final class ConvertUtils {
public static String utcToLocalTime(Context context, long timestamp) { public static String utcToLocalTime(Context context, long timestamp) {
final Locale locale = getLocale(context); final Locale locale = getLocale(context);
final String pattern = final String pattern =
DateFormat.getBestDateTimePattern(locale, "MMM dd,yyyy HH:mm:ss"); DateFormat.getBestDateTimePattern(locale, "MMM dd,yyyy HH:mm:ss");
return DateFormat.format(pattern, timestamp).toString(); return DateFormat.format(pattern, timestamp).toString();
} }
@@ -159,18 +164,18 @@ public final class ConvertUtils {
final int timestampStride = 2; final int timestampStride = 2;
for (int index = 0; index < timeSlotSize; index++) { for (int index = 0; index < timeSlotSize; index++) {
final Long currentTimestamp = final Long currentTimestamp =
Long.valueOf(batteryHistoryKeys[index * timestampStride]); Long.valueOf(batteryHistoryKeys[index * timestampStride]);
final Long nextTimestamp = final Long nextTimestamp =
Long.valueOf(batteryHistoryKeys[index * timestampStride + 1]); Long.valueOf(batteryHistoryKeys[index * timestampStride + 1]);
final Long nextTwoTimestamp = final Long nextTwoTimestamp =
Long.valueOf(batteryHistoryKeys[index * timestampStride + 2]); Long.valueOf(batteryHistoryKeys[index * timestampStride + 2]);
// Fetches BatteryHistEntry data from corresponding time slot. // Fetches BatteryHistEntry data from corresponding time slot.
final Map<String, BatteryHistEntry> currentBatteryHistMap = final Map<String, BatteryHistEntry> currentBatteryHistMap =
batteryHistoryMap.getOrDefault(currentTimestamp, EMPTY_BATTERY_MAP); batteryHistoryMap.getOrDefault(currentTimestamp, EMPTY_BATTERY_MAP);
final Map<String, BatteryHistEntry> nextBatteryHistMap = final Map<String, BatteryHistEntry> nextBatteryHistMap =
batteryHistoryMap.getOrDefault(nextTimestamp, EMPTY_BATTERY_MAP); batteryHistoryMap.getOrDefault(nextTimestamp, EMPTY_BATTERY_MAP);
final Map<String, BatteryHistEntry> nextTwoBatteryHistMap = final Map<String, BatteryHistEntry> nextTwoBatteryHistMap =
batteryHistoryMap.getOrDefault(nextTwoTimestamp, EMPTY_BATTERY_MAP); batteryHistoryMap.getOrDefault(nextTwoTimestamp, EMPTY_BATTERY_MAP);
// We should not get the empty list since we have at least one fake data to record // We should not get the empty list since we have at least one fake data to record
// the battery level and status in each time slot, the empty list is used to // the battery level and status in each time slot, the empty list is used to
// represent there is no enough data to apply interpolation arithmetic. // represent there is no enough data to apply interpolation arithmetic.
@@ -195,27 +200,27 @@ public final class ConvertUtils {
// Calculates all packages diff usage data in a specific time slot. // Calculates all packages diff usage data in a specific time slot.
for (String key : allBatteryHistEntryKeys) { for (String key : allBatteryHistEntryKeys) {
final BatteryHistEntry currentEntry = final BatteryHistEntry currentEntry =
currentBatteryHistMap.getOrDefault(key, EMPTY_BATTERY_HIST_ENTRY); currentBatteryHistMap.getOrDefault(key, EMPTY_BATTERY_HIST_ENTRY);
final BatteryHistEntry nextEntry = final BatteryHistEntry nextEntry =
nextBatteryHistMap.getOrDefault(key, EMPTY_BATTERY_HIST_ENTRY); nextBatteryHistMap.getOrDefault(key, EMPTY_BATTERY_HIST_ENTRY);
final BatteryHistEntry nextTwoEntry = final BatteryHistEntry nextTwoEntry =
nextTwoBatteryHistMap.getOrDefault(key, EMPTY_BATTERY_HIST_ENTRY); nextTwoBatteryHistMap.getOrDefault(key, EMPTY_BATTERY_HIST_ENTRY);
// Cumulative values is a specific time slot for a specific app. // Cumulative values is a specific time slot for a specific app.
long foregroundUsageTimeInMs = long foregroundUsageTimeInMs =
getDiffValue( getDiffValue(
currentEntry.mForegroundUsageTimeInMs, currentEntry.mForegroundUsageTimeInMs,
nextEntry.mForegroundUsageTimeInMs, nextEntry.mForegroundUsageTimeInMs,
nextTwoEntry.mForegroundUsageTimeInMs); nextTwoEntry.mForegroundUsageTimeInMs);
long backgroundUsageTimeInMs = long backgroundUsageTimeInMs =
getDiffValue( getDiffValue(
currentEntry.mBackgroundUsageTimeInMs, currentEntry.mBackgroundUsageTimeInMs,
nextEntry.mBackgroundUsageTimeInMs, nextEntry.mBackgroundUsageTimeInMs,
nextTwoEntry.mBackgroundUsageTimeInMs); nextTwoEntry.mBackgroundUsageTimeInMs);
double consumePower = double consumePower =
getDiffValue( getDiffValue(
currentEntry.mConsumePower, currentEntry.mConsumePower,
nextEntry.mConsumePower, nextEntry.mConsumePower,
nextTwoEntry.mConsumePower); nextTwoEntry.mConsumePower);
// Excludes entry since we don't have enough data to calculate. // Excludes entry since we don't have enough data to calculate.
if (foregroundUsageTimeInMs == 0 if (foregroundUsageTimeInMs == 0
&& backgroundUsageTimeInMs == 0 && backgroundUsageTimeInMs == 0
@@ -223,14 +228,14 @@ public final class ConvertUtils {
continue; continue;
} }
final BatteryHistEntry selectedBatteryEntry = final BatteryHistEntry selectedBatteryEntry =
selectBatteryHistEntry(currentEntry, nextEntry, nextTwoEntry); selectBatteryHistEntry(currentEntry, nextEntry, nextTwoEntry);
if (selectedBatteryEntry == null) { if (selectedBatteryEntry == null) {
continue; continue;
} }
// Forces refine the cumulative value since it may introduce deviation // Forces refine the cumulative value since it may introduce deviation
// error since we will apply the interpolation arithmetic. // error since we will apply the interpolation arithmetic.
final float totalUsageTimeInMs = final float totalUsageTimeInMs =
foregroundUsageTimeInMs + backgroundUsageTimeInMs; foregroundUsageTimeInMs + backgroundUsageTimeInMs;
if (totalUsageTimeInMs > TOTAL_TIME_THRESHOLD) { if (totalUsageTimeInMs > TOTAL_TIME_THRESHOLD) {
final float ratio = TOTAL_TIME_THRESHOLD / totalUsageTimeInMs; final float ratio = TOTAL_TIME_THRESHOLD / totalUsageTimeInMs;
if (DEBUG) { if (DEBUG) {
@@ -240,19 +245,19 @@ public final class ConvertUtils {
currentEntry)); currentEntry));
} }
foregroundUsageTimeInMs = foregroundUsageTimeInMs =
Math.round(foregroundUsageTimeInMs * ratio); Math.round(foregroundUsageTimeInMs * ratio);
backgroundUsageTimeInMs = backgroundUsageTimeInMs =
Math.round(backgroundUsageTimeInMs * ratio); Math.round(backgroundUsageTimeInMs * ratio);
consumePower = consumePower * ratio; consumePower = consumePower * ratio;
} }
totalConsumePower += consumePower; totalConsumePower += consumePower;
batteryDiffEntryList.add( batteryDiffEntryList.add(
new BatteryDiffEntry( new BatteryDiffEntry(
context, context,
foregroundUsageTimeInMs, foregroundUsageTimeInMs,
backgroundUsageTimeInMs, backgroundUsageTimeInMs,
consumePower, consumePower,
selectedBatteryEntry)); selectedBatteryEntry));
} }
// Sets total consume power data into all BatteryDiffEntry in the same slot. // Sets total consume power data into all BatteryDiffEntry in the same slot.
for (BatteryDiffEntry diffEntry : batteryDiffEntryList) { for (BatteryDiffEntry diffEntry : batteryDiffEntryList) {
@@ -282,9 +287,9 @@ public final class ConvertUtils {
} else { } else {
// Sums up some fields data into the existing one. // Sums up some fields data into the existing one.
oldBatteryDiffEntry.mForegroundUsageTimeInMs += oldBatteryDiffEntry.mForegroundUsageTimeInMs +=
entry.mForegroundUsageTimeInMs; entry.mForegroundUsageTimeInMs;
oldBatteryDiffEntry.mBackgroundUsageTimeInMs += oldBatteryDiffEntry.mBackgroundUsageTimeInMs +=
entry.mBackgroundUsageTimeInMs; entry.mBackgroundUsageTimeInMs;
oldBatteryDiffEntry.mConsumePower += entry.mConsumePower; oldBatteryDiffEntry.mConsumePower += entry.mConsumePower;
} }
totalConsumePower += entry.mConsumePower; totalConsumePower += entry.mConsumePower;
@@ -318,7 +323,7 @@ public final class ConvertUtils {
if (packageName != null if (packageName != null
&& !backgroundUsageTimeHideList.isEmpty() && !backgroundUsageTimeHideList.isEmpty()
&& backgroundUsageTimeHideList.contains(packageName)) { && backgroundUsageTimeHideList.contains(packageName)) {
entry.mBackgroundUsageTimeInMs = 0; entry.mBackgroundUsageTimeInMs = 0;
} }
} }
} }
@@ -342,7 +347,7 @@ public final class ConvertUtils {
return entry2; return entry2;
} else { } else {
return entry3 != null && entry3 != EMPTY_BATTERY_HIST_ENTRY return entry3 != null && entry3 != EMPTY_BATTERY_HIST_ENTRY
? entry3 : null; ? entry3 : null;
} }
} }
@@ -352,8 +357,8 @@ public final class ConvertUtils {
return Locale.getDefault(); return Locale.getDefault();
} }
final LocaleList locales = final LocaleList locales =
context.getResources().getConfiguration().getLocales(); context.getResources().getConfiguration().getLocales();
return locales != null && !locales.isEmpty() ? locales.get(0) return locales != null && !locales.isEmpty() ? locales.get(0)
: Locale.getDefault(); : Locale.getDefault();
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,11 +13,10 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import android.content.Context; import android.content.Context;
import android.util.AttributeSet; import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
@@ -33,8 +32,10 @@ public class ExpandDividerPreference extends Preference {
@VisibleForTesting @VisibleForTesting
static final String PREFERENCE_KEY = "expandable_divider"; static final String PREFERENCE_KEY = "expandable_divider";
@VisibleForTesting TextView mTextView; @VisibleForTesting
@VisibleForTesting ImageView mImageView; TextView mTextView;
@VisibleForTesting
ImageView mImageView;
private OnExpandListener mOnExpandListener; private OnExpandListener mOnExpandListener;
private boolean mIsExpanded = false; private boolean mIsExpanded = false;
@@ -42,6 +43,7 @@ public class ExpandDividerPreference extends Preference {
/** A callback listener for expand state is changed by users. */ /** A callback listener for expand state is changed by users. */
public interface OnExpandListener { public interface OnExpandListener {
/** Callback function for expand state is changed by users. */
void onExpand(boolean isExpanded); void onExpand(boolean isExpanded);
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2009 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import android.content.Context; import android.content.Context;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
@@ -67,34 +67,41 @@ public class PowerGaugePreference extends AppPreference {
mShowAnomalyIcon = false; mShowAnomalyIcon = false;
} }
/** Sets the content description. */
public void setContentDescription(String name) { public void setContentDescription(String name) {
mContentDescription = name; mContentDescription = name;
notifyChanged(); notifyChanged();
} }
/** Sets the percent of total. */
public void setPercent(double percentOfTotal) { public void setPercent(double percentOfTotal) {
mProgress = Utils.formatPercentage(percentOfTotal, true); mProgress = Utils.formatPercentage(percentOfTotal, true);
notifyChanged(); notifyChanged();
} }
/** Gets the percent of total. */
public String getPercent() { public String getPercent() {
return mProgress.toString(); return mProgress.toString();
} }
/** Sets the subtitle. */
public void setSubtitle(CharSequence subtitle) { public void setSubtitle(CharSequence subtitle) {
mProgress = subtitle; mProgress = subtitle;
notifyChanged(); notifyChanged();
} }
/** Gets the subtitle. */
public CharSequence getSubtitle() { public CharSequence getSubtitle() {
return mProgress; return mProgress;
} }
/** Sets whether to show anomaly icon */
public void shouldShowAnomalyIcon(boolean showAnomalyIcon) { public void shouldShowAnomalyIcon(boolean showAnomalyIcon) {
mShowAnomalyIcon = showAnomalyIcon; mShowAnomalyIcon = showAnomalyIcon;
notifyChanged(); notifyChanged();
} }
/** Gets whether to show anomaly icon */
public boolean showAnomalyIcon() { public boolean showAnomalyIcon() {
return mShowAnomalyIcon; return mShowAnomalyIcon;
} }

View File

@@ -1,17 +1,19 @@
/* /*
* Copyright (C) 2017 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * Licensed under the Apache License, Version 2.0 (the "License");
* except in compliance with the License. You may obtain a copy of the License at * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software distributed under the * Unless required by applicable law or agreed to in writing, software
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * distributed under the License is distributed on an "AS IS" BASIS,
* KIND, either express or implied. See the License for the specific language governing * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* permissions and limitations under the License. * See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.android.settings.fuelgauge.BatteryBroadcastReceiver.BatteryUpdateType; import static com.android.settings.fuelgauge.BatteryBroadcastReceiver.BatteryUpdateType;
@@ -35,6 +37,7 @@ import androidx.loader.content.Loader;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.SettingsActivity; import com.android.settings.SettingsActivity;
import com.android.settings.fuelgauge.BatteryBroadcastReceiver; import com.android.settings.fuelgauge.BatteryBroadcastReceiver;
import com.android.settings.fuelgauge.PowerUsageFeatureProvider;
import com.android.settings.overlay.FeatureFactory; import com.android.settings.overlay.FeatureFactory;
import com.android.settings.search.BaseSearchIndexProvider; import com.android.settings.search.BaseSearchIndexProvider;
import com.android.settingslib.core.AbstractPreferenceController; import com.android.settingslib.core.AbstractPreferenceController;
@@ -45,6 +48,7 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
/** Advanced power usage. */
@SearchIndexable(forTarget = SearchIndexable.ALL & ~SearchIndexable.ARC) @SearchIndexable(forTarget = SearchIndexable.ALL & ~SearchIndexable.ARC)
public class PowerUsageAdvanced extends PowerUsageBase { public class PowerUsageAdvanced extends PowerUsageBase {
private static final String TAG = "AdvancedBatteryUsage"; private static final String TAG = "AdvancedBatteryUsage";
@@ -69,14 +73,14 @@ public class PowerUsageAdvanced extends PowerUsageBase {
private final ContentObserver mBatteryObserver = private final ContentObserver mBatteryObserver =
new ContentObserver(new Handler()) { new ContentObserver(new Handler()) {
@Override @Override
public void onChange(boolean selfChange) { public void onChange(boolean selfChange) {
Log.d(TAG, "onBatteryContentChange: " + selfChange); Log.d(TAG, "onBatteryContentChange: " + selfChange);
mIsChartDataLoaded = false; mIsChartDataLoaded = false;
restartBatteryStatsLoader( restartBatteryStatsLoader(
BatteryBroadcastReceiver.BatteryUpdateType.MANUAL); BatteryBroadcastReceiver.BatteryUpdateType.MANUAL);
} }
}; };
@Override @Override
public void onCreate(Bundle icicle) { public void onCreate(Bundle icicle) {
@@ -87,7 +91,7 @@ public class PowerUsageAdvanced extends PowerUsageBase {
if (mIsChartGraphEnabled) { if (mIsChartGraphEnabled) {
setBatteryChartPreferenceController(); setBatteryChartPreferenceController();
} else { } else {
updateHistPrefSummary(context); updateHistPrefSummary(context);
} }
} }
@@ -143,13 +147,13 @@ public class PowerUsageAdvanced extends PowerUsageBase {
if (mIsChartGraphEnabled) { if (mIsChartGraphEnabled) {
mBatteryChartPreferenceController = mBatteryChartPreferenceController =
new BatteryChartPreferenceController(context, KEY_APP_LIST, new BatteryChartPreferenceController(context, KEY_APP_LIST,
getSettingsLifecycle(), (SettingsActivity) getActivity(), this); getSettingsLifecycle(), (SettingsActivity) getActivity(), this);
controllers.add(mBatteryChartPreferenceController); controllers.add(mBatteryChartPreferenceController);
setBatteryChartPreferenceController(); setBatteryChartPreferenceController();
} else { } else {
mBatteryAppListPreferenceController = mBatteryAppListPreferenceController =
new BatteryAppListPreferenceController(context, KEY_APP_LIST, new BatteryAppListPreferenceController(context, KEY_APP_LIST,
getSettingsLifecycle(), (SettingsActivity) getActivity(), this); getSettingsLifecycle(), (SettingsActivity) getActivity(), this);
controllers.add(mBatteryAppListPreferenceController); controllers.add(mBatteryAppListPreferenceController);
} }
return controllers; return controllers;
@@ -185,7 +189,7 @@ public class PowerUsageAdvanced extends PowerUsageBase {
if (mIsChartGraphEnabled && !mIsChartDataLoaded) { if (mIsChartGraphEnabled && !mIsChartDataLoaded) {
mIsChartDataLoaded = true; mIsChartDataLoaded = true;
getLoaderManager().restartLoader(LOADER_BATTERY_USAGE_STATS, bundle, getLoaderManager().restartLoader(LOADER_BATTERY_USAGE_STATS, bundle,
mBatteryHistoryLoaderCallbacks); mBatteryHistoryLoaderCallbacks);
} else if (!mIsChartGraphEnabled) { } else if (!mIsChartGraphEnabled) {
super.restartBatteryStatsLoader(refreshType); super.restartBatteryStatsLoader(refreshType);
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2015 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.android.settings.fuelgauge.BatteryBroadcastReceiver.BatteryUpdateType; import static com.android.settings.fuelgauge.BatteryBroadcastReceiver.BatteryUpdateType;
@@ -23,7 +23,6 @@ import android.os.BatteryUsageStats;
import android.os.Bundle; import android.os.Bundle;
import android.os.UserManager; import android.os.UserManager;
import android.util.Log; import android.util.Log;
import android.view.Menu;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting; import androidx.annotation.VisibleForTesting;
@@ -31,6 +30,8 @@ import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader; import androidx.loader.content.Loader;
import com.android.settings.dashboard.DashboardFragment; import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.fuelgauge.BatteryBroadcastReceiver;
import com.android.settings.fuelgauge.BatteryUtils;
/** /**
* Common base class for things that need to show the battery usage graph. * Common base class for things that need to show the battery usage graph.
@@ -99,6 +100,7 @@ public abstract class PowerUsageBase extends DashboardFragment {
} }
protected abstract void refreshUi(@BatteryUpdateType int refreshType); protected abstract void refreshUi(@BatteryUpdateType int refreshType);
protected abstract boolean isBatteryHistoryNeeded(); protected abstract boolean isBatteryHistoryNeeded();
protected void updatePreference(BatteryHistoryPreference historyPref) { protected void updatePreference(BatteryHistoryPreference historyPref) {

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2009 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.android.settings.fuelgauge.BatteryBroadcastReceiver.BatteryUpdateType; import static com.android.settings.fuelgauge.BatteryBroadcastReceiver.BatteryUpdateType;
@@ -34,6 +34,11 @@ import androidx.preference.Preference;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.SettingsActivity; import com.android.settings.SettingsActivity;
import com.android.settings.Utils; import com.android.settings.Utils;
import com.android.settings.fuelgauge.BatteryHeaderPreferenceController;
import com.android.settings.fuelgauge.BatteryInfo;
import com.android.settings.fuelgauge.BatteryInfoLoader;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.fuelgauge.PowerUsageFeatureProvider;
import com.android.settings.fuelgauge.batterytip.BatteryTipLoader; import com.android.settings.fuelgauge.batterytip.BatteryTipLoader;
import com.android.settings.fuelgauge.batterytip.BatteryTipPreferenceController; import com.android.settings.fuelgauge.batterytip.BatteryTipPreferenceController;
import com.android.settings.fuelgauge.batterytip.tips.BatteryTip; import com.android.settings.fuelgauge.batterytip.tips.BatteryTip;
@@ -255,9 +260,9 @@ public class PowerUsageSummary extends PowerUsageBase implements
void initPreference() { void initPreference() {
mBatteryUsagePreference = findPreference(KEY_BATTERY_USAGE); mBatteryUsagePreference = findPreference(KEY_BATTERY_USAGE);
mBatteryUsagePreference.setSummary( mBatteryUsagePreference.setSummary(
mPowerFeatureProvider.isChartGraphEnabled(getContext()) ? mPowerFeatureProvider.isChartGraphEnabled(getContext())
getString(R.string.advanced_battery_preference_summary_with_hours) : ? getString(R.string.advanced_battery_preference_summary_with_hours)
getString(R.string.advanced_battery_preference_summary)); : getString(R.string.advanced_battery_preference_summary));
mHelpPreference = findPreference(KEY_BATTERY_ERROR); mHelpPreference = findPreference(KEY_BATTERY_ERROR);
mHelpPreference.setVisible(false); mHelpPreference.setVisible(false);

View File

@@ -44,11 +44,11 @@ import androidx.slice.builders.SliceAction;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.SubSettings; import com.android.settings.SubSettings;
import com.android.settings.Utils; import com.android.settings.Utils;
import com.android.settings.fuelgauge.BatteryUsageStatsLoader;
import com.android.settings.fuelgauge.PowerUsageSummary;
import com.android.settings.fuelgauge.batterytip.BatteryTipLoader; import com.android.settings.fuelgauge.batterytip.BatteryTipLoader;
import com.android.settings.fuelgauge.batterytip.BatteryTipPreferenceController; import com.android.settings.fuelgauge.batterytip.BatteryTipPreferenceController;
import com.android.settings.fuelgauge.batterytip.tips.BatteryTip; import com.android.settings.fuelgauge.batterytip.tips.BatteryTip;
import com.android.settings.fuelgauge.batteryusage.BatteryUsageStatsLoader;
import com.android.settings.fuelgauge.batteryusage.PowerUsageSummary;
import com.android.settings.slices.CustomSliceable; import com.android.settings.slices.CustomSliceable;
import com.android.settings.slices.SliceBackgroundWorker; import com.android.settings.slices.SliceBackgroundWorker;
import com.android.settings.slices.SliceBuilderUtils; import com.android.settings.slices.SliceBuilderUtils;

View File

@@ -21,8 +21,8 @@ import android.util.ArrayMap;
import com.android.settings.backup.UserBackupSettingsActivity; import com.android.settings.backup.UserBackupSettingsActivity;
import com.android.settings.connecteddevice.ConnectedDeviceDashboardFragment; import com.android.settings.connecteddevice.ConnectedDeviceDashboardFragment;
import com.android.settings.connecteddevice.usb.UsbDetailsFragment; import com.android.settings.connecteddevice.usb.UsbDetailsFragment;
import com.android.settings.fuelgauge.PowerUsageAdvanced; import com.android.settings.fuelgauge.batteryusage.PowerUsageAdvanced;
import com.android.settings.fuelgauge.PowerUsageSummary; import com.android.settings.fuelgauge.batteryusage.PowerUsageSummary;
import com.android.settings.gestures.GestureNavigationSettingsFragment; import com.android.settings.gestures.GestureNavigationSettingsFragment;
import com.android.settings.gestures.SystemNavigationGestureSettings; import com.android.settings.gestures.SystemNavigationGestureSettings;
import com.android.settings.location.LocationSettings; import com.android.settings.location.LocationSettings;

View File

@@ -40,8 +40,8 @@ import androidx.preference.Preference;
import androidx.preference.PreferenceScreen; import androidx.preference.PreferenceScreen;
import com.android.settings.SettingsActivity; import com.android.settings.SettingsActivity;
import com.android.settings.fuelgauge.BatteryDiffEntry;
import com.android.settings.fuelgauge.BatteryUtils; import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.fuelgauge.batteryusage.BatteryDiffEntry;
import com.android.settingslib.applications.ApplicationsState; import com.android.settingslib.applications.ApplicationsState;
import org.junit.Before; import org.junit.Before;

View File

@@ -45,7 +45,6 @@ import android.os.BatteryStats;
import android.os.Bundle; import android.os.Bundle;
import android.os.Process; import android.os.Process;
import android.os.UserHandle; import android.os.UserHandle;
import android.util.Pair;
import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentActivity;
import androidx.loader.app.LoaderManager; import androidx.loader.app.LoaderManager;
@@ -54,6 +53,7 @@ import androidx.recyclerview.widget.RecyclerView;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.SettingsActivity; import com.android.settings.SettingsActivity;
import com.android.settings.fuelgauge.batteryusage.BatteryEntry;
import com.android.settings.testutils.FakeFeatureFactory; import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.shadow.ShadowActivityManager; import com.android.settings.testutils.shadow.ShadowActivityManager;
import com.android.settings.testutils.shadow.ShadowEntityHeaderController; import com.android.settings.testutils.shadow.ShadowEntityHeaderController;

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2017 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2017 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
@@ -35,6 +35,7 @@ import androidx.preference.PreferenceGroup;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.SettingsActivity; import com.android.settings.SettingsActivity;
import com.android.settings.core.InstrumentedPreferenceFragment; import com.android.settings.core.InstrumentedPreferenceFragment;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.testutils.FakeFeatureFactory; import com.android.settings.testutils.FakeFeatureFactory;
import org.junit.Before; import org.junit.Before;
@@ -81,9 +82,9 @@ public class BatteryAppListPreferenceControllerTest {
when(mContext.getPackageManager()).thenReturn(mPackageManager); when(mContext.getPackageManager()).thenReturn(mPackageManager);
when(mContext.getApplicationContext()).thenReturn(mContext); when(mContext.getApplicationContext()).thenReturn(mContext);
when(mContext.getSystemService(UserManager.class)).thenReturn(mUserManager); when(mContext.getSystemService(UserManager.class)).thenReturn(mUserManager);
when(mUserManager.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[] {}); when(mUserManager.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[]{});
when(mFeatureFactory.powerUsageFeatureProvider.getHideApplicationSummary(mContext)) when(mFeatureFactory.powerUsageFeatureProvider.getHideApplicationSummary(mContext))
.thenReturn(new String[] {"com.android.googlequicksearchbox"}); .thenReturn(new String[]{"com.android.googlequicksearchbox"});
mPreference = new PowerGaugePreference(mContext); mPreference = new PowerGaugePreference(mContext);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -14,22 +14,20 @@
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.app.settings.SettingsEnums; import android.app.settings.SettingsEnums;
import android.content.Context;
import android.content.ContentValues; import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.content.res.Configuration; import android.content.res.Configuration;
import android.content.res.Resources; import android.content.res.Resources;
@@ -37,15 +35,14 @@ import android.graphics.drawable.Drawable;
import android.os.Bundle; import android.os.Bundle;
import android.os.LocaleList; import android.os.LocaleList;
import android.text.format.DateUtils; import android.text.format.DateUtils;
import android.util.Pair;
import androidx.preference.Preference; import androidx.preference.Preference;
import androidx.preference.PreferenceCategory; import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceGroup; import androidx.preference.PreferenceGroup;
import com.android.settings.R;
import com.android.settings.SettingsActivity; import com.android.settings.SettingsActivity;
import com.android.settings.core.InstrumentedPreferenceFragment; import com.android.settings.core.InstrumentedPreferenceFragment;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.testutils.FakeFeatureFactory; import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider; import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
@@ -58,11 +55,10 @@ import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import java.util.Arrays;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
import java.util.List;
import java.util.Map; import java.util.Map;
@RunWith(RobolectricTestRunner.class) @RunWith(RobolectricTestRunner.class)
@@ -70,20 +66,24 @@ public final class BatteryChartPreferenceControllerTest {
private static final String PREF_KEY = "pref_key"; private static final String PREF_KEY = "pref_key";
private static final String PREF_SUMMARY = "fake preference summary"; private static final String PREF_SUMMARY = "fake preference summary";
private static final int DESIRED_HISTORY_SIZE = private static final int DESIRED_HISTORY_SIZE =
BatteryChartPreferenceController.DESIRED_HISTORY_SIZE; BatteryChartPreferenceController.DESIRED_HISTORY_SIZE;
@Mock private InstrumentedPreferenceFragment mFragment; @Mock
@Mock private SettingsActivity mSettingsActivity; private InstrumentedPreferenceFragment mFragment;
@Mock private PreferenceGroup mAppListGroup; @Mock
@Mock private PackageManager mPackageManager; private SettingsActivity mSettingsActivity;
@Mock private Drawable mDrawable; @Mock
@Mock private BatteryHistEntry mBatteryHistEntry; private PreferenceGroup mAppListGroup;
@Mock private BatteryChartView mBatteryChartView; @Mock
@Mock private PowerGaugePreference mPowerGaugePreference; private Drawable mDrawable;
@Mock private ExpandDividerPreference mExpandDividerPreference; @Mock
@Mock private BatteryUtils mBatteryUtils; private BatteryHistEntry mBatteryHistEntry;
@Mock private Configuration mConfiguration; @Mock
@Mock private Resources mResources; private BatteryChartView mBatteryChartView;
@Mock
private PowerGaugePreference mPowerGaugePreference;
@Mock
private BatteryUtils mBatteryUtils;
private Context mContext; private Context mContext;
private FakeFeatureFactory mFeatureFactory; private FakeFeatureFactory mFeatureFactory;
@@ -102,29 +102,29 @@ public final class BatteryChartPreferenceControllerTest {
final Resources resources = spy(mContext.getResources()); final Resources resources = spy(mContext.getResources());
resources.getConfiguration().setLocales(new LocaleList(new Locale("en_US"))); resources.getConfiguration().setLocales(new LocaleList(new Locale("en_US")));
doReturn(resources).when(mContext).getResources(); doReturn(resources).when(mContext).getResources();
doReturn(new String[] {"com.android.googlequicksearchbox"}) doReturn(new String[]{"com.android.googlequicksearchbox"})
.when(mFeatureFactory.powerUsageFeatureProvider) .when(mFeatureFactory.powerUsageFeatureProvider)
.getHideApplicationSummary(mContext); .getHideApplicationSummary(mContext);
doReturn(new String[] {"com.android.gms.persistent"}) doReturn(new String[]{"com.android.gms.persistent"})
.when(mFeatureFactory.powerUsageFeatureProvider) .when(mFeatureFactory.powerUsageFeatureProvider)
.getHideApplicationEntries(mContext); .getHideApplicationEntries(mContext);
mBatteryChartPreferenceController = createController(); mBatteryChartPreferenceController = createController();
mBatteryChartPreferenceController.mPrefContext = mContext; mBatteryChartPreferenceController.mPrefContext = mContext;
mBatteryChartPreferenceController.mAppListPrefGroup = mAppListGroup; mBatteryChartPreferenceController.mAppListPrefGroup = mAppListGroup;
mBatteryChartPreferenceController.mBatteryChartView = mBatteryChartView; mBatteryChartPreferenceController.mBatteryChartView = mBatteryChartView;
mBatteryDiffEntry = new BatteryDiffEntry( mBatteryDiffEntry = new BatteryDiffEntry(
mContext, mContext,
/*foregroundUsageTimeInMs=*/ 1, /*foregroundUsageTimeInMs=*/ 1,
/*backgroundUsageTimeInMs=*/ 2, /*backgroundUsageTimeInMs=*/ 2,
/*consumePower=*/ 3, /*consumePower=*/ 3,
mBatteryHistEntry); mBatteryHistEntry);
mBatteryDiffEntry = spy(mBatteryDiffEntry); mBatteryDiffEntry = spy(mBatteryDiffEntry);
// Adds fake testing data. // Adds fake testing data.
BatteryDiffEntry.sResourceCache.put( BatteryDiffEntry.sResourceCache.put(
"fakeBatteryDiffEntryKey", "fakeBatteryDiffEntryKey",
new BatteryEntry.NameAndIcon("fakeName", /*icon=*/ null, /*iconId=*/ 1)); new BatteryEntry.NameAndIcon("fakeName", /*icon=*/ null, /*iconId=*/ 1));
mBatteryChartPreferenceController.setBatteryHistoryMap( mBatteryChartPreferenceController.setBatteryHistoryMap(
createBatteryHistoryMap()); createBatteryHistoryMap());
} }
@Test @Test
@@ -151,7 +151,7 @@ public final class BatteryChartPreferenceControllerTest {
public void testOnDestroy_clearPreferenceCache() { public void testOnDestroy_clearPreferenceCache() {
// Ensures the testing environment is correct. // Ensures the testing environment is correct.
mBatteryChartPreferenceController.mPreferenceCache.put( mBatteryChartPreferenceController.mPreferenceCache.put(
PREF_KEY, mPowerGaugePreference); PREF_KEY, mPowerGaugePreference);
assertThat(mBatteryChartPreferenceController.mPreferenceCache).hasSize(1); assertThat(mBatteryChartPreferenceController.mPreferenceCache).hasSize(1);
mBatteryChartPreferenceController.onDestroy(); mBatteryChartPreferenceController.onDestroy();
@@ -168,19 +168,19 @@ public final class BatteryChartPreferenceControllerTest {
@Test @Test
public void testSetBatteryHistoryMap_createExpectedKeysAndLevels() { public void testSetBatteryHistoryMap_createExpectedKeysAndLevels() {
mBatteryChartPreferenceController.setBatteryHistoryMap( mBatteryChartPreferenceController.setBatteryHistoryMap(
createBatteryHistoryMap()); createBatteryHistoryMap());
// Verifies the created battery keys array. // Verifies the created battery keys array.
for (int index = 0; index < DESIRED_HISTORY_SIZE; index++) { for (int index = 0; index < DESIRED_HISTORY_SIZE; index++) {
assertThat(mBatteryChartPreferenceController.mBatteryHistoryKeys[index]) assertThat(mBatteryChartPreferenceController.mBatteryHistoryKeys[index])
// These values is are calculated by hand from createBatteryHistoryMap(). // These values is are calculated by hand from createBatteryHistoryMap().
.isEqualTo(index + 1); .isEqualTo(index + 1);
} }
// Verifies the created battery levels array. // Verifies the created battery levels array.
for (int index = 0; index < 13; index++) { for (int index = 0; index < 13; index++) {
assertThat(mBatteryChartPreferenceController.mBatteryHistoryLevels[index]) assertThat(mBatteryChartPreferenceController.mBatteryHistoryLevels[index])
// These values is are calculated by hand from createBatteryHistoryMap(). // These values is are calculated by hand from createBatteryHistoryMap().
.isEqualTo(100 - index * 2); .isEqualTo(100 - index * 2);
} }
assertThat(mBatteryChartPreferenceController.mBatteryIndexedMap).hasSize(13); assertThat(mBatteryChartPreferenceController.mBatteryIndexedMap).hasSize(13);
} }
@@ -188,19 +188,19 @@ public final class BatteryChartPreferenceControllerTest {
@Test @Test
public void testSetBatteryHistoryMap_largeSize_createExpectedKeysAndLevels() { public void testSetBatteryHistoryMap_largeSize_createExpectedKeysAndLevels() {
mBatteryChartPreferenceController.setBatteryHistoryMap( mBatteryChartPreferenceController.setBatteryHistoryMap(
createBatteryHistoryMap()); createBatteryHistoryMap());
// Verifies the created battery keys array. // Verifies the created battery keys array.
for (int index = 0; index < DESIRED_HISTORY_SIZE; index++) { for (int index = 0; index < DESIRED_HISTORY_SIZE; index++) {
assertThat(mBatteryChartPreferenceController.mBatteryHistoryKeys[index]) assertThat(mBatteryChartPreferenceController.mBatteryHistoryKeys[index])
// These values is are calculated by hand from createBatteryHistoryMap(). // These values is are calculated by hand from createBatteryHistoryMap().
.isEqualTo(index + 1); .isEqualTo(index + 1);
} }
// Verifies the created battery levels array. // Verifies the created battery levels array.
for (int index = 0; index < 13; index++) { for (int index = 0; index < 13; index++) {
assertThat(mBatteryChartPreferenceController.mBatteryHistoryLevels[index]) assertThat(mBatteryChartPreferenceController.mBatteryHistoryLevels[index])
// These values is are calculated by hand from createBatteryHistoryMap(). // These values is are calculated by hand from createBatteryHistoryMap().
.isEqualTo(100 - index * 2); .isEqualTo(100 - index * 2);
} }
assertThat(mBatteryChartPreferenceController.mBatteryIndexedMap).hasSize(13); assertThat(mBatteryChartPreferenceController.mBatteryIndexedMap).hasSize(13);
} }
@@ -209,14 +209,14 @@ public final class BatteryChartPreferenceControllerTest {
public void testRefreshUi_batteryIndexedMapIsNull_ignoreRefresh() { public void testRefreshUi_batteryIndexedMapIsNull_ignoreRefresh() {
mBatteryChartPreferenceController.setBatteryHistoryMap(null); mBatteryChartPreferenceController.setBatteryHistoryMap(null);
assertThat(mBatteryChartPreferenceController.refreshUi( assertThat(mBatteryChartPreferenceController.refreshUi(
/*trapezoidIndex=*/ 1, /*isForce=*/ false)).isFalse(); /*trapezoidIndex=*/ 1, /*isForce=*/ false)).isFalse();
} }
@Test @Test
public void testRefreshUi_batteryChartViewIsNull_ignoreRefresh() { public void testRefreshUi_batteryChartViewIsNull_ignoreRefresh() {
mBatteryChartPreferenceController.mBatteryChartView = null; mBatteryChartPreferenceController.mBatteryChartView = null;
assertThat(mBatteryChartPreferenceController.refreshUi( assertThat(mBatteryChartPreferenceController.refreshUi(
/*trapezoidIndex=*/ 1, /*isForce=*/ false)).isFalse(); /*trapezoidIndex=*/ 1, /*isForce=*/ false)).isFalse();
} }
@Test @Test
@@ -224,7 +224,7 @@ public final class BatteryChartPreferenceControllerTest {
final int trapezoidIndex = 1; final int trapezoidIndex = 1;
mBatteryChartPreferenceController.mTrapezoidIndex = trapezoidIndex; mBatteryChartPreferenceController.mTrapezoidIndex = trapezoidIndex;
assertThat(mBatteryChartPreferenceController.refreshUi( assertThat(mBatteryChartPreferenceController.refreshUi(
trapezoidIndex, /*isForce=*/ false)).isFalse(); trapezoidIndex, /*isForce=*/ false)).isFalse();
} }
@Test @Test
@@ -232,18 +232,18 @@ public final class BatteryChartPreferenceControllerTest {
final int trapezoidIndex = 1; final int trapezoidIndex = 1;
mBatteryChartPreferenceController.mTrapezoidIndex = trapezoidIndex; mBatteryChartPreferenceController.mTrapezoidIndex = trapezoidIndex;
assertThat(mBatteryChartPreferenceController.refreshUi( assertThat(mBatteryChartPreferenceController.refreshUi(
trapezoidIndex, /*isForce=*/ true)).isTrue(); trapezoidIndex, /*isForce=*/ true)).isTrue();
} }
@Test @Test
public void testForceRefreshUi_updateTrapezoidIndexIntoSelectAll() { public void testForceRefreshUi_updateTrapezoidIndexIntoSelectAll() {
mBatteryChartPreferenceController.mTrapezoidIndex = mBatteryChartPreferenceController.mTrapezoidIndex =
BatteryChartView.SELECTED_INDEX_INVALID; BatteryChartView.SELECTED_INDEX_INVALID;
mBatteryChartPreferenceController.setBatteryHistoryMap( mBatteryChartPreferenceController.setBatteryHistoryMap(
createBatteryHistoryMap()); createBatteryHistoryMap());
assertThat(mBatteryChartPreferenceController.mTrapezoidIndex) assertThat(mBatteryChartPreferenceController.mTrapezoidIndex)
.isEqualTo(BatteryChartView.SELECTED_INDEX_ALL); .isEqualTo(BatteryChartView.SELECTED_INDEX_ALL);
} }
@Test @Test
@@ -252,7 +252,7 @@ public final class BatteryChartPreferenceControllerTest {
doReturn(0).when(mAppListGroup).getPreferenceCount(); doReturn(0).when(mAppListGroup).getPreferenceCount();
mBatteryChartPreferenceController.refreshUi( mBatteryChartPreferenceController.refreshUi(
trapezoidIndex, /*isForce=*/ true); trapezoidIndex, /*isForce=*/ true);
verify(mAppListGroup, never()).removeAll(); verify(mAppListGroup, never()).removeAll();
} }
@@ -266,17 +266,17 @@ public final class BatteryChartPreferenceControllerTest {
assertThat(mBatteryChartPreferenceController.mPreferenceCache).isEmpty(); assertThat(mBatteryChartPreferenceController.mPreferenceCache).isEmpty();
mBatteryChartPreferenceController.refreshUi( mBatteryChartPreferenceController.refreshUi(
trapezoidIndex, /*isForce=*/ true); trapezoidIndex, /*isForce=*/ true);
assertThat(mBatteryChartPreferenceController.mPreferenceCache.get(PREF_KEY)) assertThat(mBatteryChartPreferenceController.mPreferenceCache.get(PREF_KEY))
.isEqualTo(mPowerGaugePreference); .isEqualTo(mPowerGaugePreference);
verify(mAppListGroup).removeAll(); verify(mAppListGroup).removeAll();
} }
@Test @Test
public void testAddPreferenceToScreen_emptyContent_ignoreAddPreference() { public void testAddPreferenceToScreen_emptyContent_ignoreAddPreference() {
mBatteryChartPreferenceController.addPreferenceToScreen( mBatteryChartPreferenceController.addPreferenceToScreen(
new ArrayList<BatteryDiffEntry>()); new ArrayList<BatteryDiffEntry>());
verify(mAppListGroup, never()).addPreference(any()); verify(mAppListGroup, never()).addPreference(any());
} }
@@ -291,12 +291,12 @@ public final class BatteryChartPreferenceControllerTest {
doReturn(false).when(mBatteryDiffEntry).validForRestriction(); doReturn(false).when(mBatteryDiffEntry).validForRestriction();
mBatteryChartPreferenceController.addPreferenceToScreen( mBatteryChartPreferenceController.addPreferenceToScreen(
Arrays.asList(mBatteryDiffEntry)); Arrays.asList(mBatteryDiffEntry));
// Verifies the preference cache. // Verifies the preference cache.
final PowerGaugePreference pref = final PowerGaugePreference pref =
(PowerGaugePreference) mBatteryChartPreferenceController.mPreferenceCache (PowerGaugePreference) mBatteryChartPreferenceController.mPreferenceCache
.get(PREF_KEY); .get(PREF_KEY);
assertThat(pref).isNotNull(); assertThat(pref).isNotNull();
// Verifies the added preference configuration. // Verifies the added preference configuration.
verify(mAppListGroup).addPreference(pref); verify(mAppListGroup).addPreference(pref);
@@ -319,7 +319,7 @@ public final class BatteryChartPreferenceControllerTest {
doReturn(mPowerGaugePreference).when(mAppListGroup).findPreference(PREF_KEY); doReturn(mPowerGaugePreference).when(mAppListGroup).findPreference(PREF_KEY);
mBatteryChartPreferenceController.addPreferenceToScreen( mBatteryChartPreferenceController.addPreferenceToScreen(
Arrays.asList(mBatteryDiffEntry)); Arrays.asList(mBatteryDiffEntry));
verify(mAppListGroup, never()).addPreference(any()); verify(mAppListGroup, never()).addPreference(any());
} }
@@ -327,12 +327,12 @@ public final class BatteryChartPreferenceControllerTest {
@Test @Test
public void testHandlePreferenceTreeiClick_notPowerGaugePreference_returnFalse() { public void testHandlePreferenceTreeiClick_notPowerGaugePreference_returnFalse() {
assertThat(mBatteryChartPreferenceController.handlePreferenceTreeClick(mAppListGroup)) assertThat(mBatteryChartPreferenceController.handlePreferenceTreeClick(mAppListGroup))
.isFalse(); .isFalse();
verify(mMetricsFeatureProvider, never()) verify(mMetricsFeatureProvider, never())
.action(mContext, SettingsEnums.ACTION_BATTERY_USAGE_APP_ITEM); .action(mContext, SettingsEnums.ACTION_BATTERY_USAGE_APP_ITEM);
verify(mMetricsFeatureProvider, never()) verify(mMetricsFeatureProvider, never())
.action(mContext, SettingsEnums.ACTION_BATTERY_USAGE_SYSTEM_ITEM); .action(mContext, SettingsEnums.ACTION_BATTERY_USAGE_SYSTEM_ITEM);
} }
@Test @Test
@@ -341,7 +341,7 @@ public final class BatteryChartPreferenceControllerTest {
doReturn(mBatteryDiffEntry).when(mPowerGaugePreference).getBatteryDiffEntry(); doReturn(mBatteryDiffEntry).when(mPowerGaugePreference).getBatteryDiffEntry();
assertThat(mBatteryChartPreferenceController.handlePreferenceTreeClick( assertThat(mBatteryChartPreferenceController.handlePreferenceTreeClick(
mPowerGaugePreference)).isTrue(); mPowerGaugePreference)).isTrue();
verify(mMetricsFeatureProvider) verify(mMetricsFeatureProvider)
.action( .action(
SettingsEnums.OPEN_BATTERY_USAGE, SettingsEnums.OPEN_BATTERY_USAGE,
@@ -358,7 +358,7 @@ public final class BatteryChartPreferenceControllerTest {
doReturn(mBatteryDiffEntry).when(mPowerGaugePreference).getBatteryDiffEntry(); doReturn(mBatteryDiffEntry).when(mPowerGaugePreference).getBatteryDiffEntry();
assertThat(mBatteryChartPreferenceController.handlePreferenceTreeClick( assertThat(mBatteryChartPreferenceController.handlePreferenceTreeClick(
mPowerGaugePreference)).isTrue(); mPowerGaugePreference)).isTrue();
verify(mMetricsFeatureProvider) verify(mMetricsFeatureProvider)
.action( .action(
SettingsEnums.OPEN_BATTERY_USAGE, SettingsEnums.OPEN_BATTERY_USAGE,
@@ -374,9 +374,9 @@ public final class BatteryChartPreferenceControllerTest {
pref.setSummary(PREF_SUMMARY); pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary( mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry( pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ 0, /*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ 0)); /*backgroundUsageTimeInMs=*/ 0));
assertThat(pref.getSummary()).isNull(); assertThat(pref.getSummary()).isNull();
} }
@@ -386,9 +386,9 @@ public final class BatteryChartPreferenceControllerTest {
pref.setSummary(PREF_SUMMARY); pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary( mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry( pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ 0, /*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS)); /*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS));
assertThat(pref.getSummary()).isEqualTo("Background: 1 min"); assertThat(pref.getSummary()).isEqualTo("Background: 1 min");
} }
@@ -398,9 +398,9 @@ public final class BatteryChartPreferenceControllerTest {
pref.setSummary(PREF_SUMMARY); pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary( mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry( pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ 100, /*foregroundUsageTimeInMs=*/ 100,
/*backgroundUsageTimeInMs=*/ 200)); /*backgroundUsageTimeInMs=*/ 200));
assertThat(pref.getSummary()).isEqualTo("Total: less than a min"); assertThat(pref.getSummary()).isEqualTo("Total: less than a min");
} }
@@ -410,11 +410,11 @@ public final class BatteryChartPreferenceControllerTest {
pref.setSummary(PREF_SUMMARY); pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary( mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry( pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS, /*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS,
/*backgroundUsageTimeInMs=*/ 200)); /*backgroundUsageTimeInMs=*/ 200));
assertThat(pref.getSummary()) assertThat(pref.getSummary())
.isEqualTo("Total: 1 min\nBackground: less than a min"); .isEqualTo("Total: 1 min\nBackground: less than a min");
} }
@Test @Test
@@ -423,9 +423,9 @@ public final class BatteryChartPreferenceControllerTest {
pref.setSummary(PREF_SUMMARY); pref.setSummary(PREF_SUMMARY);
mBatteryChartPreferenceController.setPreferenceSummary( mBatteryChartPreferenceController.setPreferenceSummary(
pref, createBatteryDiffEntry( pref, createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS, /*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS,
/*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS)); /*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS));
assertThat(pref.getSummary()).isEqualTo("Total: 2 min\nBackground: 1 min"); assertThat(pref.getSummary()).isEqualTo("Total: 2 min\nBackground: 1 min");
} }
@@ -434,11 +434,11 @@ public final class BatteryChartPreferenceControllerTest {
final PowerGaugePreference pref = new PowerGaugePreference(mContext); final PowerGaugePreference pref = new PowerGaugePreference(mContext);
pref.setSummary(PREF_SUMMARY); pref.setSummary(PREF_SUMMARY);
final BatteryDiffEntry batteryDiffEntry = final BatteryDiffEntry batteryDiffEntry =
spy(createBatteryDiffEntry( spy(createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS, /*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS,
/*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS)); /*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS));
doReturn("com.android.googlequicksearchbox").when(batteryDiffEntry) doReturn("com.android.googlequicksearchbox").when(batteryDiffEntry)
.getPackageName(); .getPackageName();
mBatteryChartPreferenceController.setPreferenceSummary(pref, batteryDiffEntry); mBatteryChartPreferenceController.setPreferenceSummary(pref, batteryDiffEntry);
assertThat(pref.getSummary()).isNull(); assertThat(pref.getSummary()).isNull();
@@ -447,28 +447,28 @@ public final class BatteryChartPreferenceControllerTest {
@Test @Test
public void testValidateUsageTime_returnTrueIfBatteryDiffEntryIsValid() { public void testValidateUsageTime_returnTrueIfBatteryDiffEntryIsValid() {
assertThat(BatteryChartPreferenceController.validateUsageTime( assertThat(BatteryChartPreferenceController.validateUsageTime(
createBatteryDiffEntry( createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS, /*foregroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS,
/*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS))) /*backgroundUsageTimeInMs=*/ DateUtils.MINUTE_IN_MILLIS)))
.isTrue(); .isTrue();
} }
@Test @Test
public void testValidateUsageTime_foregroundTimeExceedThreshold_returnFalse() { public void testValidateUsageTime_foregroundTimeExceedThreshold_returnFalse() {
assertThat(BatteryChartPreferenceController.validateUsageTime( assertThat(BatteryChartPreferenceController.validateUsageTime(
createBatteryDiffEntry( createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ DateUtils.HOUR_IN_MILLIS * 3, /*foregroundUsageTimeInMs=*/ DateUtils.HOUR_IN_MILLIS * 3,
/*backgroundUsageTimeInMs=*/ 0))) /*backgroundUsageTimeInMs=*/ 0)))
.isFalse(); .isFalse();
} }
@Test @Test
public void testValidateUsageTime_backgroundTimeExceedThreshold_returnFalse() { public void testValidateUsageTime_backgroundTimeExceedThreshold_returnFalse() {
assertThat(BatteryChartPreferenceController.validateUsageTime( assertThat(BatteryChartPreferenceController.validateUsageTime(
createBatteryDiffEntry( createBatteryDiffEntry(
/*foregroundUsageTimeInMs=*/ 0, /*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ DateUtils.HOUR_IN_MILLIS * 3))) /*backgroundUsageTimeInMs=*/ DateUtils.HOUR_IN_MILLIS * 3)))
.isFalse(); .isFalse();
} }
@Test @Test
@@ -486,10 +486,10 @@ public final class BatteryChartPreferenceControllerTest {
// Verifies the added preference. // Verifies the added preference.
assertThat(captor.getValue().getKey()).isEqualTo(PREF_KEY); assertThat(captor.getValue().getKey()).isEqualTo(PREF_KEY);
verify(mMetricsFeatureProvider) verify(mMetricsFeatureProvider)
.action( .action(
mContext, mContext,
SettingsEnums.ACTION_BATTERY_USAGE_EXPAND_ITEM, SettingsEnums.ACTION_BATTERY_USAGE_EXPAND_ITEM,
true /*isExpanded*/); true /*isExpanded*/);
} }
@Test @Test
@@ -506,10 +506,10 @@ public final class BatteryChartPreferenceControllerTest {
verify(mAppListGroup).removePreference(mPowerGaugePreference); verify(mAppListGroup).removePreference(mPowerGaugePreference);
assertThat(mBatteryChartPreferenceController.mPreferenceCache).hasSize(1); assertThat(mBatteryChartPreferenceController.mPreferenceCache).hasSize(1);
verify(mMetricsFeatureProvider) verify(mMetricsFeatureProvider)
.action( .action(
mContext, mContext,
SettingsEnums.ACTION_BATTERY_USAGE_EXPAND_ITEM, SettingsEnums.ACTION_BATTERY_USAGE_EXPAND_ITEM,
false /*isExpanded*/); false /*isExpanded*/);
} }
@Test @Test
@@ -517,16 +517,16 @@ public final class BatteryChartPreferenceControllerTest {
mBatteryChartPreferenceController.onSelect(1 /*slot index*/); mBatteryChartPreferenceController.onSelect(1 /*slot index*/);
verify(mMetricsFeatureProvider) verify(mMetricsFeatureProvider)
.action(mContext, SettingsEnums.ACTION_BATTERY_USAGE_TIME_SLOT); .action(mContext, SettingsEnums.ACTION_BATTERY_USAGE_TIME_SLOT);
} }
@Test @Test
public void testOnSelect_selectAll_logMetric() { public void testOnSelect_selectAll_logMetric() {
mBatteryChartPreferenceController.onSelect( mBatteryChartPreferenceController.onSelect(
BatteryChartView.SELECTED_INDEX_ALL /*slot index*/); BatteryChartView.SELECTED_INDEX_ALL /*slot index*/);
verify(mMetricsFeatureProvider) verify(mMetricsFeatureProvider)
.action(mContext, SettingsEnums.ACTION_BATTERY_USAGE_SHOW_ALL); .action(mContext, SettingsEnums.ACTION_BATTERY_USAGE_SHOW_ALL);
} }
@Test @Test
@@ -534,9 +534,9 @@ public final class BatteryChartPreferenceControllerTest {
mBatteryChartPreferenceController = createController(); mBatteryChartPreferenceController = createController();
setUpBatteryHistoryKeys(); setUpBatteryHistoryKeys();
mBatteryChartPreferenceController.mAppListPrefGroup = mBatteryChartPreferenceController.mAppListPrefGroup =
spy(new PreferenceCategory(mContext)); spy(new PreferenceCategory(mContext));
mBatteryChartPreferenceController.mExpandDividerPreference = mBatteryChartPreferenceController.mExpandDividerPreference =
spy(new ExpandDividerPreference(mContext)); spy(new ExpandDividerPreference(mContext));
// Simulates select the first slot. // Simulates select the first slot.
mBatteryChartPreferenceController.mTrapezoidIndex = 0; mBatteryChartPreferenceController.mTrapezoidIndex = 0;
@@ -545,12 +545,12 @@ public final class BatteryChartPreferenceControllerTest {
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
// Verifies the title in the preference group. // Verifies the title in the preference group.
verify(mBatteryChartPreferenceController.mAppListPrefGroup) verify(mBatteryChartPreferenceController.mAppListPrefGroup)
.setTitle(captor.capture()); .setTitle(captor.capture());
assertThat(captor.getValue()).isNotEqualTo("App usage for past 24 hr"); assertThat(captor.getValue()).isNotEqualTo("App usage for past 24 hr");
// Verifies the title in the expandable divider. // Verifies the title in the expandable divider.
captor = ArgumentCaptor.forClass(String.class); captor = ArgumentCaptor.forClass(String.class);
verify(mBatteryChartPreferenceController.mExpandDividerPreference) verify(mBatteryChartPreferenceController.mExpandDividerPreference)
.setTitle(captor.capture()); .setTitle(captor.capture());
assertThat(captor.getValue()).isNotEqualTo("System usage for past 24 hr"); assertThat(captor.getValue()).isNotEqualTo("System usage for past 24 hr");
} }
@@ -558,27 +558,27 @@ public final class BatteryChartPreferenceControllerTest {
public void testRefreshCategoryTitle_setLast24HrIntoBothTitleTextView() { public void testRefreshCategoryTitle_setLast24HrIntoBothTitleTextView() {
mBatteryChartPreferenceController = createController(); mBatteryChartPreferenceController = createController();
mBatteryChartPreferenceController.mAppListPrefGroup = mBatteryChartPreferenceController.mAppListPrefGroup =
spy(new PreferenceCategory(mContext)); spy(new PreferenceCategory(mContext));
mBatteryChartPreferenceController.mExpandDividerPreference = mBatteryChartPreferenceController.mExpandDividerPreference =
spy(new ExpandDividerPreference(mContext)); spy(new ExpandDividerPreference(mContext));
// Simulates select all condition. // Simulates select all condition.
mBatteryChartPreferenceController.mTrapezoidIndex = mBatteryChartPreferenceController.mTrapezoidIndex =
BatteryChartView.SELECTED_INDEX_ALL; BatteryChartView.SELECTED_INDEX_ALL;
mBatteryChartPreferenceController.refreshCategoryTitle(); mBatteryChartPreferenceController.refreshCategoryTitle();
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
// Verifies the title in the preference group. // Verifies the title in the preference group.
verify(mBatteryChartPreferenceController.mAppListPrefGroup) verify(mBatteryChartPreferenceController.mAppListPrefGroup)
.setTitle(captor.capture()); .setTitle(captor.capture());
assertThat(captor.getValue()) assertThat(captor.getValue())
.isEqualTo("App usage for past 24 hr"); .isEqualTo("App usage for past 24 hr");
// Verifies the title in the expandable divider. // Verifies the title in the expandable divider.
captor = ArgumentCaptor.forClass(String.class); captor = ArgumentCaptor.forClass(String.class);
verify(mBatteryChartPreferenceController.mExpandDividerPreference) verify(mBatteryChartPreferenceController.mExpandDividerPreference)
.setTitle(captor.capture()); .setTitle(captor.capture());
assertThat(captor.getValue()) assertThat(captor.getValue())
.isEqualTo("System usage for past 24 hr"); .isEqualTo("System usage for past 24 hr");
} }
@Test @Test
@@ -586,37 +586,37 @@ public final class BatteryChartPreferenceControllerTest {
mBatteryChartPreferenceController = createController(); mBatteryChartPreferenceController = createController();
mBatteryChartPreferenceController.mBatteryHistoryKeys = null; mBatteryChartPreferenceController.mBatteryHistoryKeys = null;
mBatteryChartPreferenceController.mBatteryChartView = mBatteryChartPreferenceController.mBatteryChartView =
spy(new BatteryChartView(mContext)); spy(new BatteryChartView(mContext));
mBatteryChartPreferenceController.setTimestampLabel(); mBatteryChartPreferenceController.setTimestampLabel();
verify(mBatteryChartPreferenceController.mBatteryChartView, never()) verify(mBatteryChartPreferenceController.mBatteryChartView, never())
.setLatestTimestamp(anyLong()); .setLatestTimestamp(anyLong());
} }
@Test @Test
public void testSetTimestampLabel_setExpectedTimestampData() { public void testSetTimestampLabel_setExpectedTimestampData() {
mBatteryChartPreferenceController = createController(); mBatteryChartPreferenceController = createController();
mBatteryChartPreferenceController.mBatteryChartView = mBatteryChartPreferenceController.mBatteryChartView =
spy(new BatteryChartView(mContext)); spy(new BatteryChartView(mContext));
setUpBatteryHistoryKeys(); setUpBatteryHistoryKeys();
mBatteryChartPreferenceController.setTimestampLabel(); mBatteryChartPreferenceController.setTimestampLabel();
verify(mBatteryChartPreferenceController.mBatteryChartView) verify(mBatteryChartPreferenceController.mBatteryChartView)
.setLatestTimestamp(1619247636826L); .setLatestTimestamp(1619247636826L);
} }
@Test @Test
public void testSetTimestampLabel_withoutValidTimestamp_setExpectedTimestampData() { public void testSetTimestampLabel_withoutValidTimestamp_setExpectedTimestampData() {
mBatteryChartPreferenceController = createController(); mBatteryChartPreferenceController = createController();
mBatteryChartPreferenceController.mBatteryChartView = mBatteryChartPreferenceController.mBatteryChartView =
spy(new BatteryChartView(mContext)); spy(new BatteryChartView(mContext));
mBatteryChartPreferenceController.mBatteryHistoryKeys = new long[] {0L}; mBatteryChartPreferenceController.mBatteryHistoryKeys = new long[]{0L};
mBatteryChartPreferenceController.setTimestampLabel(); mBatteryChartPreferenceController.setTimestampLabel();
verify(mBatteryChartPreferenceController.mBatteryChartView) verify(mBatteryChartPreferenceController.mBatteryChartView)
.setLatestTimestamp(anyLong()); .setLatestTimestamp(anyLong());
} }
@Test @Test
@@ -633,10 +633,10 @@ public final class BatteryChartPreferenceControllerTest {
mBatteryChartPreferenceController.onCreate(bundle); mBatteryChartPreferenceController.onCreate(bundle);
mBatteryChartPreferenceController.setBatteryHistoryMap( mBatteryChartPreferenceController.setBatteryHistoryMap(
createBatteryHistoryMap()); createBatteryHistoryMap());
assertThat(mBatteryChartPreferenceController.mTrapezoidIndex) assertThat(mBatteryChartPreferenceController.mTrapezoidIndex)
.isEqualTo(expectedIndex); .isEqualTo(expectedIndex);
assertThat(mBatteryChartPreferenceController.mIsExpanded).isTrue(); assertThat(mBatteryChartPreferenceController.mIsExpanded).isTrue();
} }
@@ -644,24 +644,24 @@ public final class BatteryChartPreferenceControllerTest {
public void testIsValidToShowSummary_returnExpectedResult() { public void testIsValidToShowSummary_returnExpectedResult() {
assertThat(mBatteryChartPreferenceController assertThat(mBatteryChartPreferenceController
.isValidToShowSummary("com.google.android.apps.scone")) .isValidToShowSummary("com.google.android.apps.scone"))
.isTrue(); .isTrue();
// Verifies the item which is defined in the array list. // Verifies the item which is defined in the array list.
assertThat(mBatteryChartPreferenceController assertThat(mBatteryChartPreferenceController
.isValidToShowSummary("com.android.googlequicksearchbox")) .isValidToShowSummary("com.android.googlequicksearchbox"))
.isFalse(); .isFalse();
} }
@Test @Test
public void testIsValidToShowEntry_returnExpectedResult() { public void testIsValidToShowEntry_returnExpectedResult() {
assertThat(mBatteryChartPreferenceController assertThat(mBatteryChartPreferenceController
.isValidToShowEntry("com.google.android.apps.scone")) .isValidToShowEntry("com.google.android.apps.scone"))
.isTrue(); .isTrue();
// Verifies the items which are defined in the array list. // Verifies the items which are defined in the array list.
assertThat(mBatteryChartPreferenceController assertThat(mBatteryChartPreferenceController
.isValidToShowEntry("com.android.gms.persistent")) .isValidToShowEntry("com.android.gms.persistent"))
.isFalse(); .isFalse();
} }
private static Map<Long, Map<String, BatteryHistEntry>> createBatteryHistoryMap() { private static Map<Long, Map<String, BatteryHistEntry>> createBatteryHistoryMap() {
@@ -680,22 +680,22 @@ public final class BatteryChartPreferenceControllerTest {
private BatteryDiffEntry createBatteryDiffEntry( private BatteryDiffEntry createBatteryDiffEntry(
long foregroundUsageTimeInMs, long backgroundUsageTimeInMs) { long foregroundUsageTimeInMs, long backgroundUsageTimeInMs) {
return new BatteryDiffEntry( return new BatteryDiffEntry(
mContext, foregroundUsageTimeInMs, backgroundUsageTimeInMs, mContext, foregroundUsageTimeInMs, backgroundUsageTimeInMs,
/*consumePower=*/ 0, mBatteryHistEntry); /*consumePower=*/ 0, mBatteryHistEntry);
} }
private void setUpBatteryHistoryKeys() { private void setUpBatteryHistoryKeys() {
mBatteryChartPreferenceController.mBatteryHistoryKeys = mBatteryChartPreferenceController.mBatteryHistoryKeys =
new long[] {1619196786769L, 0L, 1619247636826L}; new long[]{1619196786769L, 0L, 1619247636826L};
ConvertUtils.utcToLocalTimeHour( ConvertUtils.utcToLocalTimeHour(
mContext, /*timestamp=*/ 0, /*is24HourFormat=*/ false); mContext, /*timestamp=*/ 0, /*is24HourFormat=*/ false);
} }
private BatteryChartPreferenceController createController() { private BatteryChartPreferenceController createController() {
final BatteryChartPreferenceController controller = final BatteryChartPreferenceController controller =
new BatteryChartPreferenceController( new BatteryChartPreferenceController(
mContext, "app_list", /*lifecycle=*/ null, mContext, "app_list", /*lifecycle=*/ null,
mSettingsActivity, mFragment); mSettingsActivity, mFragment);
controller.mPrefContext = mContext; controller.mPrefContext = mContext;
return controller; return controller;
} }

View File

@@ -1,5 +1,6 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
@@ -11,14 +12,11 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*
*
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
@@ -30,6 +28,7 @@ import android.content.Context;
import android.os.LocaleList; import android.os.LocaleList;
import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityManager;
import com.android.settings.fuelgauge.PowerUsageFeatureProvider;
import com.android.settings.testutils.FakeFeatureFactory; import com.android.settings.testutils.FakeFeatureFactory;
import org.junit.Before; import org.junit.Before;
@@ -40,8 +39,8 @@ import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import java.util.Arrays;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale; import java.util.Locale;
@RunWith(RobolectricTestRunner.class) @RunWith(RobolectricTestRunner.class)
@@ -52,8 +51,10 @@ public final class BatteryChartViewTest {
private FakeFeatureFactory mFeatureFactory; private FakeFeatureFactory mFeatureFactory;
private PowerUsageFeatureProvider mPowerUsageFeatureProvider; private PowerUsageFeatureProvider mPowerUsageFeatureProvider;
@Mock private AccessibilityServiceInfo mockAccessibilityServiceInfo; @Mock
@Mock private AccessibilityManager mockAccessibilityManager; private AccessibilityServiceInfo mMockAccessibilityServiceInfo;
@Mock
private AccessibilityManager mMockAccessibilityManager;
@Before @Before
public void setUp() { public void setUp() {
@@ -62,64 +63,64 @@ public final class BatteryChartViewTest {
mPowerUsageFeatureProvider = mFeatureFactory.powerUsageFeatureProvider; mPowerUsageFeatureProvider = mFeatureFactory.powerUsageFeatureProvider;
mContext = spy(RuntimeEnvironment.application); mContext = spy(RuntimeEnvironment.application);
mContext.getResources().getConfiguration().setLocales( mContext.getResources().getConfiguration().setLocales(
new LocaleList(new Locale("en_US"))); new LocaleList(new Locale("en_US")));
mBatteryChartView = new BatteryChartView(mContext); mBatteryChartView = new BatteryChartView(mContext);
doReturn(mockAccessibilityManager).when(mContext) doReturn(mMockAccessibilityManager).when(mContext)
.getSystemService(AccessibilityManager.class); .getSystemService(AccessibilityManager.class);
doReturn("TalkBackService").when(mockAccessibilityServiceInfo).getId(); doReturn("TalkBackService").when(mMockAccessibilityServiceInfo).getId();
doReturn(Arrays.asList(mockAccessibilityServiceInfo)) doReturn(Arrays.asList(mMockAccessibilityServiceInfo))
.when(mockAccessibilityManager) .when(mMockAccessibilityManager)
.getEnabledAccessibilityServiceList(anyInt()); .getEnabledAccessibilityServiceList(anyInt());
} }
@Test @Test
public void testIsAccessibilityEnabled_disable_returnFalse() { public void testIsAccessibilityEnabled_disable_returnFalse() {
doReturn(false).when(mockAccessibilityManager).isEnabled(); doReturn(false).when(mMockAccessibilityManager).isEnabled();
assertThat(BatteryChartView.isAccessibilityEnabled(mContext)).isFalse(); assertThat(BatteryChartView.isAccessibilityEnabled(mContext)).isFalse();
} }
@Test @Test
public void testIsAccessibilityEnabled_emptyInfo_returnFalse() { public void testIsAccessibilityEnabled_emptyInfo_returnFalse() {
doReturn(true).when(mockAccessibilityManager).isEnabled(); doReturn(true).when(mMockAccessibilityManager).isEnabled();
doReturn(new ArrayList<AccessibilityServiceInfo>()) doReturn(new ArrayList<AccessibilityServiceInfo>())
.when(mockAccessibilityManager) .when(mMockAccessibilityManager)
.getEnabledAccessibilityServiceList(anyInt()); .getEnabledAccessibilityServiceList(anyInt());
assertThat(BatteryChartView.isAccessibilityEnabled(mContext)).isFalse(); assertThat(BatteryChartView.isAccessibilityEnabled(mContext)).isFalse();
} }
@Test @Test
public void testIsAccessibilityEnabled_validServiceId_returnTrue() { public void testIsAccessibilityEnabled_validServiceId_returnTrue() {
doReturn(true).when(mockAccessibilityManager).isEnabled(); doReturn(true).when(mMockAccessibilityManager).isEnabled();
assertThat(BatteryChartView.isAccessibilityEnabled(mContext)).isTrue(); assertThat(BatteryChartView.isAccessibilityEnabled(mContext)).isTrue();
} }
@Test @Test
public void testSetSelectedIndex_invokesCallback() { public void testSetSelectedIndex_invokesCallback() {
final int selectedIndex[] = new int[1]; final int[] selectedIndex = new int[1];
final int expectedIndex = 2; final int expectedIndex = 2;
mBatteryChartView.mSelectedIndex = 1; mBatteryChartView.mSelectedIndex = 1;
mBatteryChartView.setOnSelectListener( mBatteryChartView.setOnSelectListener(
trapezoidIndex -> { trapezoidIndex -> {
selectedIndex[0] = trapezoidIndex; selectedIndex[0] = trapezoidIndex;
}); });
mBatteryChartView.setSelectedIndex(expectedIndex); mBatteryChartView.setSelectedIndex(expectedIndex);
assertThat(mBatteryChartView.mSelectedIndex) assertThat(mBatteryChartView.mSelectedIndex)
.isEqualTo(expectedIndex); .isEqualTo(expectedIndex);
assertThat(selectedIndex[0]).isEqualTo(expectedIndex); assertThat(selectedIndex[0]).isEqualTo(expectedIndex);
} }
@Test @Test
public void testSetSelectedIndex_sameIndex_notInvokesCallback() { public void testSetSelectedIndex_sameIndex_notInvokesCallback() {
final int selectedIndex[] = new int[1]; final int[] selectedIndex = new int[1];
final int expectedIndex = 1; final int expectedIndex = 1;
mBatteryChartView.mSelectedIndex = expectedIndex; mBatteryChartView.mSelectedIndex = expectedIndex;
mBatteryChartView.setOnSelectListener( mBatteryChartView.setOnSelectListener(
trapezoidIndex -> { trapezoidIndex -> {
selectedIndex[0] = trapezoidIndex; selectedIndex[0] = trapezoidIndex;
}); });
mBatteryChartView.setSelectedIndex(expectedIndex); mBatteryChartView.setSelectedIndex(expectedIndex);
@@ -130,7 +131,7 @@ public final class BatteryChartViewTest {
public void testClickable_isChartGraphSlotsEnabledIsFalse_notClickable() { public void testClickable_isChartGraphSlotsEnabledIsFalse_notClickable() {
mBatteryChartView.setClickableForce(true); mBatteryChartView.setClickableForce(true);
when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext)) when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext))
.thenReturn(false); .thenReturn(false);
mBatteryChartView.onAttachedToWindow(); mBatteryChartView.onAttachedToWindow();
assertThat(mBatteryChartView.isClickable()).isFalse(); assertThat(mBatteryChartView.isClickable()).isFalse();
@@ -141,8 +142,8 @@ public final class BatteryChartViewTest {
public void testClickable_accessibilityIsDisabled_clickable() { public void testClickable_accessibilityIsDisabled_clickable() {
mBatteryChartView.setClickableForce(true); mBatteryChartView.setClickableForce(true);
when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext)) when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext))
.thenReturn(true); .thenReturn(true);
doReturn(false).when(mockAccessibilityManager).isEnabled(); doReturn(false).when(mMockAccessibilityManager).isEnabled();
mBatteryChartView.onAttachedToWindow(); mBatteryChartView.onAttachedToWindow();
assertThat(mBatteryChartView.isClickable()).isTrue(); assertThat(mBatteryChartView.isClickable()).isTrue();
@@ -153,11 +154,11 @@ public final class BatteryChartViewTest {
public void testClickable_accessibilityIsEnabledWithoutValidId_clickable() { public void testClickable_accessibilityIsEnabledWithoutValidId_clickable() {
mBatteryChartView.setClickableForce(true); mBatteryChartView.setClickableForce(true);
when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext)) when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext))
.thenReturn(true); .thenReturn(true);
doReturn(true).when(mockAccessibilityManager).isEnabled(); doReturn(true).when(mMockAccessibilityManager).isEnabled();
doReturn(new ArrayList<AccessibilityServiceInfo>()) doReturn(new ArrayList<AccessibilityServiceInfo>())
.when(mockAccessibilityManager) .when(mMockAccessibilityManager)
.getEnabledAccessibilityServiceList(anyInt()); .getEnabledAccessibilityServiceList(anyInt());
mBatteryChartView.onAttachedToWindow(); mBatteryChartView.onAttachedToWindow();
assertThat(mBatteryChartView.isClickable()).isTrue(); assertThat(mBatteryChartView.isClickable()).isTrue();
@@ -168,8 +169,8 @@ public final class BatteryChartViewTest {
public void testClickable_accessibilityIsEnabledWithValidId_notClickable() { public void testClickable_accessibilityIsEnabledWithValidId_notClickable() {
mBatteryChartView.setClickableForce(true); mBatteryChartView.setClickableForce(true);
when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext)) when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext))
.thenReturn(true); .thenReturn(true);
doReturn(true).when(mockAccessibilityManager).isEnabled(); doReturn(true).when(mMockAccessibilityManager).isEnabled();
mBatteryChartView.onAttachedToWindow(); mBatteryChartView.onAttachedToWindow();
assertThat(mBatteryChartView.isClickable()).isFalse(); assertThat(mBatteryChartView.isClickable()).isFalse();
@@ -186,13 +187,13 @@ public final class BatteryChartViewTest {
mBatteryChartView.setLevels(levels); mBatteryChartView.setLevels(levels);
mBatteryChartView.setClickableForce(true); mBatteryChartView.setClickableForce(true);
when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext)) when(mPowerUsageFeatureProvider.isChartGraphSlotsEnabled(mContext))
.thenReturn(true); .thenReturn(true);
doReturn(true).when(mockAccessibilityManager).isEnabled(); doReturn(true).when(mMockAccessibilityManager).isEnabled();
mBatteryChartView.onAttachedToWindow(); mBatteryChartView.onAttachedToWindow();
// Ensures the testing environment is correct. // Ensures the testing environment is correct.
assertThat(mBatteryChartView.isClickable()).isFalse(); assertThat(mBatteryChartView.isClickable()).isFalse();
// Turns off accessibility service. // Turns off accessibility service.
doReturn(false).when(mockAccessibilityManager).isEnabled(); doReturn(false).when(mMockAccessibilityManager).isEnabled();
mBatteryChartView.onAttachedToWindow(); mBatteryChartView.onAttachedToWindow();
@@ -202,23 +203,23 @@ public final class BatteryChartViewTest {
@Test @Test
public void testOnAttachedToWindow_addAccessibilityStateChangeListener() { public void testOnAttachedToWindow_addAccessibilityStateChangeListener() {
mBatteryChartView.onAttachedToWindow(); mBatteryChartView.onAttachedToWindow();
verify(mockAccessibilityManager) verify(mMockAccessibilityManager)
.addAccessibilityStateChangeListener(mBatteryChartView); .addAccessibilityStateChangeListener(mBatteryChartView);
} }
@Test @Test
public void testOnDetachedFromWindow_removeAccessibilityStateChangeListener() { public void testOnDetachedFromWindow_removeAccessibilityStateChangeListener() {
mBatteryChartView.onAttachedToWindow(); mBatteryChartView.onAttachedToWindow();
mBatteryChartView.mHandler.postDelayed( mBatteryChartView.mHandler.postDelayed(
mBatteryChartView.mUpdateClickableStateRun, 1000); mBatteryChartView.mUpdateClickableStateRun, 1000);
mBatteryChartView.onDetachedFromWindow(); mBatteryChartView.onDetachedFromWindow();
verify(mockAccessibilityManager) verify(mMockAccessibilityManager)
.removeAccessibilityStateChangeListener(mBatteryChartView); .removeAccessibilityStateChangeListener(mBatteryChartView);
assertThat(mBatteryChartView.mHandler.hasCallbacks( assertThat(mBatteryChartView.mHandler.hasCallbacks(
mBatteryChartView.mUpdateClickableStateRun)) mBatteryChartView.mUpdateClickableStateRun))
.isFalse(); .isFalse();
} }
@Test @Test
@@ -227,8 +228,8 @@ public final class BatteryChartViewTest {
mBatteryChartView.onAccessibilityStateChanged(/*enabled=*/ true); mBatteryChartView.onAccessibilityStateChanged(/*enabled=*/ true);
verify(mBatteryChartView.mHandler) verify(mBatteryChartView.mHandler)
.removeCallbacks(mBatteryChartView.mUpdateClickableStateRun); .removeCallbacks(mBatteryChartView.mUpdateClickableStateRun);
verify(mBatteryChartView.mHandler) verify(mBatteryChartView.mHandler)
.postDelayed(mBatteryChartView.mUpdateClickableStateRun, 500L); .postDelayed(mBatteryChartView.mUpdateClickableStateRun, 500L);
} }
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
@@ -35,6 +35,7 @@ import android.os.UserHandle;
import android.os.UserManager; import android.os.UserManager;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.fuelgauge.BatteryUtils;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -59,15 +60,24 @@ public final class BatteryDiffEntryTest {
private Context mContext; private Context mContext;
@Mock private ApplicationInfo mockAppInfo; @Mock
@Mock private PackageManager mockPackageManager; private ApplicationInfo mMockAppInfo;
@Mock private UserManager mockUserManager; @Mock
@Mock private Drawable mockDrawable; private PackageManager mMockPackageManager;
@Mock private Drawable mockDrawable2; @Mock
@Mock private Drawable mockBadgedDrawable; private UserManager mMockUserManager;
@Mock private BatteryHistEntry mBatteryHistEntry; @Mock
@Mock private PackageInfo mockPackageInfo; private Drawable mMockDrawable;
@Mock private ConstantState mockConstantState; @Mock
private Drawable mMockDrawable2;
@Mock
private Drawable mMockBadgedDrawable;
@Mock
private BatteryHistEntry mBatteryHistEntry;
@Mock
private PackageInfo mMockPackageInfo;
@Mock
private ConstantState mMockConstantState;
@Before @Before
public void setUp() { public void setUp() {
@@ -75,20 +85,20 @@ public final class BatteryDiffEntryTest {
ShadowUserHandle.reset(); ShadowUserHandle.reset();
mContext = spy(RuntimeEnvironment.application); mContext = spy(RuntimeEnvironment.application);
doReturn(mContext).when(mContext).getApplicationContext(); doReturn(mContext).when(mContext).getApplicationContext();
doReturn(mockUserManager).when(mContext).getSystemService(UserManager.class); doReturn(mMockUserManager).when(mContext).getSystemService(UserManager.class);
doReturn(mockPackageManager).when(mContext).getPackageManager(); doReturn(mMockPackageManager).when(mContext).getPackageManager();
BatteryDiffEntry.clearCache(); BatteryDiffEntry.clearCache();
} }
@Test @Test
public void testSetTotalConsumePower_returnExpectedResult() { public void testSetTotalConsumePower_returnExpectedResult() {
final BatteryDiffEntry entry = final BatteryDiffEntry entry =
new BatteryDiffEntry( new BatteryDiffEntry(
mContext, mContext,
/*foregroundUsageTimeInMs=*/ 10001L, /*foregroundUsageTimeInMs=*/ 10001L,
/*backgroundUsageTimeInMs=*/ 20002L, /*backgroundUsageTimeInMs=*/ 20002L,
/*consumePower=*/ 22.0, /*consumePower=*/ 22.0,
/*batteryHistEntry=*/ null); /*batteryHistEntry=*/ null);
entry.setTotalConsumePower(100.0); entry.setTotalConsumePower(100.0);
assertThat(entry.getPercentOfTotal()).isEqualTo(22.0); assertThat(entry.getPercentOfTotal()).isEqualTo(22.0);
@@ -97,12 +107,12 @@ public final class BatteryDiffEntryTest {
@Test @Test
public void testSetTotalConsumePower_setZeroValue_returnsZeroValue() { public void testSetTotalConsumePower_setZeroValue_returnsZeroValue() {
final BatteryDiffEntry entry = final BatteryDiffEntry entry =
new BatteryDiffEntry( new BatteryDiffEntry(
mContext, mContext,
/*foregroundUsageTimeInMs=*/ 10001L, /*foregroundUsageTimeInMs=*/ 10001L,
/*backgroundUsageTimeInMs=*/ 20002L, /*backgroundUsageTimeInMs=*/ 20002L,
/*consumePower=*/ 22.0, /*consumePower=*/ 22.0,
/*batteryHistEntry=*/ null); /*batteryHistEntry=*/ null);
entry.setTotalConsumePower(0); entry.setTotalConsumePower(0);
assertThat(entry.getPercentOfTotal()).isEqualTo(0); assertThat(entry.getPercentOfTotal()).isEqualTo(0);
@@ -127,9 +137,9 @@ public final class BatteryDiffEntryTest {
final String expectedName = "Ambient display"; final String expectedName = "Ambient display";
// Generates fake testing data. // Generates fake testing data.
final ContentValues values = getContentValuesWithType( final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY); ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
values.put("drainType", values.put("drainType",
Integer.valueOf(BatteryConsumer.POWER_COMPONENT_AMBIENT_DISPLAY)); Integer.valueOf(BatteryConsumer.POWER_COMPONENT_AMBIENT_DISPLAY));
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values); final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
final BatteryDiffEntry entry = createBatteryDiffEntry(10, batteryHistEntry); final BatteryDiffEntry entry = createBatteryDiffEntry(10, batteryHistEntry);
@@ -139,7 +149,7 @@ public final class BatteryDiffEntryTest {
assertThat(BatteryDiffEntry.sResourceCache).hasSize(1); assertThat(BatteryDiffEntry.sResourceCache).hasSize(1);
// Verifies the app label in the cache. // Verifies the app label in the cache.
final BatteryEntry.NameAndIcon nameAndIcon = final BatteryEntry.NameAndIcon nameAndIcon =
BatteryDiffEntry.sResourceCache.get(entry.getKey()); BatteryDiffEntry.sResourceCache.get(entry.getKey());
assertThat(nameAndIcon.mName).isEqualTo(expectedName); assertThat(nameAndIcon.mName).isEqualTo(expectedName);
assertThat(nameAndIcon.mIconId).isEqualTo(R.drawable.ic_settings_aod); assertThat(nameAndIcon.mIconId).isEqualTo(R.drawable.ic_settings_aod);
// Verifies the restrictable flag in the cache. // Verifies the restrictable flag in the cache.
@@ -150,10 +160,10 @@ public final class BatteryDiffEntryTest {
@Test @Test
public void testLoadLabelAndIcon_forUserBattery_returnExpectedResult() { public void testLoadLabelAndIcon_forUserBattery_returnExpectedResult() {
final String expectedName = "Removed user"; final String expectedName = "Removed user";
doReturn(null).when(mockUserManager).getUserInfo(1001); doReturn(null).when(mMockUserManager).getUserInfo(1001);
// Generates fake testing data. // Generates fake testing data.
final ContentValues values = getContentValuesWithType( final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_USER_BATTERY); ConvertUtils.CONSUMER_TYPE_USER_BATTERY);
values.put("userId", Integer.valueOf(1001)); values.put("userId", Integer.valueOf(1001));
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values); final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
@@ -165,7 +175,7 @@ public final class BatteryDiffEntryTest {
assertThat(BatteryDiffEntry.sResourceCache).hasSize(1); assertThat(BatteryDiffEntry.sResourceCache).hasSize(1);
// Verifies the app label in the cache. // Verifies the app label in the cache.
final BatteryEntry.NameAndIcon nameAndIcon = final BatteryEntry.NameAndIcon nameAndIcon =
BatteryDiffEntry.sResourceCache.get(entry.getKey()); BatteryDiffEntry.sResourceCache.get(entry.getKey());
assertThat(nameAndIcon.mName).isEqualTo(expectedName); assertThat(nameAndIcon.mName).isEqualTo(expectedName);
assertThat(nameAndIcon.mIconId).isEqualTo(0); assertThat(nameAndIcon.mIconId).isEqualTo(0);
// Verifies the restrictable flag in the cache. // Verifies the restrictable flag in the cache.
@@ -178,13 +188,13 @@ public final class BatteryDiffEntryTest {
final String expectedAppLabel = "fake app label"; final String expectedAppLabel = "fake app label";
final String fakePackageName = "com.fake.google.com"; final String fakePackageName = "com.fake.google.com";
final ContentValues values = getContentValuesWithType( final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY); ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put("uid", /*invalid uid*/ 10001); values.put("uid", /*invalid uid*/ 10001);
values.put("packageName", fakePackageName); values.put("packageName", fakePackageName);
doReturn(mockAppInfo).when(mockPackageManager) doReturn(mMockAppInfo).when(mMockPackageManager)
.getApplicationInfo(fakePackageName, 0); .getApplicationInfo(fakePackageName, 0);
doReturn(expectedAppLabel).when(mockPackageManager) doReturn(expectedAppLabel).when(mMockPackageManager)
.getApplicationLabel(mockAppInfo); .getApplicationLabel(mMockAppInfo);
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values); final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
final BatteryDiffEntry entry = createBatteryDiffEntry(10, batteryHistEntry); final BatteryDiffEntry entry = createBatteryDiffEntry(10, batteryHistEntry);
@@ -194,7 +204,7 @@ public final class BatteryDiffEntryTest {
assertThat(BatteryDiffEntry.sResourceCache).hasSize(1); assertThat(BatteryDiffEntry.sResourceCache).hasSize(1);
// Verifies the app label in the cache. // Verifies the app label in the cache.
final BatteryEntry.NameAndIcon nameAndIcon = final BatteryEntry.NameAndIcon nameAndIcon =
BatteryDiffEntry.sResourceCache.get(entry.getKey()); BatteryDiffEntry.sResourceCache.get(entry.getKey());
assertThat(nameAndIcon.mName).isEqualTo(expectedAppLabel); assertThat(nameAndIcon.mName).isEqualTo(expectedAppLabel);
// Verifies the restrictable flag in the cache. // Verifies the restrictable flag in the cache.
assertThat(entry.mValidForRestriction).isFalse(); assertThat(entry.mValidForRestriction).isFalse();
@@ -205,7 +215,7 @@ public final class BatteryDiffEntryTest {
public void testGetAppLabel_loadDataFromPreDefinedNameAndUid() { public void testGetAppLabel_loadDataFromPreDefinedNameAndUid() {
final String expectedAppLabel = "Android OS"; final String expectedAppLabel = "Android OS";
final ContentValues values = getContentValuesWithType( final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY); ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values); final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
final BatteryDiffEntry entry = createBatteryDiffEntry(10, batteryHistEntry); final BatteryDiffEntry entry = createBatteryDiffEntry(10, batteryHistEntry);
@@ -214,7 +224,7 @@ public final class BatteryDiffEntryTest {
assertThat(BatteryDiffEntry.sResourceCache).hasSize(1); assertThat(BatteryDiffEntry.sResourceCache).hasSize(1);
// Verifies the app label in the cache. // Verifies the app label in the cache.
final BatteryEntry.NameAndIcon nameAndIcon = final BatteryEntry.NameAndIcon nameAndIcon =
BatteryDiffEntry.sResourceCache.get(entry.getKey()); BatteryDiffEntry.sResourceCache.get(entry.getKey());
assertThat(nameAndIcon.mName).isEqualTo(expectedAppLabel); assertThat(nameAndIcon.mName).isEqualTo(expectedAppLabel);
} }
@@ -222,7 +232,7 @@ public final class BatteryDiffEntryTest {
public void testGetAppLabel_nullAppLabel_returnAppLabelInBatteryHistEntry() { public void testGetAppLabel_nullAppLabel_returnAppLabelInBatteryHistEntry() {
final String expectedAppLabel = "fake app label"; final String expectedAppLabel = "fake app label";
final ContentValues values = getContentValuesWithType( final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY); ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put("appLabel", expectedAppLabel); values.put("appLabel", expectedAppLabel);
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values); final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
@@ -236,15 +246,15 @@ public final class BatteryDiffEntryTest {
@Test @Test
public void testGetAppIcon_nonUidConsumer_returnAppIconInBatteryDiffEntry() { public void testGetAppIcon_nonUidConsumer_returnAppIconInBatteryDiffEntry() {
final ContentValues values = getContentValuesWithType( final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY); ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values); final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
mockConstantState(mockDrawable); mockConstantState(mMockDrawable);
final BatteryDiffEntry entry = createBatteryDiffEntry(10, batteryHistEntry); final BatteryDiffEntry entry = createBatteryDiffEntry(10, batteryHistEntry);
entry.mIsLoaded = true; entry.mIsLoaded = true;
entry.mAppIcon = mockDrawable; entry.mAppIcon = mMockDrawable;
assertThat(entry.getAppIcon()).isEqualTo(mockDrawable); assertThat(entry.getAppIcon()).isEqualTo(mMockDrawable);
assertThat(BatteryDiffEntry.sResourceCache).isEmpty(); assertThat(BatteryDiffEntry.sResourceCache).isEmpty();
} }
@@ -252,38 +262,38 @@ public final class BatteryDiffEntryTest {
public void testGetAppIcon_uidConsumerForNonOwner_returnDefaultActivityIconWithBadge() public void testGetAppIcon_uidConsumerForNonOwner_returnDefaultActivityIconWithBadge()
throws Exception { throws Exception {
ShadowUserHandle.setUid(10); ShadowUserHandle.setUid(10);
final BatteryDiffEntry entry = createBatteryDiffEntry(mockDrawable); final BatteryDiffEntry entry = createBatteryDiffEntry(mMockDrawable);
mockConstantState(mockDrawable); mockConstantState(mMockDrawable);
mockConstantState(mockBadgedDrawable); mockConstantState(mMockBadgedDrawable);
doReturn(mockBadgedDrawable).when(mockUserManager) doReturn(mMockBadgedDrawable).when(mMockUserManager)
.getBadgedIconForUser(eq(mockDrawable), any()); .getBadgedIconForUser(eq(mMockDrawable), any());
entry.mAppIcon = null; entry.mAppIcon = null;
assertThat(entry.getAppIcon()).isEqualTo(mockBadgedDrawable); assertThat(entry.getAppIcon()).isEqualTo(mMockBadgedDrawable);
} }
@Test @Test
public void testGetAppIcon_uidConsumerWithNullIcon_returnDefaultActivityIcon() public void testGetAppIcon_uidConsumerWithNullIcon_returnDefaultActivityIcon()
throws Exception { throws Exception {
final BatteryDiffEntry entry = createBatteryDiffEntry(mockDrawable); final BatteryDiffEntry entry = createBatteryDiffEntry(mMockDrawable);
mockConstantState(mockDrawable); mockConstantState(mMockDrawable);
entry.mAppIcon = null; entry.mAppIcon = null;
assertThat(entry.getAppIcon()).isEqualTo(mockDrawable); assertThat(entry.getAppIcon()).isEqualTo(mMockDrawable);
assertThat(BatteryDiffEntry.sResourceCache).hasSize(1); assertThat(BatteryDiffEntry.sResourceCache).hasSize(1);
// Verifies the app label in the cache. // Verifies the app label in the cache.
final BatteryEntry.NameAndIcon nameAndIcon = final BatteryEntry.NameAndIcon nameAndIcon =
BatteryDiffEntry.sResourceCache.get(entry.getKey()); BatteryDiffEntry.sResourceCache.get(entry.getKey());
assertThat(nameAndIcon.mIcon).isEqualTo(mockDrawable); assertThat(nameAndIcon.mIcon).isEqualTo(mMockDrawable);
} }
@Test @Test
public void testClearCache_clearDataForResourcesAndFlags() { public void testClearCache_clearDataForResourcesAndFlags() {
BatteryDiffEntry.sResourceCache.put( BatteryDiffEntry.sResourceCache.put(
"fake application key", "fake application key",
new BatteryEntry.NameAndIcon("app label", null, /*iconId=*/ 0)); new BatteryEntry.NameAndIcon("app label", null, /*iconId=*/ 0));
BatteryDiffEntry.sValidForRestriction.put( BatteryDiffEntry.sValidForRestriction.put(
"fake application key", Boolean.valueOf(false)); "fake application key", Boolean.valueOf(false));
BatteryDiffEntry.clearCache(); BatteryDiffEntry.clearCache();
@@ -295,83 +305,83 @@ public final class BatteryDiffEntryTest {
public void testClearCache_switchLocale_clearCacheIconAndLabel() throws Exception { public void testClearCache_switchLocale_clearCacheIconAndLabel() throws Exception {
final int userId = UserHandle.getUserId(1001); final int userId = UserHandle.getUserId(1001);
Locale.setDefault(new Locale("en_US")); Locale.setDefault(new Locale("en_US"));
final BatteryDiffEntry entry1 = createBatteryDiffEntry(mockDrawable); final BatteryDiffEntry entry1 = createBatteryDiffEntry(mMockDrawable);
mockConstantState(mockDrawable); mockConstantState(mMockDrawable);
assertThat(entry1.getAppIcon()).isEqualTo(mockDrawable); assertThat(entry1.getAppIcon()).isEqualTo(mMockDrawable);
// Switch the locale into another one. // Switch the locale into another one.
Locale.setDefault(new Locale("zh_TW")); Locale.setDefault(new Locale("zh_TW"));
final BatteryDiffEntry entry2 = createBatteryDiffEntry(mockDrawable2); final BatteryDiffEntry entry2 = createBatteryDiffEntry(mMockDrawable2);
// We should get new drawable without caching. // We should get new drawable without caching.
mockConstantState(mockDrawable2); mockConstantState(mMockDrawable2);
assertThat(entry2.getAppIcon()).isEqualTo(mockDrawable2); assertThat(entry2.getAppIcon()).isEqualTo(mMockDrawable2);
// Verifies the cache is updated into the new drawable. // Verifies the cache is updated into the new drawable.
final BatteryEntry.NameAndIcon nameAndIcon = final BatteryEntry.NameAndIcon nameAndIcon =
BatteryDiffEntry.sResourceCache.get(entry2.getKey()); BatteryDiffEntry.sResourceCache.get(entry2.getKey());
assertThat(nameAndIcon.mIcon).isEqualTo(mockDrawable2); assertThat(nameAndIcon.mIcon).isEqualTo(mMockDrawable2);
} }
@Test @Test
public void testIsSystemEntry_userBattery_returnTrue() { public void testIsSystemEntry_userBattery_returnTrue() {
final BatteryDiffEntry entry = final BatteryDiffEntry entry =
createBatteryDiffEntry( createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_USER_BATTERY, ConvertUtils.CONSUMER_TYPE_USER_BATTERY,
/*uid=*/ 0, /*isHidden=*/ false); /*uid=*/ 0, /*isHidden=*/ false);
assertThat(entry.isSystemEntry()).isTrue(); assertThat(entry.isSystemEntry()).isTrue();
} }
@Test @Test
public void testIsSystemEntry_systemBattery_returnTrue() { public void testIsSystemEntry_systemBattery_returnTrue() {
final BatteryDiffEntry entry = final BatteryDiffEntry entry =
createBatteryDiffEntry( createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY, ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY,
/*uid=*/ 0, /*isHidden=*/ false); /*uid=*/ 0, /*isHidden=*/ false);
assertThat(entry.isSystemEntry()).isTrue(); assertThat(entry.isSystemEntry()).isTrue();
} }
@Test @Test
public void testIsSystemEntry_uidBattery_returnFalse() { public void testIsSystemEntry_uidBattery_returnFalse() {
final BatteryDiffEntry entry = final BatteryDiffEntry entry =
createBatteryDiffEntry( createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY, ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ 123, /*isHidden=*/ false); /*uid=*/ 123, /*isHidden=*/ false);
assertThat(entry.isSystemEntry()).isFalse(); assertThat(entry.isSystemEntry()).isFalse();
} }
@Test @Test
public void testIsSystemEntry_uidBatteryWithHiddenState_returnTrue() { public void testIsSystemEntry_uidBatteryWithHiddenState_returnTrue() {
final BatteryDiffEntry entry = final BatteryDiffEntry entry =
createBatteryDiffEntry( createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY, ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ 123, /*isHidden=*/ true); /*uid=*/ 123, /*isHidden=*/ true);
assertThat(entry.isSystemEntry()).isTrue(); assertThat(entry.isSystemEntry()).isTrue();
} }
@Test @Test
public void testIsSystemEntry_uidBatteryWithSystemProcess_returnFalse() { public void testIsSystemEntry_uidBatteryWithSystemProcess_returnFalse() {
final BatteryDiffEntry entry = final BatteryDiffEntry entry =
createBatteryDiffEntry( createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY, ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ 1230, /*isHidden=*/ false); /*uid=*/ 1230, /*isHidden=*/ false);
assertThat(entry.isSystemEntry()).isFalse(); assertThat(entry.isSystemEntry()).isFalse();
} }
@Test @Test
public void testIsSystemEntry_uidBatteryWithTetheringProcess_returnTrue() { public void testIsSystemEntry_uidBatteryWithTetheringProcess_returnTrue() {
final BatteryDiffEntry entry = final BatteryDiffEntry entry =
createBatteryDiffEntry( createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY, ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ BatteryUtils.UID_TETHERING, /*isHidden=*/ false); /*uid=*/ BatteryUtils.UID_TETHERING, /*isHidden=*/ false);
assertThat(entry.isSystemEntry()).isTrue(); assertThat(entry.isSystemEntry()).isTrue();
} }
@Test @Test
public void testIsSystemEntry_uidBatteryWithRemovedAppsProcess_returnTrue() { public void testIsSystemEntry_uidBatteryWithRemovedAppsProcess_returnTrue() {
final BatteryDiffEntry entry = final BatteryDiffEntry entry =
createBatteryDiffEntry( createBatteryDiffEntry(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY, ConvertUtils.CONSUMER_TYPE_UID_BATTERY,
/*uid=*/ BatteryUtils.UID_REMOVED_APPS, /*isHidden=*/ false); /*uid=*/ BatteryUtils.UID_REMOVED_APPS, /*isHidden=*/ false);
assertThat(entry.isSystemEntry()).isTrue(); assertThat(entry.isSystemEntry()).isTrue();
} }
@@ -380,30 +390,30 @@ public final class BatteryDiffEntryTest {
final String expectedAppLabel = "fake app label"; final String expectedAppLabel = "fake app label";
final String fakePackageName = "com.fake.google.com"; final String fakePackageName = "com.fake.google.com";
final ContentValues values = getContentValuesWithType( final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY); ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put("uid", /*invalid uid*/ 10001); values.put("uid", /*invalid uid*/ 10001);
values.put("packageName", fakePackageName); values.put("packageName", fakePackageName);
final BatteryDiffEntry entry = final BatteryDiffEntry entry =
createBatteryDiffEntry(10, new BatteryHistEntry(values)); createBatteryDiffEntry(10, new BatteryHistEntry(values));
entry.updateRestrictionFlagState(); entry.updateRestrictionFlagState();
// Sets false if the app entry cannot be found. // Sets false if the app entry cannot be found.
assertThat(entry.mValidForRestriction).isFalse(); assertThat(entry.mValidForRestriction).isFalse();
doReturn(BatteryUtils.UID_NULL).when(mockPackageManager).getPackageUid( doReturn(BatteryUtils.UID_NULL).when(mMockPackageManager).getPackageUid(
entry.getPackageName(), PackageManager.GET_META_DATA); entry.getPackageName(), PackageManager.GET_META_DATA);
entry.updateRestrictionFlagState(); entry.updateRestrictionFlagState();
// Sets false if the app is invalid package name. // Sets false if the app is invalid package name.
assertThat(entry.mValidForRestriction).isFalse(); assertThat(entry.mValidForRestriction).isFalse();
doReturn(1000).when(mockPackageManager).getPackageUid( doReturn(1000).when(mMockPackageManager).getPackageUid(
entry.getPackageName(), PackageManager.GET_META_DATA); entry.getPackageName(), PackageManager.GET_META_DATA);
entry.updateRestrictionFlagState(); entry.updateRestrictionFlagState();
// Sets false if the app PackageInfo cannot be found. // Sets false if the app PackageInfo cannot be found.
assertThat(entry.mValidForRestriction).isFalse(); assertThat(entry.mValidForRestriction).isFalse();
doReturn(mockPackageInfo).when(mockPackageManager).getPackageInfo( doReturn(mMockPackageInfo).when(mMockPackageManager).getPackageInfo(
eq(entry.getPackageName()), anyInt()); eq(entry.getPackageName()), anyInt());
entry.updateRestrictionFlagState(); entry.updateRestrictionFlagState();
// Sets true if package is valid and PackageInfo can be found. // Sets true if package is valid and PackageInfo can be found.
assertThat(entry.mValidForRestriction).isTrue(); assertThat(entry.mValidForRestriction).isTrue();
@@ -413,10 +423,10 @@ public final class BatteryDiffEntryTest {
public void testGetPackageName_returnExpectedResult() { public void testGetPackageName_returnExpectedResult() {
final String expectedPackageName = "com.fake.google.com"; final String expectedPackageName = "com.fake.google.com";
final ContentValues values = getContentValuesWithType( final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY); ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put("packageName", expectedPackageName); values.put("packageName", expectedPackageName);
final BatteryDiffEntry entry = final BatteryDiffEntry entry =
createBatteryDiffEntry(10, new BatteryHistEntry(values)); createBatteryDiffEntry(10, new BatteryHistEntry(values));
assertThat(entry.getPackageName()).isEqualTo(expectedPackageName); assertThat(entry.getPackageName()).isEqualTo(expectedPackageName);
} }
@@ -425,12 +435,12 @@ public final class BatteryDiffEntryTest {
public void testGetPackageName_withProcessName_returnExpectedResult() { public void testGetPackageName_withProcessName_returnExpectedResult() {
final String expectedPackageName = "com.fake.google.com"; final String expectedPackageName = "com.fake.google.com";
final ContentValues values = getContentValuesWithType( final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY); ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put( values.put(
"packageName", "packageName",
expectedPackageName + ":privileged_process0"); expectedPackageName + ":privileged_process0");
final BatteryDiffEntry entry = final BatteryDiffEntry entry =
createBatteryDiffEntry(10, new BatteryHistEntry(values)); createBatteryDiffEntry(10, new BatteryHistEntry(values));
assertThat(entry.getPackageName()).isEqualTo(expectedPackageName); assertThat(entry.getPackageName()).isEqualTo(expectedPackageName);
} }
@@ -441,21 +451,21 @@ public final class BatteryDiffEntryTest {
values.put("isHidden", isHidden); values.put("isHidden", isHidden);
values.put("uid", uid); values.put("uid", uid);
return new BatteryDiffEntry( return new BatteryDiffEntry(
mContext, mContext,
/*foregroundUsageTimeInMs=*/ 0, /*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ 0, /*backgroundUsageTimeInMs=*/ 0,
/*consumePower=*/ 0, /*consumePower=*/ 0,
new BatteryHistEntry(values)); new BatteryHistEntry(values));
} }
private BatteryDiffEntry createBatteryDiffEntry( private BatteryDiffEntry createBatteryDiffEntry(
double consumePower, BatteryHistEntry batteryHistEntry) { double consumePower, BatteryHistEntry batteryHistEntry) {
final BatteryDiffEntry entry = new BatteryDiffEntry( final BatteryDiffEntry entry = new BatteryDiffEntry(
mContext, mContext,
/*foregroundUsageTimeInMs=*/ 0, /*foregroundUsageTimeInMs=*/ 0,
/*backgroundUsageTimeInMs=*/ 0, /*backgroundUsageTimeInMs=*/ 0,
consumePower, consumePower,
batteryHistEntry); batteryHistEntry);
entry.setTotalConsumePower(100.0); entry.setTotalConsumePower(100.0);
return entry; return entry;
} }
@@ -468,20 +478,20 @@ public final class BatteryDiffEntryTest {
private BatteryDiffEntry createBatteryDiffEntry(Drawable drawable) throws Exception { private BatteryDiffEntry createBatteryDiffEntry(Drawable drawable) throws Exception {
final ContentValues values = getContentValuesWithType( final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY); ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put("uid", 1001); values.put("uid", 1001);
values.put("packageName", "com.a.b.c"); values.put("packageName", "com.a.b.c");
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values); final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
doReturn(drawable).when(mockPackageManager).getDefaultActivityIcon(); doReturn(drawable).when(mMockPackageManager).getDefaultActivityIcon();
doReturn(null).when(mockPackageManager).getApplicationInfo("com.a.b.c", 0); doReturn(null).when(mMockPackageManager).getApplicationInfo("com.a.b.c", 0);
doReturn(new String[] {"com.a.b.c"}).when(mockPackageManager) doReturn(new String[]{"com.a.b.c"}).when(mMockPackageManager)
.getPackagesForUid(1001); .getPackagesForUid(1001);
return createBatteryDiffEntry(10, batteryHistEntry); return createBatteryDiffEntry(10, batteryHistEntry);
} }
private void mockConstantState(Drawable drawable) { private void mockConstantState(Drawable drawable) {
doReturn(mockConstantState).when(drawable).getConstantState(); doReturn(mMockConstantState).when(drawable).getConstantState();
doReturn(drawable).when(mockConstantState).newDrawable(); doReturn(drawable).when(mMockConstantState).newDrawable();
} }
@Implements(UserHandle.class) @Implements(UserHandle.class)

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2016 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
@@ -37,7 +37,8 @@ import android.os.UserBatteryConsumer;
import android.os.UserManager; import android.os.UserManager;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.fuelgauge.BatteryEntry.NameAndIcon; import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.fuelgauge.batteryusage.BatteryEntry.NameAndIcon;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
@@ -62,31 +63,36 @@ public class BatteryEntryTest {
private static final String HIGH_DRAIN_PACKAGE = "com.android.test.screen"; private static final String HIGH_DRAIN_PACKAGE = "com.android.test.screen";
private static final String ANDROID_PACKAGE = "android"; private static final String ANDROID_PACKAGE = "android";
@Rule public MockitoRule mocks = MockitoJUnit.rule(); @Rule
public MockitoRule mocks = MockitoJUnit.rule();
@Mock(answer = Answers.RETURNS_DEEP_STUBS) @Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Context mMockContext; private Context mMockContext;
private Context mContext; private Context mContext;
@Mock private Handler mockHandler; @Mock
@Mock private PackageManager mockPackageManager; private Handler mMockHandler;
@Mock private UserManager mockUserManager; @Mock
@Mock private UidBatteryConsumer mUidBatteryConsumer; private PackageManager mMockPackageManager;
@Mock
private UserManager mMockUserManager;
@Mock
private UidBatteryConsumer mUidBatteryConsumer;
@Before @Before
public void stubContextToReturnMockPackageManager() { public void stubContextToReturnMockPackageManager() {
mContext = spy(RuntimeEnvironment.application); mContext = spy(RuntimeEnvironment.application);
when(mMockContext.getPackageManager()).thenReturn(mockPackageManager); when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager);
} }
@Before @Before
public void stubPackageManagerToReturnAppPackageAndName() throws NameNotFoundException { public void stubPackageManagerToReturnAppPackageAndName() throws NameNotFoundException {
when(mockPackageManager.getApplicationInfo(anyString(), eq(0) /* no flags */)) when(mMockPackageManager.getApplicationInfo(anyString(), eq(0) /* no flags */))
.thenAnswer(invocation -> { .thenAnswer(invocation -> {
ApplicationInfo info = new ApplicationInfo(); ApplicationInfo info = new ApplicationInfo();
info.packageName = invocation.getArgument(0); info.packageName = invocation.getArgument(0);
return info; return info;
}); });
when(mockPackageManager.getApplicationLabel(any(ApplicationInfo.class))) when(mMockPackageManager.getApplicationLabel(any(ApplicationInfo.class)))
.thenAnswer(invocation -> LABEL_PREFIX .thenAnswer(invocation -> LABEL_PREFIX
+ ((ApplicationInfo) invocation.getArgument(0)).packageName); + ((ApplicationInfo) invocation.getArgument(0)).packageName);
} }
@@ -96,7 +102,7 @@ public class BatteryEntryTest {
UidBatteryConsumer consumer = mock(UidBatteryConsumer.class); UidBatteryConsumer consumer = mock(UidBatteryConsumer.class);
when(consumer.getUid()).thenReturn(APP_UID); when(consumer.getUid()).thenReturn(APP_UID);
when(consumer.getPackageWithHighestDrain()).thenReturn(highDrainPackage); when(consumer.getPackageWithHighestDrain()).thenReturn(highDrainPackage);
return new BatteryEntry(mMockContext, mockHandler, mockUserManager, return new BatteryEntry(mMockContext, mMockHandler, mMockUserManager,
consumer, false, APP_UID, packages, packageName); consumer, false, APP_UID, packages, packageName);
} }
@@ -111,7 +117,7 @@ public class BatteryEntryTest {
private BatteryEntry createUserBatteryConsumer(int userId) { private BatteryEntry createUserBatteryConsumer(int userId) {
UserBatteryConsumer consumer = mock(UserBatteryConsumer.class); UserBatteryConsumer consumer = mock(UserBatteryConsumer.class);
when(consumer.getUserId()).thenReturn(userId); when(consumer.getUserId()).thenReturn(userId);
return new BatteryEntry(mMockContext, mockHandler, mockUserManager, return new BatteryEntry(mMockContext, mMockHandler, mMockUserManager,
consumer, false, 0, null, null); consumer, false, 0, null, null);
} }
@@ -127,7 +133,7 @@ public class BatteryEntryTest {
@Test @Test
public void batteryEntryForApp_shouldSetLabelAsPackageName_whenPackageCannotBeFound() public void batteryEntryForApp_shouldSetLabelAsPackageName_whenPackageCannotBeFound()
throws Exception { throws Exception {
when(mockPackageManager.getApplicationInfo(APP_DEFAULT_PACKAGE_NAME, 0 /* no flags */)) when(mMockPackageManager.getApplicationInfo(APP_DEFAULT_PACKAGE_NAME, 0 /* no flags */))
.thenThrow(new NameNotFoundException()); .thenThrow(new NameNotFoundException());
BatteryEntry entry = createBatteryEntryForApp(null, APP_DEFAULT_PACKAGE_NAME, null); BatteryEntry entry = createBatteryEntryForApp(null, APP_DEFAULT_PACKAGE_NAME, null);
@@ -137,7 +143,7 @@ public class BatteryEntryTest {
@Test @Test
public void batteryEntryForApp_shouldSetHighestDrainPackage_whenPackagesCannotBeFoundForUid() { public void batteryEntryForApp_shouldSetHighestDrainPackage_whenPackagesCannotBeFoundForUid() {
when(mockPackageManager.getPackagesForUid(APP_UID)).thenReturn(null); when(mMockPackageManager.getPackagesForUid(APP_UID)).thenReturn(null);
BatteryEntry entry = createBatteryEntryForApp(null, null, HIGH_DRAIN_PACKAGE); BatteryEntry entry = createBatteryEntryForApp(null, null, HIGH_DRAIN_PACKAGE);
@@ -147,7 +153,7 @@ public class BatteryEntryTest {
@Test @Test
public void batteryEntryForApp_shouldSetHighestDrainPackage_whenMultiplePackagesFoundForUid() { public void batteryEntryForApp_shouldSetHighestDrainPackage_whenMultiplePackagesFoundForUid() {
BatteryEntry entry = createBatteryEntryForApp( BatteryEntry entry = createBatteryEntryForApp(
new String[] {APP_DEFAULT_PACKAGE_NAME, "package2", "package3"}, null, new String[]{APP_DEFAULT_PACKAGE_NAME, "package2", "package3"}, null,
HIGH_DRAIN_PACKAGE); HIGH_DRAIN_PACKAGE);
assertThat(entry.getLabel()).isEqualTo(LABEL_PREFIX + HIGH_DRAIN_PACKAGE); assertThat(entry.getLabel()).isEqualTo(LABEL_PREFIX + HIGH_DRAIN_PACKAGE);
@@ -176,8 +182,8 @@ public class BatteryEntryTest {
when(mUidBatteryConsumer.getTimeInStateMs(UidBatteryConsumer.STATE_FOREGROUND)) when(mUidBatteryConsumer.getTimeInStateMs(UidBatteryConsumer.STATE_FOREGROUND))
.thenReturn(100L); .thenReturn(100L);
final BatteryEntry entry = new BatteryEntry(RuntimeEnvironment.application, mockHandler, final BatteryEntry entry = new BatteryEntry(RuntimeEnvironment.application, mMockHandler,
mockUserManager, mUidBatteryConsumer, false, 0, null, null); mMockUserManager, mUidBatteryConsumer, false, 0, null, null);
assertThat(entry.getTimeInForegroundMs()).isEqualTo(100L); assertThat(entry.getTimeInForegroundMs()).isEqualTo(100L);
} }
@@ -195,8 +201,8 @@ public class BatteryEntryTest {
when(mUidBatteryConsumer.getTimeInStateMs(UidBatteryConsumer.STATE_BACKGROUND)) when(mUidBatteryConsumer.getTimeInStateMs(UidBatteryConsumer.STATE_BACKGROUND))
.thenReturn(100L); .thenReturn(100L);
final BatteryEntry entry = new BatteryEntry(RuntimeEnvironment.application, mockHandler, final BatteryEntry entry = new BatteryEntry(RuntimeEnvironment.application, mMockHandler,
mockUserManager, mUidBatteryConsumer, false, 0, null, null); mMockUserManager, mUidBatteryConsumer, false, 0, null, null);
assertThat(entry.getTimeInBackgroundMs()).isEqualTo(100L); assertThat(entry.getTimeInBackgroundMs()).isEqualTo(100L);
} }
@@ -247,7 +253,7 @@ public class BatteryEntryTest {
@Test @Test
public void getKey_UserBatteryConsumer_returnUserId() { public void getKey_UserBatteryConsumer_returnUserId() {
doReturn(mockUserManager).when(mMockContext).getSystemService(UserManager.class); doReturn(mMockUserManager).when(mMockContext).getSystemService(UserManager.class);
final BatteryEntry entry = createUserBatteryConsumer(2); final BatteryEntry entry = createUserBatteryConsumer(2);
final String key = entry.getKey(); final String key = entry.getKey();
assertThat(key).isEqualTo("U|2"); assertThat(key).isEqualTo("U|2");
@@ -256,8 +262,8 @@ public class BatteryEntryTest {
@Test @Test
public void getNameAndIconFromUserId_nullUserInfo_returnDefaultNameAndIcon() { public void getNameAndIconFromUserId_nullUserInfo_returnDefaultNameAndIcon() {
final int userId = 1001; final int userId = 1001;
doReturn(mockUserManager).when(mContext).getSystemService(UserManager.class); doReturn(mMockUserManager).when(mContext).getSystemService(UserManager.class);
doReturn(null).when(mockUserManager).getUserInfo(userId); doReturn(null).when(mMockUserManager).getUserInfo(userId);
final NameAndIcon nameAndIcon = BatteryEntry.getNameAndIconFromUserId( final NameAndIcon nameAndIcon = BatteryEntry.getNameAndIconFromUserId(
mContext, userId); mContext, userId);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
@@ -38,7 +38,7 @@ import java.util.TimeZone;
public final class BatteryHistEntryTest { public final class BatteryHistEntryTest {
@Mock @Mock
private BatteryEntry mockBatteryEntry; private BatteryEntry mMockBatteryEntry;
@Mock @Mock
private BatteryUsageStats mBatteryUsageStats; private BatteryUsageStats mBatteryUsageStats;
@@ -50,33 +50,33 @@ public final class BatteryHistEntryTest {
@Test @Test
public void testConstructor_contentValues_returnsExpectedResult() { public void testConstructor_contentValues_returnsExpectedResult() {
final int expectedType = 3; final int expectedType = 3;
when(mockBatteryEntry.getUid()).thenReturn(1001); when(mMockBatteryEntry.getUid()).thenReturn(1001);
when(mockBatteryEntry.getLabel()).thenReturn("Settings"); when(mMockBatteryEntry.getLabel()).thenReturn("Settings");
when(mockBatteryEntry.getDefaultPackageName()) when(mMockBatteryEntry.getDefaultPackageName())
.thenReturn("com.google.android.settings.battery"); .thenReturn("com.google.android.settings.battery");
when(mockBatteryEntry.isHidden()).thenReturn(true); when(mMockBatteryEntry.isHidden()).thenReturn(true);
when(mBatteryUsageStats.getConsumedPower()).thenReturn(5.1); when(mBatteryUsageStats.getConsumedPower()).thenReturn(5.1);
when(mockBatteryEntry.getConsumedPower()).thenReturn(1.1); when(mMockBatteryEntry.getConsumedPower()).thenReturn(1.1);
mockBatteryEntry.mPercent = 0.3; mMockBatteryEntry.mPercent = 0.3;
when(mockBatteryEntry.getTimeInForegroundMs()).thenReturn(1234L); when(mMockBatteryEntry.getTimeInForegroundMs()).thenReturn(1234L);
when(mockBatteryEntry.getTimeInBackgroundMs()).thenReturn(5689L); when(mMockBatteryEntry.getTimeInBackgroundMs()).thenReturn(5689L);
when(mockBatteryEntry.getPowerComponentId()).thenReturn(expectedType); when(mMockBatteryEntry.getPowerComponentId()).thenReturn(expectedType);
when(mockBatteryEntry.getConsumerType()) when(mMockBatteryEntry.getConsumerType())
.thenReturn(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY); .thenReturn(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
final ContentValues values = final ContentValues values =
ConvertUtils.convert( ConvertUtils.convert(
mockBatteryEntry, mMockBatteryEntry,
mBatteryUsageStats, mBatteryUsageStats,
/*batteryLevel=*/ 12, /*batteryLevel=*/ 12,
/*batteryStatus=*/ BatteryManager.BATTERY_STATUS_FULL, /*batteryStatus=*/ BatteryManager.BATTERY_STATUS_FULL,
/*batteryHealth=*/ BatteryManager.BATTERY_HEALTH_COLD, /*batteryHealth=*/ BatteryManager.BATTERY_HEALTH_COLD,
/*bootTimestamp=*/ 101L, /*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L); /*timestamp=*/ 10001L);
assertBatteryHistEntry( assertBatteryHistEntry(
new BatteryHistEntry(values), new BatteryHistEntry(values),
/*drainType=*/ expectedType, /*drainType=*/ expectedType,
/*percentOfTotal=*/ mockBatteryEntry.mPercent); /*percentOfTotal=*/ mMockBatteryEntry.mPercent);
} }
@Test @Test
@@ -88,22 +88,22 @@ public final class BatteryHistEntryTest {
@Test @Test
public void testConstructor_cursor_returnsExpectedResult() { public void testConstructor_cursor_returnsExpectedResult() {
assertBatteryHistEntry( assertBatteryHistEntry(
createBatteryHistEntry( createBatteryHistEntry(
/*bootTimestamp=*/ 101L, /*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L, /*timestamp=*/ 10001L,
/*totalPower=*/ 5.1, /*totalPower=*/ 5.1,
/*consumePower=*/ 1.1, /*consumePower=*/ 1.1,
/*foregroundUsageTimeInMs=*/ 1234L, /*foregroundUsageTimeInMs=*/ 1234L,
/*backgroundUsageTimeInMs=*/ 5689L, /*backgroundUsageTimeInMs=*/ 5689L,
/*batteryLevel=*/ 12), /*batteryLevel=*/ 12),
/*drainType=*/ 3, /*drainType=*/ 3,
/*percentOfTotal=*/ 0.3); /*percentOfTotal=*/ 0.3);
} }
@Test @Test
public void testGetKey_consumerUidType_returnExpectedString() { public void testGetKey_consumerUidType_returnExpectedString() {
final ContentValues values = getContentValuesWithType( final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_UID_BATTERY); ConvertUtils.CONSUMER_TYPE_UID_BATTERY);
values.put(BatteryHistEntry.KEY_UID, 3); values.put(BatteryHistEntry.KEY_UID, 3);
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values); final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
@@ -113,7 +113,7 @@ public final class BatteryHistEntryTest {
@Test @Test
public void testGetKey_consumerUserType_returnExpectedString() { public void testGetKey_consumerUserType_returnExpectedString() {
final ContentValues values = getContentValuesWithType( final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_USER_BATTERY); ConvertUtils.CONSUMER_TYPE_USER_BATTERY);
values.put(BatteryHistEntry.KEY_USER_ID, 2); values.put(BatteryHistEntry.KEY_USER_ID, 2);
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values); final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
@@ -123,7 +123,7 @@ public final class BatteryHistEntryTest {
@Test @Test
public void testGetKey_consumerSystemType_returnExpectedString() { public void testGetKey_consumerSystemType_returnExpectedString() {
final ContentValues values = getContentValuesWithType( final ContentValues values = getContentValuesWithType(
ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY); ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
values.put(BatteryHistEntry.KEY_DRAIN_TYPE, 1); values.put(BatteryHistEntry.KEY_DRAIN_TYPE, 1);
final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values); final BatteryHistEntry batteryHistEntry = new BatteryHistEntry(values);
@@ -133,31 +133,31 @@ public final class BatteryHistEntryTest {
@Test @Test
public void testIsAppEntry_returnExpectedResult() { public void testIsAppEntry_returnExpectedResult() {
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY).isAppEntry()) assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY).isAppEntry())
.isFalse(); .isFalse();
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_USER_BATTERY).isAppEntry()) assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_USER_BATTERY).isAppEntry())
.isFalse(); .isFalse();
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_UID_BATTERY).isAppEntry()) assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_UID_BATTERY).isAppEntry())
.isTrue(); .isTrue();
} }
@Test @Test
public void testIsUserEntry_returnExpectedResult() { public void testIsUserEntry_returnExpectedResult() {
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY).isUserEntry()) assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY).isUserEntry())
.isFalse(); .isFalse();
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_USER_BATTERY).isUserEntry()) assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_USER_BATTERY).isUserEntry())
.isTrue(); .isTrue();
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_UID_BATTERY).isUserEntry()) assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_UID_BATTERY).isUserEntry())
.isFalse(); .isFalse();
} }
@Test @Test
public void testIsSystemEntry_returnExpectedResult() { public void testIsSystemEntry_returnExpectedResult() {
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY).isSystemEntry()) assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY).isSystemEntry())
.isTrue(); .isTrue();
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_USER_BATTERY).isSystemEntry()) assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_USER_BATTERY).isSystemEntry())
.isFalse(); .isFalse();
assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_UID_BATTERY).isSystemEntry()) assertThat(createEntry(ConvertUtils.CONSUMER_TYPE_UID_BATTERY).isSystemEntry())
.isFalse(); .isFalse();
} }
@Test @Test
@@ -167,39 +167,39 @@ public final class BatteryHistEntryTest {
final long lowerTimestamp = 100L; final long lowerTimestamp = 100L;
final double ratio = 0.5; final double ratio = 0.5;
final BatteryHistEntry lowerHistEntry = createBatteryHistEntry( final BatteryHistEntry lowerHistEntry = createBatteryHistEntry(
/*bootTimestamp=*/ 1000L, /*bootTimestamp=*/ 1000L,
lowerTimestamp, lowerTimestamp,
/*totalPower=*/ 50, /*totalPower=*/ 50,
/*consumePower=*/ 10, /*consumePower=*/ 10,
/*foregroundUsageTimeInMs=*/ 100, /*foregroundUsageTimeInMs=*/ 100,
/*backgroundUsageTimeInMs=*/ 200, /*backgroundUsageTimeInMs=*/ 200,
/*batteryLevel=*/ 90); /*batteryLevel=*/ 90);
final BatteryHistEntry upperHistEntry = createBatteryHistEntry( final BatteryHistEntry upperHistEntry = createBatteryHistEntry(
/*bootTimestamp=*/ 1200L, /*bootTimestamp=*/ 1200L,
upperTimestamp, upperTimestamp,
/*totalPower=*/ 80, /*totalPower=*/ 80,
/*consumePower=*/ 20, /*consumePower=*/ 20,
/*foregroundUsageTimeInMs=*/ 200, /*foregroundUsageTimeInMs=*/ 200,
/*backgroundUsageTimeInMs=*/ 300, /*backgroundUsageTimeInMs=*/ 300,
/*batteryLevel=*/ 80); /*batteryLevel=*/ 80);
final BatteryHistEntry newEntry = final BatteryHistEntry newEntry =
BatteryHistEntry.interpolate( BatteryHistEntry.interpolate(
slotTimestamp, slotTimestamp,
upperTimestamp, upperTimestamp,
ratio, ratio,
lowerHistEntry, lowerHistEntry,
upperHistEntry); upperHistEntry);
assertBatteryHistEntry( assertBatteryHistEntry(
newEntry, 3, upperHistEntry.mPercentOfTotal, newEntry, 3, upperHistEntry.mPercentOfTotal,
/*bootTimestamp=*/ 1200 - 100, /*bootTimestamp=*/ 1200 - 100,
/*timestamp=*/ slotTimestamp, /*timestamp=*/ slotTimestamp,
/*totalPower=*/ 50 + 0.5 * (80 - 50), /*totalPower=*/ 50 + 0.5 * (80 - 50),
/*consumePower=*/ 10 + 0.5 * (20 - 10), /*consumePower=*/ 10 + 0.5 * (20 - 10),
/*foregroundUsageTimeInMs=*/ Math.round(100 + 0.5 * (200 - 100)), /*foregroundUsageTimeInMs=*/ Math.round(100 + 0.5 * (200 - 100)),
/*backgroundUsageTimeInMs=*/ Math.round(200 + 0.5 * (300 - 200)), /*backgroundUsageTimeInMs=*/ Math.round(200 + 0.5 * (300 - 200)),
/*batteryLevel=*/ (int) Math.round(90 + 0.5 * (80 - 90))); /*batteryLevel=*/ (int) Math.round(90 + 0.5 * (80 - 90)));
} }
@Test @Test
@@ -209,31 +209,31 @@ public final class BatteryHistEntryTest {
final long lowerTimestamp = 100L; final long lowerTimestamp = 100L;
final double ratio = 0.5; final double ratio = 0.5;
final BatteryHistEntry upperHistEntry = createBatteryHistEntry( final BatteryHistEntry upperHistEntry = createBatteryHistEntry(
/*bootTimestamp=*/ 1200L, /*bootTimestamp=*/ 1200L,
upperTimestamp, upperTimestamp,
/*totalPower=*/ 80, /*totalPower=*/ 80,
/*consumePower=*/ 20, /*consumePower=*/ 20,
/*foregroundUsageTimeInMs=*/ 200, /*foregroundUsageTimeInMs=*/ 200,
/*backgroundUsageTimeInMs=*/ 300, /*backgroundUsageTimeInMs=*/ 300,
/*batteryLevel=*/ 80); /*batteryLevel=*/ 80);
final BatteryHistEntry newEntry = final BatteryHistEntry newEntry =
BatteryHistEntry.interpolate( BatteryHistEntry.interpolate(
slotTimestamp, slotTimestamp,
upperTimestamp, upperTimestamp,
ratio, ratio,
/*lowerHistEntry=*/ null, /*lowerHistEntry=*/ null,
upperHistEntry); upperHistEntry);
assertBatteryHistEntry( assertBatteryHistEntry(
newEntry, 3, upperHistEntry.mPercentOfTotal, newEntry, 3, upperHistEntry.mPercentOfTotal,
/*bootTimestamp=*/ 1200 - 100, /*bootTimestamp=*/ 1200 - 100,
/*timestamp=*/ slotTimestamp, /*timestamp=*/ slotTimestamp,
/*totalPower=*/ 0.5 * 80, /*totalPower=*/ 0.5 * 80,
/*consumePower=*/ 0.5 * 20, /*consumePower=*/ 0.5 * 20,
/*foregroundUsageTimeInMs=*/ Math.round(0.5 * 200), /*foregroundUsageTimeInMs=*/ Math.round(0.5 * 200),
/*backgroundUsageTimeInMs=*/ Math.round(0.5 * 300), /*backgroundUsageTimeInMs=*/ Math.round(0.5 * 300),
/*batteryLevel=*/ upperHistEntry.mBatteryLevel); /*batteryLevel=*/ upperHistEntry.mBatteryLevel);
} }
private static BatteryHistEntry createEntry(int consumerType) { private static BatteryHistEntry createEntry(int consumerType) {
@@ -243,21 +243,21 @@ public final class BatteryHistEntryTest {
private static ContentValues getContentValuesWithType(int consumerType) { private static ContentValues getContentValuesWithType(int consumerType) {
final ContentValues values = new ContentValues(); final ContentValues values = new ContentValues();
values.put(BatteryHistEntry.KEY_CONSUMER_TYPE, values.put(BatteryHistEntry.KEY_CONSUMER_TYPE,
Integer.valueOf(consumerType)); Integer.valueOf(consumerType));
return values; return values;
} }
private void assertBatteryHistEntry( private void assertBatteryHistEntry(
BatteryHistEntry entry, int drainType, double percentOfTotal) { BatteryHistEntry entry, int drainType, double percentOfTotal) {
assertBatteryHistEntry( assertBatteryHistEntry(
entry, drainType, percentOfTotal, entry, drainType, percentOfTotal,
/*bootTimestamp=*/ 101L, /*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L, /*timestamp=*/ 10001L,
/*totalPower=*/ 5.1, /*totalPower=*/ 5.1,
/*consumePower=*/ 1.1, /*consumePower=*/ 1.1,
/*foregroundUsageTimeInMs=*/ 1234L, /*foregroundUsageTimeInMs=*/ 1234L,
/*backgroundUsageTimeInMs=*/ 5689L, /*backgroundUsageTimeInMs=*/ 5689L,
/*batteryLevel=*/ 12); /*batteryLevel=*/ 12);
} }
private void assertBatteryHistEntry( private void assertBatteryHistEntry(
@@ -276,7 +276,7 @@ public final class BatteryHistEntryTest {
assertThat(entry.mUserId).isEqualTo(UserHandle.getUserId(1001)); assertThat(entry.mUserId).isEqualTo(UserHandle.getUserId(1001));
assertThat(entry.mAppLabel).isEqualTo("Settings"); assertThat(entry.mAppLabel).isEqualTo("Settings");
assertThat(entry.mPackageName) assertThat(entry.mPackageName)
.isEqualTo("com.google.android.settings.battery"); .isEqualTo("com.google.android.settings.battery");
assertThat(entry.mIsHidden).isTrue(); assertThat(entry.mIsHidden).isTrue();
assertThat(entry.mBootTimestamp).isEqualTo(bootTimestamp); assertThat(entry.mBootTimestamp).isEqualTo(bootTimestamp);
assertThat(entry.mTimestamp).isEqualTo(timestamp); assertThat(entry.mTimestamp).isEqualTo(timestamp);
@@ -288,12 +288,12 @@ public final class BatteryHistEntryTest {
assertThat(entry.mBackgroundUsageTimeInMs).isEqualTo(backgroundUsageTimeInMs); assertThat(entry.mBackgroundUsageTimeInMs).isEqualTo(backgroundUsageTimeInMs);
assertThat(entry.mDrainType).isEqualTo(drainType); assertThat(entry.mDrainType).isEqualTo(drainType);
assertThat(entry.mConsumerType) assertThat(entry.mConsumerType)
.isEqualTo(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY); .isEqualTo(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
assertThat(entry.mBatteryLevel).isEqualTo(batteryLevel); assertThat(entry.mBatteryLevel).isEqualTo(batteryLevel);
assertThat(entry.mBatteryStatus) assertThat(entry.mBatteryStatus)
.isEqualTo(BatteryManager.BATTERY_STATUS_FULL); .isEqualTo(BatteryManager.BATTERY_STATUS_FULL);
assertThat(entry.mBatteryHealth) assertThat(entry.mBatteryHealth)
.isEqualTo(BatteryManager.BATTERY_HEALTH_COLD); .isEqualTo(BatteryManager.BATTERY_HEALTH_COLD);
} }
private BatteryHistEntry createBatteryHistEntry( private BatteryHistEntry createBatteryHistEntry(
@@ -305,7 +305,7 @@ public final class BatteryHistEntryTest {
long backgroundUsageTimeInMs, long backgroundUsageTimeInMs,
int batteryLevel) { int batteryLevel) {
final MatrixCursor cursor = new MatrixCursor( final MatrixCursor cursor = new MatrixCursor(
new String[] { new String[]{
BatteryHistEntry.KEY_UID, BatteryHistEntry.KEY_UID,
BatteryHistEntry.KEY_USER_ID, BatteryHistEntry.KEY_USER_ID,
BatteryHistEntry.KEY_APP_LABEL, BatteryHistEntry.KEY_APP_LABEL,
@@ -325,7 +325,7 @@ public final class BatteryHistEntryTest {
BatteryHistEntry.KEY_BATTERY_STATUS, BatteryHistEntry.KEY_BATTERY_STATUS,
BatteryHistEntry.KEY_BATTERY_HEALTH}); BatteryHistEntry.KEY_BATTERY_HEALTH});
cursor.addRow( cursor.addRow(
new Object[] { new Object[]{
Long.valueOf(1001), Long.valueOf(1001),
Long.valueOf(UserHandle.getUserId(1001)), Long.valueOf(UserHandle.getUserId(1001)),
"Settings", "Settings",

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,18 +13,16 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import android.content.Context; import android.content.Context;
import com.android.settings.testutils.FakeFeatureFactory; import com.android.settings.testutils.FakeFeatureFactory;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@@ -32,6 +30,9 @@ import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import java.util.HashMap;
import java.util.Map;
@RunWith(RobolectricTestRunner.class) @RunWith(RobolectricTestRunner.class)
public final class BatteryHistoryLoaderTest { public final class BatteryHistoryLoaderTest {

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
@@ -31,6 +31,7 @@ import android.widget.TextView;
import androidx.preference.PreferenceViewHolder; import androidx.preference.PreferenceViewHolder;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.fuelgauge.BatteryInfo;
import com.android.settings.widget.UsageView; import com.android.settings.widget.UsageView;
import org.junit.Before; import org.junit.Before;

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2017 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
@@ -27,6 +27,7 @@ import android.os.BatteryUsageStats;
import android.os.LocaleList; import android.os.LocaleList;
import android.os.UserHandle; import android.os.UserHandle;
import com.android.settings.fuelgauge.PowerUsageFeatureProvider;
import com.android.settings.testutils.FakeFeatureFactory; import com.android.settings.testutils.FakeFeatureFactory;
import org.junit.Before; import org.junit.Before;
@@ -37,7 +38,6 @@ import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@@ -54,7 +54,7 @@ public final class ConvertUtilsTest {
@Mock @Mock
private BatteryUsageStats mBatteryUsageStats; private BatteryUsageStats mBatteryUsageStats;
@Mock @Mock
private BatteryEntry mockBatteryEntry; private BatteryEntry mMockBatteryEntry;
private FakeFeatureFactory mFeatureFactory; private FakeFeatureFactory mFeatureFactory;
private PowerUsageFeatureProvider mPowerUsageFeatureProvider; private PowerUsageFeatureProvider mPowerUsageFeatureProvider;
@@ -70,115 +70,116 @@ public final class ConvertUtilsTest {
@Test @Test
public void convert_returnsExpectedContentValues() { public void convert_returnsExpectedContentValues() {
final int expectedType = 3; final int expectedType = 3;
when(mockBatteryEntry.getUid()).thenReturn(1001); when(mMockBatteryEntry.getUid()).thenReturn(1001);
when(mockBatteryEntry.getLabel()).thenReturn("Settings"); when(mMockBatteryEntry.getLabel()).thenReturn("Settings");
when(mockBatteryEntry.getDefaultPackageName()) when(mMockBatteryEntry.getDefaultPackageName())
.thenReturn("com.google.android.settings.battery"); .thenReturn("com.google.android.settings.battery");
when(mockBatteryEntry.isHidden()).thenReturn(true); when(mMockBatteryEntry.isHidden()).thenReturn(true);
when(mBatteryUsageStats.getConsumedPower()).thenReturn(5.1); when(mBatteryUsageStats.getConsumedPower()).thenReturn(5.1);
when(mockBatteryEntry.getConsumedPower()).thenReturn(1.1); when(mMockBatteryEntry.getConsumedPower()).thenReturn(1.1);
mockBatteryEntry.mPercent = 0.3; mMockBatteryEntry.mPercent = 0.3;
when(mockBatteryEntry.getTimeInForegroundMs()).thenReturn(1234L); when(mMockBatteryEntry.getTimeInForegroundMs()).thenReturn(1234L);
when(mockBatteryEntry.getTimeInBackgroundMs()).thenReturn(5689L); when(mMockBatteryEntry.getTimeInBackgroundMs()).thenReturn(5689L);
when(mockBatteryEntry.getPowerComponentId()).thenReturn(expectedType); when(mMockBatteryEntry.getPowerComponentId()).thenReturn(expectedType);
when(mockBatteryEntry.getConsumerType()) when(mMockBatteryEntry.getConsumerType())
.thenReturn(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY); .thenReturn(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
final ContentValues values = final ContentValues values =
ConvertUtils.convert( ConvertUtils.convert(
mockBatteryEntry, mMockBatteryEntry,
mBatteryUsageStats, mBatteryUsageStats,
/*batteryLevel=*/ 12, /*batteryLevel=*/ 12,
/*batteryStatus=*/ BatteryManager.BATTERY_STATUS_FULL, /*batteryStatus=*/ BatteryManager.BATTERY_STATUS_FULL,
/*batteryHealth=*/ BatteryManager.BATTERY_HEALTH_COLD, /*batteryHealth=*/ BatteryManager.BATTERY_HEALTH_COLD,
/*bootTimestamp=*/ 101L, /*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L); /*timestamp=*/ 10001L);
assertThat(values.getAsLong(BatteryHistEntry.KEY_UID)).isEqualTo(1001L); assertThat(values.getAsLong(BatteryHistEntry.KEY_UID)).isEqualTo(1001L);
assertThat(values.getAsLong(BatteryHistEntry.KEY_USER_ID)) assertThat(values.getAsLong(BatteryHistEntry.KEY_USER_ID))
.isEqualTo(UserHandle.getUserId(1001)); .isEqualTo(UserHandle.getUserId(1001));
assertThat(values.getAsString(BatteryHistEntry.KEY_APP_LABEL)) assertThat(values.getAsString(BatteryHistEntry.KEY_APP_LABEL))
.isEqualTo("Settings"); .isEqualTo("Settings");
assertThat(values.getAsString(BatteryHistEntry.KEY_PACKAGE_NAME)) assertThat(values.getAsString(BatteryHistEntry.KEY_PACKAGE_NAME))
.isEqualTo("com.google.android.settings.battery"); .isEqualTo("com.google.android.settings.battery");
assertThat(values.getAsBoolean(BatteryHistEntry.KEY_IS_HIDDEN)).isTrue(); assertThat(values.getAsBoolean(BatteryHistEntry.KEY_IS_HIDDEN)).isTrue();
assertThat(values.getAsLong(BatteryHistEntry.KEY_BOOT_TIMESTAMP)) assertThat(values.getAsLong(BatteryHistEntry.KEY_BOOT_TIMESTAMP))
.isEqualTo(101L); .isEqualTo(101L);
assertThat(values.getAsLong(BatteryHistEntry.KEY_TIMESTAMP)).isEqualTo(10001L); assertThat(values.getAsLong(BatteryHistEntry.KEY_TIMESTAMP)).isEqualTo(10001L);
assertThat(values.getAsString(BatteryHistEntry.KEY_ZONE_ID)) assertThat(values.getAsString(BatteryHistEntry.KEY_ZONE_ID))
.isEqualTo(TimeZone.getDefault().getID()); .isEqualTo(TimeZone.getDefault().getID());
assertThat(values.getAsDouble(BatteryHistEntry.KEY_TOTAL_POWER)).isEqualTo(5.1); assertThat(values.getAsDouble(BatteryHistEntry.KEY_TOTAL_POWER)).isEqualTo(5.1);
assertThat(values.getAsDouble(BatteryHistEntry.KEY_CONSUME_POWER)).isEqualTo(1.1); assertThat(values.getAsDouble(BatteryHistEntry.KEY_CONSUME_POWER)).isEqualTo(1.1);
assertThat(values.getAsDouble(BatteryHistEntry.KEY_PERCENT_OF_TOTAL)).isEqualTo(0.3); assertThat(values.getAsDouble(BatteryHistEntry.KEY_PERCENT_OF_TOTAL)).isEqualTo(0.3);
assertThat(values.getAsLong(BatteryHistEntry.KEY_FOREGROUND_USAGE_TIME)) assertThat(values.getAsLong(BatteryHistEntry.KEY_FOREGROUND_USAGE_TIME))
.isEqualTo(1234L); .isEqualTo(1234L);
assertThat(values.getAsLong(BatteryHistEntry.KEY_BACKGROUND_USAGE_TIME)) assertThat(values.getAsLong(BatteryHistEntry.KEY_BACKGROUND_USAGE_TIME))
.isEqualTo(5689L); .isEqualTo(5689L);
assertThat(values.getAsInteger(BatteryHistEntry.KEY_DRAIN_TYPE)).isEqualTo(expectedType); assertThat(values.getAsInteger(BatteryHistEntry.KEY_DRAIN_TYPE)).isEqualTo(expectedType);
assertThat(values.getAsInteger(BatteryHistEntry.KEY_CONSUMER_TYPE)) assertThat(values.getAsInteger(BatteryHistEntry.KEY_CONSUMER_TYPE))
.isEqualTo(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY); .isEqualTo(ConvertUtils.CONSUMER_TYPE_SYSTEM_BATTERY);
assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_LEVEL)).isEqualTo(12); assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_LEVEL)).isEqualTo(12);
assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_STATUS)) assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_STATUS))
.isEqualTo(BatteryManager.BATTERY_STATUS_FULL); .isEqualTo(BatteryManager.BATTERY_STATUS_FULL);
assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_HEALTH)) assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_HEALTH))
.isEqualTo(BatteryManager.BATTERY_HEALTH_COLD); .isEqualTo(BatteryManager.BATTERY_HEALTH_COLD);
} }
@Test @Test
public void convert_nullBatteryEntry_returnsExpectedContentValues() { public void convert_nullBatteryEntry_returnsExpectedContentValues() {
final ContentValues values = final ContentValues values =
ConvertUtils.convert( ConvertUtils.convert(
/*entry=*/ null, /*entry=*/ null,
/*batteryUsageStats=*/ null, /*batteryUsageStats=*/ null,
/*batteryLevel=*/ 12, /*batteryLevel=*/ 12,
/*batteryStatus=*/ BatteryManager.BATTERY_STATUS_FULL, /*batteryStatus=*/ BatteryManager.BATTERY_STATUS_FULL,
/*batteryHealth=*/ BatteryManager.BATTERY_HEALTH_COLD, /*batteryHealth=*/ BatteryManager.BATTERY_HEALTH_COLD,
/*bootTimestamp=*/ 101L, /*bootTimestamp=*/ 101L,
/*timestamp=*/ 10001L); /*timestamp=*/ 10001L);
assertThat(values.getAsLong(BatteryHistEntry.KEY_BOOT_TIMESTAMP)) assertThat(values.getAsLong(BatteryHistEntry.KEY_BOOT_TIMESTAMP))
.isEqualTo(101L); .isEqualTo(101L);
assertThat(values.getAsLong(BatteryHistEntry.KEY_TIMESTAMP)) assertThat(values.getAsLong(BatteryHistEntry.KEY_TIMESTAMP))
.isEqualTo(10001L); .isEqualTo(10001L);
assertThat(values.getAsString(BatteryHistEntry.KEY_ZONE_ID)) assertThat(values.getAsString(BatteryHistEntry.KEY_ZONE_ID))
.isEqualTo(TimeZone.getDefault().getID()); .isEqualTo(TimeZone.getDefault().getID());
assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_LEVEL)).isEqualTo(12); assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_LEVEL)).isEqualTo(12);
assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_STATUS)) assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_STATUS))
.isEqualTo(BatteryManager.BATTERY_STATUS_FULL); .isEqualTo(BatteryManager.BATTERY_STATUS_FULL);
assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_HEALTH)) assertThat(values.getAsInteger(BatteryHistEntry.KEY_BATTERY_HEALTH))
.isEqualTo(BatteryManager.BATTERY_HEALTH_COLD); .isEqualTo(BatteryManager.BATTERY_HEALTH_COLD);
assertThat(values.getAsString(BatteryHistEntry.KEY_PACKAGE_NAME)) assertThat(values.getAsString(BatteryHistEntry.KEY_PACKAGE_NAME))
.isEqualTo(ConvertUtils.FAKE_PACKAGE_NAME); .isEqualTo(ConvertUtils.FAKE_PACKAGE_NAME);
} }
@Test @Test
public void getIndexedUsageMap_nullOrEmptyHistoryMap_returnEmptyCollection() { public void getIndexedUsageMap_nullOrEmptyHistoryMap_returnEmptyCollection() {
final int timeSlotSize = 2; final int timeSlotSize = 2;
final long[] batteryHistoryKeys = new long[] {101L, 102L, 103L, 104L, 105L}; final long[] batteryHistoryKeys = new long[]{101L, 102L, 103L, 104L, 105L};
assertThat(ConvertUtils.getIndexedUsageMap( assertThat(ConvertUtils.getIndexedUsageMap(
mContext, timeSlotSize, batteryHistoryKeys, mContext, timeSlotSize, batteryHistoryKeys,
/*batteryHistoryMap=*/ null, /*purgeLowPercentageAndFakeData=*/ true)) /*batteryHistoryMap=*/ null, /*purgeLowPercentageAndFakeData=*/ true))
.isEmpty(); .isEmpty();
assertThat(ConvertUtils.getIndexedUsageMap( assertThat(ConvertUtils.getIndexedUsageMap(
mContext, timeSlotSize, batteryHistoryKeys, mContext, timeSlotSize, batteryHistoryKeys,
new HashMap<Long, Map<String, BatteryHistEntry>>(), new HashMap<Long, Map<String, BatteryHistEntry>>(),
/*purgeLowPercentageAndFakeData=*/ true)) /*purgeLowPercentageAndFakeData=*/ true))
.isEmpty(); .isEmpty();
} }
@Test @Test
public void getIndexedUsageMap_returnsExpectedResult() { public void getIndexedUsageMap_returnsExpectedResult() {
// Creates the fake testing data. // Creates the fake testing data.
final int timeSlotSize = 2; final int timeSlotSize = 2;
final long[] batteryHistoryKeys = new long[] {101L, 102L, 103L, 104L, 105L}; final long[] batteryHistoryKeys = new long[]{101L, 102L, 103L, 104L, 105L};
final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap = final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap =
new HashMap<>(); new HashMap<>();
final BatteryHistEntry fakeEntry = createBatteryHistEntry( final BatteryHistEntry fakeEntry = createBatteryHistEntry(
ConvertUtils.FAKE_PACKAGE_NAME, "fake_label", 0, 0L, 0L, 0L); ConvertUtils.FAKE_PACKAGE_NAME, "fake_label", 0, 0L, 0L, 0L);
// Adds the index = 0 data. // Adds the index = 0 data.
Map<String, BatteryHistEntry> entryMap = new HashMap<>(); Map<String, BatteryHistEntry> entryMap = new HashMap<>();
BatteryHistEntry entry = createBatteryHistEntry( BatteryHistEntry entry = createBatteryHistEntry(
"package1", "label1", 5.0, 1L, 10L, 20L); "package1", "label1", 5.0, 1L, 10L, 20L);
entryMap.put(entry.getKey(), entry); entryMap.put(entry.getKey(), entry);
entryMap.put(fakeEntry.getKey(), fakeEntry); entryMap.put(fakeEntry.getKey(), fakeEntry);
batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[0]), entryMap); batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[0]), entryMap);
@@ -189,38 +190,38 @@ public final class ConvertUtilsTest {
// Adds the index = 2 data. // Adds the index = 2 data.
entryMap = new HashMap<>(); entryMap = new HashMap<>();
entry = createBatteryHistEntry( entry = createBatteryHistEntry(
"package2", "label2", 10.0, 2L, 15L, 25L); "package2", "label2", 10.0, 2L, 15L, 25L);
entryMap.put(entry.getKey(), entry); entryMap.put(entry.getKey(), entry);
entryMap.put(fakeEntry.getKey(), fakeEntry); entryMap.put(fakeEntry.getKey(), fakeEntry);
batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[2]), entryMap); batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[2]), entryMap);
// Adds the index = 3 data. // Adds the index = 3 data.
entryMap = new HashMap<>(); entryMap = new HashMap<>();
entry = createBatteryHistEntry( entry = createBatteryHistEntry(
"package2", "label2", 15.0, 2L, 25L, 35L); "package2", "label2", 15.0, 2L, 25L, 35L);
entryMap.put(entry.getKey(), entry); entryMap.put(entry.getKey(), entry);
entry = createBatteryHistEntry( entry = createBatteryHistEntry(
"package3", "label3", 5.0, 3L, 5L, 5L); "package3", "label3", 5.0, 3L, 5L, 5L);
entryMap.put(entry.getKey(), entry); entryMap.put(entry.getKey(), entry);
entryMap.put(fakeEntry.getKey(), fakeEntry); entryMap.put(fakeEntry.getKey(), fakeEntry);
batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[3]), entryMap); batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[3]), entryMap);
// Adds the index = 4 data. // Adds the index = 4 data.
entryMap = new HashMap<>(); entryMap = new HashMap<>();
entry = createBatteryHistEntry( entry = createBatteryHistEntry(
"package2", "label2", 30.0, 2L, 30L, 40L); "package2", "label2", 30.0, 2L, 30L, 40L);
entryMap.put(entry.getKey(), entry); entryMap.put(entry.getKey(), entry);
entry = createBatteryHistEntry( entry = createBatteryHistEntry(
"package2", "label2", 75.0, 4L, 40L, 50L); "package2", "label2", 75.0, 4L, 40L, 50L);
entryMap.put(entry.getKey(), entry); entryMap.put(entry.getKey(), entry);
entry = createBatteryHistEntry( entry = createBatteryHistEntry(
"package3", "label3", 5.0, 3L, 5L, 5L); "package3", "label3", 5.0, 3L, 5L, 5L);
entryMap.put(entry.getKey(), entry); entryMap.put(entry.getKey(), entry);
entryMap.put(fakeEntry.getKey(), fakeEntry); entryMap.put(fakeEntry.getKey(), fakeEntry);
batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[4]), entryMap); batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[4]), entryMap);
final Map<Integer, List<BatteryDiffEntry>> resultMap = final Map<Integer, List<BatteryDiffEntry>> resultMap =
ConvertUtils.getIndexedUsageMap( ConvertUtils.getIndexedUsageMap(
mContext, timeSlotSize, batteryHistoryKeys, batteryHistoryMap, mContext, timeSlotSize, batteryHistoryKeys, batteryHistoryMap,
/*purgeLowPercentageAndFakeData=*/ false); /*purgeLowPercentageAndFakeData=*/ false);
assertThat(resultMap).hasSize(3); assertThat(resultMap).hasSize(3);
// Verifies the first timestamp result. // Verifies the first timestamp result.
@@ -243,9 +244,9 @@ public final class ConvertUtilsTest {
// Test getIndexedUsageMap() with purged data. // Test getIndexedUsageMap() with purged data.
ConvertUtils.PERCENTAGE_OF_TOTAL_THRESHOLD = 50; ConvertUtils.PERCENTAGE_OF_TOTAL_THRESHOLD = 50;
final Map<Integer, List<BatteryDiffEntry>> purgedResultMap = final Map<Integer, List<BatteryDiffEntry>> purgedResultMap =
ConvertUtils.getIndexedUsageMap( ConvertUtils.getIndexedUsageMap(
mContext, timeSlotSize, batteryHistoryKeys, batteryHistoryMap, mContext, timeSlotSize, batteryHistoryKeys, batteryHistoryMap,
/*purgeLowPercentageAndFakeData=*/ true); /*purgeLowPercentageAndFakeData=*/ true);
assertThat(purgedResultMap).hasSize(3); assertThat(purgedResultMap).hasSize(3);
// Verifies the first timestamp result. // Verifies the first timestamp result.
@@ -260,7 +261,7 @@ public final class ConvertUtilsTest {
assertThat(entryList).hasSize(1); assertThat(entryList).hasSize(1);
// Verifies the fake data is cleared out. // Verifies the fake data is cleared out.
assertThat(entryList.get(0).getPackageName()) assertThat(entryList.get(0).getPackageName())
.isNotEqualTo(ConvertUtils.FAKE_PACKAGE_NAME); .isNotEqualTo(ConvertUtils.FAKE_PACKAGE_NAME);
// Adds lacked data into the battery history map. // Adds lacked data into the battery history map.
final int remainingSize = 25 - batteryHistoryKeys.length; final int remainingSize = 25 - batteryHistoryKeys.length;
@@ -268,10 +269,10 @@ public final class ConvertUtilsTest {
batteryHistoryMap.put(105L + index + 1, new HashMap<>()); batteryHistoryMap.put(105L + index + 1, new HashMap<>());
} }
when(mPowerUsageFeatureProvider.getBatteryHistory(mContext)) when(mPowerUsageFeatureProvider.getBatteryHistory(mContext))
.thenReturn(batteryHistoryMap); .thenReturn(batteryHistoryMap);
final List<BatteryDiffEntry> batteryDiffEntryList = final List<BatteryDiffEntry> batteryDiffEntryList =
BatteryChartPreferenceController.getBatteryLast24HrUsageData(mContext); BatteryChartPreferenceController.getBatteryLast24HrUsageData(mContext);
assertThat(batteryDiffEntryList).isNotEmpty(); assertThat(batteryDiffEntryList).isNotEmpty();
final BatteryDiffEntry resultEntry = batteryDiffEntryList.get(0); final BatteryDiffEntry resultEntry = batteryDiffEntryList.get(0);
@@ -281,11 +282,11 @@ public final class ConvertUtilsTest {
@Test @Test
public void getIndexedUsageMap_usageTimeExceed_returnsExpectedResult() { public void getIndexedUsageMap_usageTimeExceed_returnsExpectedResult() {
final int timeSlotSize = 1; final int timeSlotSize = 1;
final long[] batteryHistoryKeys = new long[] {101L, 102L, 103L}; final long[] batteryHistoryKeys = new long[]{101L, 102L, 103L};
final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap = final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap =
new HashMap<>(); new HashMap<>();
final BatteryHistEntry fakeEntry = createBatteryHistEntry( final BatteryHistEntry fakeEntry = createBatteryHistEntry(
ConvertUtils.FAKE_PACKAGE_NAME, "fake_label", 0, 0L, 0L, 0L); ConvertUtils.FAKE_PACKAGE_NAME, "fake_label", 0, 0L, 0L, 0L);
// Adds the index = 0 data. // Adds the index = 0 data.
Map<String, BatteryHistEntry> entryMap = new HashMap<>(); Map<String, BatteryHistEntry> entryMap = new HashMap<>();
entryMap.put(fakeEntry.getKey(), fakeEntry); entryMap.put(fakeEntry.getKey(), fakeEntry);
@@ -297,14 +298,14 @@ public final class ConvertUtilsTest {
// Adds the index = 2 data. // Adds the index = 2 data.
entryMap = new HashMap<>(); entryMap = new HashMap<>();
final BatteryHistEntry entry = createBatteryHistEntry( final BatteryHistEntry entry = createBatteryHistEntry(
"package3", "label3", 500, 5L, 3600000L, 7200000L); "package3", "label3", 500, 5L, 3600000L, 7200000L);
entryMap.put(entry.getKey(), entry); entryMap.put(entry.getKey(), entry);
batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[2]), entryMap); batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[2]), entryMap);
final Map<Integer, List<BatteryDiffEntry>> purgedResultMap = final Map<Integer, List<BatteryDiffEntry>> purgedResultMap =
ConvertUtils.getIndexedUsageMap( ConvertUtils.getIndexedUsageMap(
mContext, timeSlotSize, batteryHistoryKeys, batteryHistoryMap, mContext, timeSlotSize, batteryHistoryKeys, batteryHistoryMap,
/*purgeLowPercentageAndFakeData=*/ true); /*purgeLowPercentageAndFakeData=*/ true);
assertThat(purgedResultMap).hasSize(2); assertThat(purgedResultMap).hasSize(2);
final List<BatteryDiffEntry> entryList = purgedResultMap.get(0); final List<BatteryDiffEntry> entryList = purgedResultMap.get(0);
@@ -313,19 +314,19 @@ public final class ConvertUtilsTest {
final float ratio = (float) (7200) / (float) (3600 + 7200); final float ratio = (float) (7200) / (float) (3600 + 7200);
final BatteryDiffEntry resultEntry = entryList.get(0); final BatteryDiffEntry resultEntry = entryList.get(0);
assertThat(resultEntry.mForegroundUsageTimeInMs) assertThat(resultEntry.mForegroundUsageTimeInMs)
.isEqualTo(Math.round(entry.mForegroundUsageTimeInMs * ratio)); .isEqualTo(Math.round(entry.mForegroundUsageTimeInMs * ratio));
assertThat(resultEntry.mBackgroundUsageTimeInMs) assertThat(resultEntry.mBackgroundUsageTimeInMs)
.isEqualTo(Math.round(entry.mBackgroundUsageTimeInMs * ratio)); .isEqualTo(Math.round(entry.mBackgroundUsageTimeInMs * ratio));
assertThat(resultEntry.mConsumePower) assertThat(resultEntry.mConsumePower)
.isEqualTo(entry.mConsumePower * ratio); .isEqualTo(entry.mConsumePower * ratio);
} }
@Test @Test
public void getIndexedUsageMap_hideBackgroundUsageTime_returnsExpectedResult() { public void getIndexedUsageMap_hideBackgroundUsageTime_returnsExpectedResult() {
final long[] batteryHistoryKeys = new long[] {101L, 102L, 103L}; final long[] batteryHistoryKeys = new long[]{101L, 102L, 103L};
final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap = new HashMap<>(); final Map<Long, Map<String, BatteryHistEntry>> batteryHistoryMap = new HashMap<>();
final BatteryHistEntry fakeEntry = createBatteryHistEntry( final BatteryHistEntry fakeEntry = createBatteryHistEntry(
ConvertUtils.FAKE_PACKAGE_NAME, "fake_label", 0, 0L, 0L, 0L); ConvertUtils.FAKE_PACKAGE_NAME, "fake_label", 0, 0L, 0L, 0L);
// Adds the index = 0 data. // Adds the index = 0 data.
Map<String, BatteryHistEntry> entryMap = new HashMap<>(); Map<String, BatteryHistEntry> entryMap = new HashMap<>();
entryMap.put(fakeEntry.getKey(), fakeEntry); entryMap.put(fakeEntry.getKey(), fakeEntry);
@@ -337,16 +338,16 @@ public final class ConvertUtilsTest {
// Adds the index = 2 data. // Adds the index = 2 data.
entryMap = new HashMap<>(); entryMap = new HashMap<>();
final BatteryHistEntry entry = createBatteryHistEntry( final BatteryHistEntry entry = createBatteryHistEntry(
"package3", "label3", 500, 5L, 3600000L, 7200000L); "package3", "label3", 500, 5L, 3600000L, 7200000L);
entryMap.put(entry.getKey(), entry); entryMap.put(entry.getKey(), entry);
batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[2]), entryMap); batteryHistoryMap.put(Long.valueOf(batteryHistoryKeys[2]), entryMap);
when(mPowerUsageFeatureProvider.getHideBackgroundUsageTimeSet(mContext)) when(mPowerUsageFeatureProvider.getHideBackgroundUsageTimeSet(mContext))
.thenReturn(new HashSet(Arrays.asList((CharSequence) "package3"))); .thenReturn(new HashSet(Arrays.asList((CharSequence) "package3")));
final Map<Integer, List<BatteryDiffEntry>> purgedResultMap = final Map<Integer, List<BatteryDiffEntry>> purgedResultMap =
ConvertUtils.getIndexedUsageMap( ConvertUtils.getIndexedUsageMap(
mContext, /*timeSlotSize=*/ 1, batteryHistoryKeys, batteryHistoryMap, mContext, /*timeSlotSize=*/ 1, batteryHistoryKeys, batteryHistoryMap,
/*purgeLowPercentageAndFakeData=*/ true); /*purgeLowPercentageAndFakeData=*/ true);
final BatteryDiffEntry resultEntry = purgedResultMap.get(0).get(0); final BatteryDiffEntry resultEntry = purgedResultMap.get(0).get(0);
assertThat(resultEntry.mBackgroundUsageTimeInMs).isEqualTo(0); assertThat(resultEntry.mBackgroundUsageTimeInMs).isEqualTo(0);
@@ -355,7 +356,7 @@ public final class ConvertUtilsTest {
@Test @Test
public void getLocale_nullContext_returnDefaultLocale() { public void getLocale_nullContext_returnDefaultLocale() {
assertThat(ConvertUtils.getLocale(/*context=*/ null)) assertThat(ConvertUtils.getLocale(/*context=*/ null))
.isEqualTo(Locale.getDefault()); .isEqualTo(Locale.getDefault());
} }
@Test @Test
@@ -379,12 +380,12 @@ public final class ConvertUtilsTest {
values.put(BatteryHistEntry.KEY_APP_LABEL, appLabel); values.put(BatteryHistEntry.KEY_APP_LABEL, appLabel);
values.put(BatteryHistEntry.KEY_UID, Long.valueOf(uid)); values.put(BatteryHistEntry.KEY_UID, Long.valueOf(uid));
values.put(BatteryHistEntry.KEY_CONSUMER_TYPE, values.put(BatteryHistEntry.KEY_CONSUMER_TYPE,
Integer.valueOf(ConvertUtils.CONSUMER_TYPE_UID_BATTERY)); Integer.valueOf(ConvertUtils.CONSUMER_TYPE_UID_BATTERY));
values.put(BatteryHistEntry.KEY_CONSUME_POWER, consumePower); values.put(BatteryHistEntry.KEY_CONSUME_POWER, consumePower);
values.put(BatteryHistEntry.KEY_FOREGROUND_USAGE_TIME, values.put(BatteryHistEntry.KEY_FOREGROUND_USAGE_TIME,
Long.valueOf(foregroundUsageTimeInMs)); Long.valueOf(foregroundUsageTimeInMs));
values.put(BatteryHistEntry.KEY_BACKGROUND_USAGE_TIME, values.put(BatteryHistEntry.KEY_BACKGROUND_USAGE_TIME,
Long.valueOf(backgroundUsageTimeInMs)); Long.valueOf(backgroundUsageTimeInMs));
return new BatteryHistEntry(values); return new BatteryHistEntry(values);
} }

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2021 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -14,14 +14,13 @@
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context; import android.content.Context;
import android.widget.ImageView; import android.widget.ImageView;
@@ -74,7 +73,7 @@ public final class ExpandDividerPreferenceTest {
@Test @Test
public void testOnClick_switchExpandStateAndInvokeCallback() { public void testOnClick_switchExpandStateAndInvokeCallback() {
final boolean[] isExpandedArray = new boolean[] {false}; final boolean[] isExpandedArray = new boolean[]{false};
mExpandDividerPreference.mImageView = mImageView; mExpandDividerPreference.mImageView = mImageView;
mExpandDividerPreference.setOnExpandListener( mExpandDividerPreference.setOnExpandListener(
isExpanded -> isExpandedArray[0] = isExpanded); isExpanded -> isExpandedArray[0] = isExpanded);
@@ -94,7 +93,7 @@ public final class ExpandDividerPreferenceTest {
@Test @Test
public void testSetIsExpanded_updateStateButNotInvokeCallback() { public void testSetIsExpanded_updateStateButNotInvokeCallback() {
final boolean[] isExpandedArray = new boolean[] {false}; final boolean[] isExpandedArray = new boolean[]{false};
mExpandDividerPreference.mImageView = mImageView; mExpandDividerPreference.mImageView = mImageView;
mExpandDividerPreference.setOnExpandListener( mExpandDividerPreference.setOnExpandListener(
isExpanded -> isExpandedArray[0] = isExpanded); isExpanded -> isExpandedArray[0] = isExpanded);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2017 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
@@ -55,7 +55,7 @@ public class PowerGaugePreferenceTest {
mContext = RuntimeEnvironment.application; mContext = RuntimeEnvironment.application;
mRootView = LayoutInflater.from(mContext).inflate(R.layout.preference_app, null); mRootView = LayoutInflater.from(mContext).inflate(R.layout.preference_app, null);
mWidgetView = mWidgetView =
LayoutInflater.from(mContext).inflate(R.layout.preference_widget_summary, null); LayoutInflater.from(mContext).inflate(R.layout.preference_widget_summary, null);
final LinearLayout widgetFrame = mRootView.findViewById(android.R.id.widget_frame); final LinearLayout widgetFrame = mRootView.findViewById(android.R.id.widget_frame);
assertThat(widgetFrame).isNotNull(); assertThat(widgetFrame).isNotNull();
widgetFrame.addView(mWidgetView); widgetFrame.addView(mWidgetView);

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2017 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyInt;

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright (C) 2016 The Android Open Source Project * Copyright (C) 2022 The Android Open Source Project
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -13,11 +13,11 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.fuelgauge; package com.android.settings.fuelgauge.batteryusage;
import static com.android.settings.fuelgauge.PowerUsageSummary.BATTERY_INFO_LOADER; import static com.android.settings.fuelgauge.batteryusage.PowerUsageSummary.BATTERY_INFO_LOADER;
import static com.android.settings.fuelgauge.PowerUsageSummary.KEY_BATTERY_ERROR; import static com.android.settings.fuelgauge.batteryusage.PowerUsageSummary.KEY_BATTERY_ERROR;
import static com.android.settings.fuelgauge.PowerUsageSummary.KEY_BATTERY_USAGE; import static com.android.settings.fuelgauge.batteryusage.PowerUsageSummary.KEY_BATTERY_USAGE;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
@@ -44,6 +44,8 @@ import androidx.preference.PreferenceScreen;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.SettingsActivity; import com.android.settings.SettingsActivity;
import com.android.settings.fuelgauge.BatteryBroadcastReceiver;
import com.android.settings.fuelgauge.BatteryUtils;
import com.android.settings.fuelgauge.batterytip.BatteryTipPreferenceController; import com.android.settings.fuelgauge.batterytip.BatteryTipPreferenceController;
import com.android.settings.testutils.FakeFeatureFactory; import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.XmlTestUtils; import com.android.settings.testutils.XmlTestUtils;
@@ -55,6 +57,7 @@ import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
@@ -74,6 +77,7 @@ public class PowerUsageSummaryTest {
public static void beforeClass() { public static void beforeClass() {
sAdditionalBatteryInfoIntent = new Intent("com.example.app.ADDITIONAL_BATTERY_INFO"); sAdditionalBatteryInfoIntent = new Intent("com.example.app.ADDITIONAL_BATTERY_INFO");
} }
@Mock @Mock
private SettingsActivity mSettingsActivity; private SettingsActivity mSettingsActivity;
@Mock @Mock
@@ -111,7 +115,7 @@ public class PowerUsageSummaryTest {
.thenReturn(sAdditionalBatteryInfoIntent); .thenReturn(sAdditionalBatteryInfoIntent);
when(mFeatureFactory.powerUsageFeatureProvider.isChartGraphEnabled(mRealContext)) when(mFeatureFactory.powerUsageFeatureProvider.isChartGraphEnabled(mRealContext))
.thenReturn(true); .thenReturn(true);
mFragment.mBatteryUtils = spy(new BatteryUtils(mRealContext)); mFragment.mBatteryUtils = Mockito.spy(new BatteryUtils(mRealContext));
ReflectionHelpers.setField(mFragment, "mVisibilityLoggerMixin", mVisibilityLoggerMixin); ReflectionHelpers.setField(mFragment, "mVisibilityLoggerMixin", mVisibilityLoggerMixin);
ReflectionHelpers.setField(mFragment, "mBatteryBroadcastReceiver", ReflectionHelpers.setField(mFragment, "mBatteryBroadcastReceiver",
mBatteryBroadcastReceiver); mBatteryBroadcastReceiver);

View File

@@ -31,13 +31,13 @@ import androidx.slice.SliceProvider;
import androidx.slice.widget.SliceLiveData; import androidx.slice.widget.SliceLiveData;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.fuelgauge.BatteryUsageStatsLoader;
import com.android.settings.fuelgauge.batterytip.AppInfo; import com.android.settings.fuelgauge.batterytip.AppInfo;
import com.android.settings.fuelgauge.batterytip.BatteryTipLoader; import com.android.settings.fuelgauge.batterytip.BatteryTipLoader;
import com.android.settings.fuelgauge.batterytip.tips.BatteryTip; import com.android.settings.fuelgauge.batterytip.tips.BatteryTip;
import com.android.settings.fuelgauge.batterytip.tips.EarlyWarningTip; import com.android.settings.fuelgauge.batterytip.tips.EarlyWarningTip;
import com.android.settings.fuelgauge.batterytip.tips.HighUsageTip; import com.android.settings.fuelgauge.batterytip.tips.HighUsageTip;
import com.android.settings.fuelgauge.batterytip.tips.LowBatteryTip; import com.android.settings.fuelgauge.batterytip.tips.LowBatteryTip;
import com.android.settings.fuelgauge.batteryusage.BatteryUsageStatsLoader;
import com.android.settings.slices.SliceBackgroundWorker; import com.android.settings.slices.SliceBackgroundWorker;
import org.junit.After; import org.junit.After;

View File

@@ -23,8 +23,8 @@ import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.android.settings.backup.UserBackupSettingsActivity; import com.android.settings.backup.UserBackupSettingsActivity;
import com.android.settings.connecteddevice.ConnectedDeviceDashboardFragment; import com.android.settings.connecteddevice.ConnectedDeviceDashboardFragment;
import com.android.settings.connecteddevice.usb.UsbDetailsFragment; import com.android.settings.connecteddevice.usb.UsbDetailsFragment;
import com.android.settings.fuelgauge.PowerUsageAdvanced; import com.android.settings.fuelgauge.batteryusage.PowerUsageAdvanced;
import com.android.settings.fuelgauge.PowerUsageSummary; import com.android.settings.fuelgauge.batteryusage.PowerUsageSummary;
import com.android.settings.gestures.GestureNavigationSettingsFragment; import com.android.settings.gestures.GestureNavigationSettingsFragment;
import com.android.settings.gestures.SystemNavigationGestureSettings; import com.android.settings.gestures.SystemNavigationGestureSettings;
import com.android.settings.location.LocationSettings; import com.android.settings.location.LocationSettings;