Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit a868c602 authored by Treehugger Robot's avatar Treehugger Robot Committed by Android (Google) Code Review
Browse files

Merge "Redesign the update logic of Allow Background Usage Page." into main

parents 0dbc16d2 1732fa8d
Loading
Loading
Loading
Loading
+19 −16
Original line number Diff line number Diff line
@@ -25,22 +25,25 @@
        android:layout="@layout/settings_entity_header"
        android:selectable="false"/>

    <PreferenceCategory
        android:key="battery_optimization_mode_category"
        android:layout="@layout/settingslib_preference_category_no_title"
        settings:controller="com.android.settings.fuelgauge.BatteryOptimizationModePreferenceController">

        <com.android.settingslib.widget.MainSwitchPreference
        android:key="allow_background_usage"
        android:title="@string/manager_battery_usage_allow_background_usage_title"
        settings:controller="com.android.settings.fuelgauge.AllowBackgroundPreferenceController"/>
            android:key="background_usage_allowability_switch"
            android:title="@string/manager_battery_usage_allow_background_usage_title"/>

        <com.android.settingslib.widget.SelectorWithWidgetPreference
            android:key="optimized_preference"
            android:title="@string/manager_battery_usage_optimized_title"
        android:summary="@string/manager_battery_usage_optimized_summary"
        settings:controller="com.android.settings.fuelgauge.OptimizedPreferenceController"/>
            android:summary="@string/manager_battery_usage_optimized_summary"/>

        <com.android.settingslib.widget.SelectorWithWidgetPreference
            android:key="unrestricted_preference"
            android:title="@string/manager_battery_usage_unrestricted_title"
        android:summary="@string/manager_battery_usage_unrestricted_summary"
        settings:controller="com.android.settings.fuelgauge.UnrestrictedPreferenceController"/>
            android:summary="@string/manager_battery_usage_unrestricted_summary"/>
    </PreferenceCategory>

    <com.android.settingslib.widget.FooterPreference
        android:key="app_usage_footer_preference"
+4 −4
Original line number Diff line number Diff line
@@ -48,12 +48,12 @@

    <PreferenceCategory
        android:title="@string/manager_battery_usage_category_title"
        android:key="manage_battery_usage_category">
        android:key="background_usage_allowability_category"
        settings:controller="com.android.settings.fuelgauge.BackgroundUsageAllowabilityPreferenceController">

        <com.android.settingslib.PrimarySwitchPreference
            android:key="allow_background_usage"
            android:title="@string/manager_battery_usage_allow_background_usage_title"
            settings:controller="com.android.settings.fuelgauge.AllowBackgroundPreferenceController"/>
            android:key="background_usage_allowability_switch"
            android:title="@string/manager_battery_usage_allow_background_usage_title"/>

    </PreferenceCategory>

+15 −89
Original line number Diff line number Diff line
@@ -26,13 +26,10 @@ import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.UserHandle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import androidx.preference.Preference;

import com.android.settings.R;
import com.android.settings.SettingsActivity;
@@ -48,7 +45,6 @@ import com.android.settings.fuelgauge.batteryusage.BatteryDiffEntry;
import com.android.settings.fuelgauge.batteryusage.BatteryEntry;
import com.android.settings.overlay.FeatureFactory;
import com.android.settings.widget.EntityHeaderController;
import com.android.settingslib.PrimarySwitchPreference;
import com.android.settingslib.applications.AppUtils;
import com.android.settingslib.applications.ApplicationsState;
import com.android.settingslib.core.AbstractPreferenceController;
@@ -67,9 +63,7 @@ import java.util.concurrent.Executors;
 * 2. Battery related controls for app(i.e uninstall, force stop)
 */
public class AdvancedPowerUsageDetail extends DashboardFragment
        implements ButtonActionDialogFragment.AppButtonsDialogListener,
                Preference.OnPreferenceClickListener,
                Preference.OnPreferenceChangeListener {
        implements ButtonActionDialogFragment.AppButtonsDialogListener {
    public static final String TAG = "AdvancedPowerDetail";
    public static final String EXTRA_UID = "extra_uid";
    public static final String EXTRA_PACKAGE_NAME = "extra_package_name";
@@ -86,7 +80,8 @@ public class AdvancedPowerUsageDetail extends DashboardFragment
    public static final String EXTRA_POWER_USAGE_AMOUNT = "extra_power_usage_amount";

    private static final String KEY_PREF_HEADER = "header_view";
    private static final String KEY_ALLOW_BACKGROUND_USAGE = "allow_background_usage";
    private static final String KEY_BACKGROUND_USAGE_ALLOWABILITY_CATEGORY =
            "background_usage_allowability_category";

    private static final int REQUEST_UNINSTALL = 0;
    private static final int REQUEST_REMOVE_DEVICE_ADMIN = 1;
@@ -96,11 +91,9 @@ public class AdvancedPowerUsageDetail extends DashboardFragment
    private AppButtonsPreferenceController mAppButtonsPreferenceController;
    private PowerUsageTimeController mPowerUsageTimeController;

    @VisibleForTesting LayoutPreference mHeaderPreference;
    @VisibleForTesting ApplicationsState mState;
    @VisibleForTesting ApplicationsState.AppEntry mAppEntry;
    @VisibleForTesting BatteryOptimizeUtils mBatteryOptimizeUtils;
    @VisibleForTesting PrimarySwitchPreference mAllowBackgroundUsagePreference;

    @VisibleForTesting @BatteryOptimizeUtils.OptimizationMode
    int mOptimizationMode = BatteryOptimizeUtils.MODE_UNKNOWN;
@@ -242,17 +235,11 @@ public class AdvancedPowerUsageDetail extends DashboardFragment
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        final Bundle bundle = getArguments();
        final int uid = bundle.getInt(EXTRA_UID, 0);
        final String packageName = bundle.getString(EXTRA_PACKAGE_NAME);
        mBatteryOptimizeUtils = new BatteryOptimizeUtils(getContext(), uid, packageName);
        mState = ApplicationsState.getInstance(getActivity().getApplication());
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        final String packageName = getArguments().getString(EXTRA_PACKAGE_NAME);
        onCreateBackgroundUsageState(packageName);
        mHeaderPreference = findPreference(KEY_PREF_HEADER);

        if (packageName != null) {
            mAppEntry = mState.getEntry(packageName, UserHandle.myUserId());
        }
@@ -264,7 +251,6 @@ public class AdvancedPowerUsageDetail extends DashboardFragment

        initHeader();
        mOptimizationMode = mBatteryOptimizeUtils.getAppOptimizationMode();
        initFooter();
        mLogStringBuilder = new StringBuilder("onResume mode = ").append(mOptimizationMode);
    }

@@ -299,7 +285,8 @@ public class AdvancedPowerUsageDetail extends DashboardFragment

    @VisibleForTesting
    void initHeader() {
        final View appSnippet = mHeaderPreference.findViewById(R.id.entity_header);
        final LayoutPreference headerPreference = findPreference(KEY_PREF_HEADER);
        final View appSnippet = headerPreference.findViewById(R.id.entity_header);
        final Activity context = getActivity();
        final Bundle bundle = getArguments();
        EntityHeaderController controller =
@@ -340,31 +327,6 @@ public class AdvancedPowerUsageDetail extends DashboardFragment
        controller.done(true /* rebindActions */);
    }

    @VisibleForTesting
    void initFooter() {
        final String stateString;
        final String detailInfoString;
        final Context context = getContext();

        if (mBatteryOptimizeUtils.isDisabledForOptimizeModeOnly()) {
            // Present optimized only string when the package name is invalid.
            stateString = context.getString(R.string.manager_battery_usage_optimized_only);
            detailInfoString =
                    context.getString(R.string.manager_battery_usage_footer_limited, stateString);
        } else if (mBatteryOptimizeUtils.isSystemOrDefaultApp()) {
            // Present unrestricted only string when the package is system or default active app.
            stateString = context.getString(R.string.manager_battery_usage_unrestricted_only);
            detailInfoString =
                    context.getString(R.string.manager_battery_usage_footer_limited, stateString);
        } else {
            // Present default string to normal app.
            detailInfoString =
                    context.getString(
                            R.string.manager_battery_usage_allow_background_usage_summary);
        }
        mAllowBackgroundUsagePreference.setSummary(detailInfoString);
    }

    @Override
    public int getMetricsCategory() {
        return SettingsEnums.FUELGAUGE_POWER_USAGE_DETAIL;
@@ -384,7 +346,6 @@ public class AdvancedPowerUsageDetail extends DashboardFragment
    protected List<AbstractPreferenceController> createPreferenceControllers(Context context) {
        final List<AbstractPreferenceController> controllers = new ArrayList<>();
        final Bundle bundle = getArguments();
        final int uid = bundle.getInt(EXTRA_UID, 0);
        final String packageName = bundle.getString(EXTRA_PACKAGE_NAME);

        mAppButtonsPreferenceController =
@@ -401,7 +362,12 @@ public class AdvancedPowerUsageDetail extends DashboardFragment
            controllers.add(mPowerUsageTimeController);
        }
        controllers.add(mAppButtonsPreferenceController);
        controllers.add(new AllowBackgroundPreferenceController(context, uid, packageName));
        controllers.add(
                new BackgroundUsageAllowabilityPreferenceController(
                        context,
                        /* dashboardFragment= */ this,
                        KEY_BACKGROUND_USAGE_ALLOWABILITY_CATEGORY,
                        mBatteryOptimizeUtils));

        return controllers;
    }
@@ -421,34 +387,6 @@ public class AdvancedPowerUsageDetail extends DashboardFragment
        }
    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        if (!(preference instanceof PrimarySwitchPreference)
                || !TextUtils.equals(preference.getKey(), KEY_ALLOW_BACKGROUND_USAGE)) {
            return false;
        }
        PowerBackgroundUsageDetail.startPowerBackgroundUsageDetailPage(
                getContext(), getArguments());
        return true;
    }

    @Override
    public boolean onPreferenceChange(@NonNull Preference preference, Object newValue) {
        if (!(preference instanceof PrimarySwitchPreference)
                || !TextUtils.equals(preference.getKey(), KEY_ALLOW_BACKGROUND_USAGE)) {
            return false;
        }
        if (newValue instanceof Boolean) {
            final boolean isAllowBackgroundUsage = (boolean) newValue;
            mBatteryOptimizeUtils.setAppUsageState(
                    isAllowBackgroundUsage
                            ? BatteryOptimizeUtils.MODE_OPTIMIZED
                            : BatteryOptimizeUtils.MODE_RESTRICTED,
                    Action.APPLY);
        }
        return true;
    }

    private void logMetricCategory(int currentOptimizeMode) {
        if (currentOptimizeMode == mOptimizationMode) {
            return;
@@ -482,16 +420,4 @@ public class AdvancedPowerUsageDetail extends DashboardFragment
                                    getArguments().getInt(EXTRA_POWER_USAGE_AMOUNT));
                });
    }

    private void onCreateBackgroundUsageState(String packageName) {
        mAllowBackgroundUsagePreference = findPreference(KEY_ALLOW_BACKGROUND_USAGE);
        if (mAllowBackgroundUsagePreference != null) {
            mAllowBackgroundUsagePreference.setOnPreferenceClickListener(this);
            mAllowBackgroundUsagePreference.setOnPreferenceChangeListener(this);
        }

        mBatteryOptimizeUtils =
                new BatteryOptimizeUtils(
                        getContext(), getArguments().getInt(EXTRA_UID), packageName);
    }
}
+0 −85
Original line number Diff line number Diff line
/*
 * Copyright (C) 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings.fuelgauge;

import android.content.Context;

import androidx.annotation.VisibleForTesting;
import androidx.preference.Preference;

import com.android.settings.core.PreferenceControllerMixin;
import com.android.settingslib.PrimarySwitchPreference;
import com.android.settingslib.core.AbstractPreferenceController;
import com.android.settingslib.widget.MainSwitchPreference;

/** Controller to update the app background usage state */
public class AllowBackgroundPreferenceController extends AbstractPreferenceController
        implements PreferenceControllerMixin {

    private static final String TAG = "AllowBackgroundPreferenceController";

    @VisibleForTesting static final String KEY_ALLOW_BACKGROUND_USAGE = "allow_background_usage";

    @VisibleForTesting BatteryOptimizeUtils mBatteryOptimizeUtils;

    public AllowBackgroundPreferenceController(Context context, int uid, String packageName) {
        super(context);
        mBatteryOptimizeUtils = new BatteryOptimizeUtils(context, uid, packageName);
    }

    private void setChecked(Preference preference, boolean checked) {
        if (preference instanceof PrimarySwitchPreference) {
            ((PrimarySwitchPreference) preference).setChecked(checked);
        } else if (preference instanceof MainSwitchPreference) {
            ((MainSwitchPreference) preference).setChecked(checked);
        }
    }

    private void setEnabled(Preference preference, boolean enabled) {
        if (preference instanceof PrimarySwitchPreference) {
            ((PrimarySwitchPreference) preference).setEnabled(enabled);
            ((PrimarySwitchPreference) preference).setSwitchEnabled(enabled);
        } else if (preference instanceof MainSwitchPreference) {
            ((MainSwitchPreference) preference).setEnabled(enabled);
        }
    }

    @Override
    public void updateState(Preference preference) {
        setEnabled(preference, mBatteryOptimizeUtils.isOptimizeModeMutable());

        final boolean isAllowBackground =
                mBatteryOptimizeUtils.getAppOptimizationMode()
                        != BatteryOptimizeUtils.MODE_RESTRICTED;
        setChecked(preference, isAllowBackground);
    }

    @Override
    public boolean isAvailable() {
        return true;
    }

    @Override
    public String getPreferenceKey() {
        return KEY_ALLOW_BACKGROUND_USAGE;
    }

    @Override
    public boolean handlePreferenceTreeClick(Preference preference) {
        return getPreferenceKey().equals(preference.getKey());
    }
}
+140 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2024 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings.fuelgauge;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;

import com.android.settings.R;
import com.android.settings.core.BasePreferenceController;
import com.android.settings.core.PreferenceControllerMixin;
import com.android.settings.dashboard.DashboardFragment;
import com.android.settingslib.PrimarySwitchPreference;

/** Controller to update the manage battery usage preference in App Battery Usage page */
public class BackgroundUsageAllowabilityPreferenceController extends BasePreferenceController
        implements PreferenceControllerMixin {

    @VisibleForTesting
    static final String KEY_BACKGROUND_USAGE_ALLOWABILITY_SWITCH =
            "background_usage_allowability_switch";

    private final BatteryOptimizeUtils mBatteryOptimizeUtils;
    private final DashboardFragment mDashboardFragment;
    @Nullable @VisibleForTesting PrimarySwitchPreference mBackgroundUsageAllowabilityPreference;

    public BackgroundUsageAllowabilityPreferenceController(
            @NonNull Context context,
            @NonNull DashboardFragment dashboardFragment,
            @NonNull String preferenceKey,
            @NonNull BatteryOptimizeUtils batteryOptimizeUtils) {
        super(context, preferenceKey);
        mDashboardFragment = dashboardFragment;
        mBatteryOptimizeUtils = batteryOptimizeUtils;
    }

    @Override
    public int getAvailabilityStatus() {
        return AVAILABLE;
    }

    @Override
    public void updateState(@NonNull Preference preference) {
        updatePreferences(mBatteryOptimizeUtils.getAppOptimizationMode());
    }

    @Override
    public void displayPreference(@NonNull PreferenceScreen screen) {
        super.displayPreference(screen);
        mBackgroundUsageAllowabilityPreference =
                screen.findPreference(KEY_BACKGROUND_USAGE_ALLOWABILITY_SWITCH);
        initPreferences();
    }

    @VisibleForTesting
    void initPreferences() {
        if (mBackgroundUsageAllowabilityPreference == null) {
            return;
        }
        final String stateString;
        final String detailInfoString;
        boolean isPreferenceEnabled = true;
        if (mBatteryOptimizeUtils.isDisabledForOptimizeModeOnly()) {
            // Present "Optimized" only string if the package name is invalid.
            stateString = mContext.getString(R.string.manager_battery_usage_optimized_only);
            detailInfoString =
                    mContext.getString(R.string.manager_battery_usage_footer_limited, stateString);
            isPreferenceEnabled = false;
        } else if (mBatteryOptimizeUtils.isSystemOrDefaultApp()) {
            // Present "Unrestricted" only string if the package is system important apps.
            stateString = mContext.getString(R.string.manager_battery_usage_unrestricted_only);
            detailInfoString =
                    mContext.getString(R.string.manager_battery_usage_footer_limited, stateString);
            isPreferenceEnabled = false;
        } else {
            // Present default string to normal app.
            detailInfoString =
                    mContext.getString(
                            R.string.manager_battery_usage_allow_background_usage_summary);
        }
        mBackgroundUsageAllowabilityPreference.setEnabled(isPreferenceEnabled);
        mBackgroundUsageAllowabilityPreference.setSwitchEnabled(isPreferenceEnabled);
        mBackgroundUsageAllowabilityPreference.setSummary(detailInfoString);
        if (isPreferenceEnabled) {
            mBackgroundUsageAllowabilityPreference.setOnPreferenceClickListener(
                    preference -> {
                        PowerBackgroundUsageDetail.startPowerBackgroundUsageDetailPage(
                                mContext, mDashboardFragment.getArguments());
                        return true;
                    });
            mBackgroundUsageAllowabilityPreference.setOnPreferenceChangeListener(
                    (preference, isAllowBackground) -> {
                        handleBatteryOptimizeModeUpdated(
                                (boolean) isAllowBackground
                                        ? BatteryOptimizeUtils.MODE_OPTIMIZED
                                        : BatteryOptimizeUtils.MODE_RESTRICTED);
                        return true;
                    });
        }
    }

    @VisibleForTesting
    void handleBatteryOptimizeModeUpdated(int newBatteryOptimizeMode) {
        if (mBatteryOptimizeUtils.getAppOptimizationMode() == newBatteryOptimizeMode) {
            Log.w(TAG, "ignore same mode for: " + mBatteryOptimizeUtils.getPackageName());
            return;
        }
        mBatteryOptimizeUtils.setAppUsageState(
                newBatteryOptimizeMode, BatteryOptimizeHistoricalLogEntry.Action.APPLY);
        updatePreferences(newBatteryOptimizeMode);
    }

    @VisibleForTesting
    void updatePreferences(int optimizationMode) {
        if (mBackgroundUsageAllowabilityPreference == null) {
            return;
        }
        mBackgroundUsageAllowabilityPreference.setChecked(
                optimizationMode != BatteryOptimizeUtils.MODE_RESTRICTED);
    }
}
Loading