Merge "Mock WifiP2pManager.class for WifiP2pSettingsTest"
diff --git a/res/values/strings.xml b/res/values/strings.xml
index c62974a..a2adeaf 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -5831,7 +5831,8 @@
 
     <!-- Fast Pair setting summary in settings screen [CHAR LIMIT=50] -->
     <string name="fast_pair_settings_summary">Nearby detection of Fast Pair bluetooth devices.</string>
-
+    <!-- Title for Fast Pair main switch preferences. [CHAR LIMIT=50] -->
+    <string name="fast_pair_main_switch_title">Scan for nearby devices</string>
     <!-- Printing settings -->
     <skip />
 
diff --git a/res/xml/fast_pair_settings.xml b/res/xml/fast_pair_settings.xml
index ec4cda9..3fd306f 100644
--- a/res/xml/fast_pair_settings.xml
+++ b/res/xml/fast_pair_settings.xml
@@ -21,4 +21,8 @@
     android:title="@string/fast_pair_settings"
     settings:keywords="@string/keywords_fast_pair">
 
-</PreferenceScreen>
\ No newline at end of file
+    <com.android.settingslib.widget.MainSwitchPreference
+        android:key="fast_pair_scan_switch"
+        android:title="@string/fast_pair_main_switch_title" />
+
+</PreferenceScreen>
diff --git a/src/com/android/settings/accessibility/AccessibilityQuickSettingUtils.java b/src/com/android/settings/accessibility/AccessibilityQuickSettingUtils.java
new file mode 100644
index 0000000..013136c
--- /dev/null
+++ b/src/com/android/settings/accessibility/AccessibilityQuickSettingUtils.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2022 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.accessibility;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.text.TextUtils;
+
+import androidx.annotation.NonNull;
+
+import java.util.StringJoiner;
+
+/** Provides utility methods to accessibility quick settings only. */
+final class AccessibilityQuickSettingUtils {
+
+    private static final String ACCESSIBILITY_PERF = "accessibility_prefs";
+    private static final String KEY_TILE_SERVICE_SHOWN = "tile_service_shown";
+    private static final char COMPONENT_NAME_SEPARATOR = ':';
+    private static final TextUtils.SimpleStringSplitter sStringColonSplitter =
+            new TextUtils.SimpleStringSplitter(COMPONENT_NAME_SEPARATOR);
+
+    /**
+     * Opts in component name into {@link AccessibilityQuickSettingUtils#KEY_TILE_SERVICE_SHOWN}
+     * colon-separated string in {@link SharedPreferences}.
+     *
+     * @param context The current context.
+     * @param componentName The component name that need to be opted in SharedPreferences.
+     */
+    public static void optInValueToSharedPreferences(Context context,
+            @NonNull ComponentName componentName) {
+        final String targetString = getFromSharedPreferences(context);
+        if (hasValueInSharedPreferences(targetString, componentName)) {
+            return;
+        }
+
+        final StringJoiner joiner = new StringJoiner(String.valueOf(COMPONENT_NAME_SEPARATOR));
+        if (!TextUtils.isEmpty(targetString)) {
+            joiner.add(targetString);
+        }
+        joiner.add(componentName.flattenToString());
+
+        SharedPreferences.Editor editor = getSharedPreferences(context).edit();
+        editor.putString(KEY_TILE_SERVICE_SHOWN, joiner.toString()).apply();
+    }
+
+    /**
+     * Returns if component name existed in {@link
+     * AccessibilityQuickSettingUtils#KEY_TILE_SERVICE_SHOWN} string in {@link SharedPreferences}.
+     *
+     * @param context The current context.
+     * @param componentName The component name that need to be checked existed in SharedPreferences.
+     * @return {@code true} if componentName existed in SharedPreferences.
+     */
+    public static boolean hasValueInSharedPreferences(Context context,
+            @NonNull ComponentName componentName) {
+        final String targetString = getFromSharedPreferences(context);
+        return hasValueInSharedPreferences(targetString, componentName);
+    }
+
+    private static boolean hasValueInSharedPreferences(String targetString,
+            @NonNull ComponentName componentName) {
+        if (TextUtils.isEmpty(targetString)) {
+            return false;
+        }
+
+        sStringColonSplitter.setString(targetString);
+
+        while (sStringColonSplitter.hasNext()) {
+            final String name = sStringColonSplitter.next();
+            if (TextUtils.equals(componentName.flattenToString(), name)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private static String getFromSharedPreferences(Context context) {
+        return getSharedPreferences(context).getString(KEY_TILE_SERVICE_SHOWN, "");
+    }
+
+    private static SharedPreferences getSharedPreferences(Context context) {
+        return context.getSharedPreferences(ACCESSIBILITY_PERF, Context.MODE_PRIVATE);
+    }
+
+    private AccessibilityQuickSettingUtils(){}
+}
diff --git a/src/com/android/settings/fuelgauge/BatteryBackupHelper.java b/src/com/android/settings/fuelgauge/BatteryBackupHelper.java
index fdbd12a..f5e21dd 100644
--- a/src/com/android/settings/fuelgauge/BatteryBackupHelper.java
+++ b/src/com/android/settings/fuelgauge/BatteryBackupHelper.java
@@ -68,6 +68,9 @@
     static final String KEY_OPTIMIZATION_LIST = "optimization_mode_list";
 
     @VisibleForTesting
+    List<ApplicationInfo> mTestApplicationInfoList = null;
+
+    @VisibleForTesting
     PowerAllowlistBackend mPowerAllowlistBackend;
     @VisibleForTesting
     IDeviceIdleController mIDeviceIdleController;
@@ -267,6 +270,9 @@
     }
 
     private List<ApplicationInfo> getInstalledApplications() {
+        if (mTestApplicationInfoList != null) {
+            return mTestApplicationInfoList;
+        }
         final List<ApplicationInfo> applications = new ArrayList<>();
         final UserManager um = mContext.getSystemService(UserManager.class);
         for (UserInfo userInfo : um.getProfiles(UserHandle.myUserId())) {
diff --git a/src/com/android/settings/nearby/FastPairSettingsFragment.java b/src/com/android/settings/nearby/FastPairSettingsFragment.java
index 094725b..7657bc3 100644
--- a/src/com/android/settings/nearby/FastPairSettingsFragment.java
+++ b/src/com/android/settings/nearby/FastPairSettingsFragment.java
@@ -17,11 +17,16 @@
 package com.android.settings.nearby;
 
 import android.app.settings.SettingsEnums;
+import android.os.Bundle;
+import android.provider.Settings;
 
 import com.android.settings.R;
 import com.android.settings.SettingsPreferenceFragment;
 import com.android.settings.search.BaseSearchIndexProvider;
 import com.android.settingslib.search.SearchIndexable;
+import com.android.settingslib.widget.MainSwitchPreference;
+
+import java.util.Objects;
 
 /**
  * Fragment with the top level fast pair settings.
@@ -29,6 +34,21 @@
 @SearchIndexable(forTarget = SearchIndexable.ALL & ~SearchIndexable.ARC)
 public class FastPairSettingsFragment extends SettingsPreferenceFragment {
 
+    private static final String SCAN_SWITCH_KEY = "fast_pair_scan_switch";
+
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+
+        MainSwitchPreference mainSwitchPreference = Objects.requireNonNull(
+                findPreference(SCAN_SWITCH_KEY));
+        mainSwitchPreference.addOnSwitchChangeListener(
+                (switchView, isChecked) ->
+                        Settings.Secure.putInt(getContentResolver(),
+                                Settings.Secure.FAST_PAIR_SCAN_ENABLED, isChecked ? 1 : 0));
+        mainSwitchPreference.setChecked(isFastPairScanAvailable());
+    }
+
     @Override
     public int getMetricsCategory() {
         return SettingsEnums.CONNECTION_DEVICE_ADVANCED_FAST_PAIR;
@@ -47,4 +67,8 @@
     public static final BaseSearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
             new BaseSearchIndexProvider(R.xml.fast_pair_settings);
 
+    private boolean isFastPairScanAvailable() {
+        return Settings.Secure.getInt(getContentResolver(),
+                Settings.Secure.FAST_PAIR_SCAN_ENABLED, 1) != 0;
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/accessibility/AccessibilityQuickSettingUtilsTest.java b/tests/robotests/src/com/android/settings/accessibility/AccessibilityQuickSettingUtilsTest.java
new file mode 100644
index 0000000..a9bbade
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/accessibility/AccessibilityQuickSettingUtilsTest.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2022 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.accessibility;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.ComponentName;
+import android.content.Context;
+
+import androidx.test.core.app.ApplicationProvider;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RobolectricTestRunner;
+
+/** Tests for {@link AccessibilityQuickSettingUtils}. */
+@RunWith(RobolectricTestRunner.class)
+public final class AccessibilityQuickSettingUtilsTest {
+    private static final String DUMMY_PACKAGE_NAME = "com.mock.example";
+    private static final String DUMMY_CLASS_NAME = DUMMY_PACKAGE_NAME + ".mock_a11y_service";
+    private static final String DUMMY_CLASS_NAME2 = DUMMY_PACKAGE_NAME + ".mock_a11y_service2";
+    private static final ComponentName DUMMY_COMPONENT_NAME = new ComponentName(DUMMY_PACKAGE_NAME,
+            DUMMY_CLASS_NAME);
+    private static final ComponentName DUMMY_COMPONENT_NAME2 = new ComponentName(DUMMY_PACKAGE_NAME,
+            DUMMY_CLASS_NAME2);
+    private final Context mContext = ApplicationProvider.getApplicationContext();
+
+    @Test
+    public void optInValueToSharedPreferences_optInValue_haveMatchString() {
+        AccessibilityQuickSettingUtils.optInValueToSharedPreferences(mContext,
+                DUMMY_COMPONENT_NAME);
+
+        assertThat(AccessibilityQuickSettingUtils.hasValueInSharedPreferences(mContext,
+                DUMMY_COMPONENT_NAME)).isTrue();
+    }
+
+    @Test
+    public void optInValueToSharedPreferences_optInTwoValues_haveMatchString() {
+        AccessibilityQuickSettingUtils.optInValueToSharedPreferences(mContext,
+                DUMMY_COMPONENT_NAME);
+        AccessibilityQuickSettingUtils.optInValueToSharedPreferences(mContext,
+                DUMMY_COMPONENT_NAME2);
+
+        assertThat(AccessibilityQuickSettingUtils.hasValueInSharedPreferences(mContext,
+                DUMMY_COMPONENT_NAME)).isTrue();
+        assertThat(AccessibilityQuickSettingUtils.hasValueInSharedPreferences(mContext,
+                DUMMY_COMPONENT_NAME2)).isTrue();
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/BatteryBackupHelperTest.java b/tests/robotests/src/com/android/settings/fuelgauge/BatteryBackupHelperTest.java
index 3424f8d..ca1797a 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/BatteryBackupHelperTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/BatteryBackupHelperTest.java
@@ -53,7 +53,6 @@
 
 import org.junit.After;
 import org.junit.Before;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
@@ -202,7 +201,6 @@
     }
 
     @Test
-    @Ignore
     public void backupOptimizationMode_backupOptimizationMode() throws Exception {
         final List<String> allowlistedApps = Arrays.asList(PACKAGE_NAME1);
         createTestingData(PACKAGE_NAME1, PACKAGE_NAME2, PACKAGE_NAME3);
@@ -215,7 +213,6 @@
     }
 
     @Test
-    @Ignore
     public void backupOptimizationMode_backupOptimizationModeAndIgnoreSystemApp()
             throws Exception {
         final List<String> allowlistedApps = Arrays.asList(PACKAGE_NAME1);
@@ -232,7 +229,6 @@
     }
 
     @Test
-    @Ignore
     public void backupOptimizationMode_backupOptimizationModeAndIgnoreDefaultApp()
             throws Exception {
         final List<String> allowlistedApps = Arrays.asList(PACKAGE_NAME1);
@@ -387,6 +383,8 @@
                         AppOpsManager.OP_RUN_ANY_IN_BACKGROUND,
                         applicationInfo2.uid,
                         applicationInfo2.packageName);
+        mBatteryBackupHelper.mTestApplicationInfoList =
+                Arrays.asList(applicationInfo1, applicationInfo2, applicationInfo3);
     }
 
     @Implements(UserHandle.class)
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/BatteryDatabaseManagerTest.java b/tests/robotests/src/com/android/settings/fuelgauge/BatteryDatabaseManagerTest.java
deleted file mode 100644
index 2ddd383..0000000
--- a/tests/robotests/src/com/android/settings/fuelgauge/BatteryDatabaseManagerTest.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * Copyright (C) 2018 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 static com.google.common.truth.Truth.assertThat;
-
-import static org.mockito.Mockito.spy;
-
-import android.content.Context;
-import android.text.format.DateUtils;
-import android.util.SparseLongArray;
-
-import com.android.settings.fuelgauge.batterytip.AnomalyDatabaseHelper;
-import com.android.settings.fuelgauge.batterytip.AppInfo;
-import com.android.settings.fuelgauge.batterytip.BatteryDatabaseManager;
-import com.android.settings.testutils.DatabaseTestUtils;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.MockitoAnnotations;
-import org.robolectric.RobolectricTestRunner;
-import org.robolectric.RuntimeEnvironment;
-
-import java.util.ArrayList;
-import java.util.List;
-
-@RunWith(RobolectricTestRunner.class)
-@Ignore
-public class BatteryDatabaseManagerTest {
-    private static String PACKAGE_NAME_NEW = "com.android.app1";
-    private static int UID_NEW = 345;
-    private static int TYPE_NEW = 1;
-    private static String PACKAGE_NAME_OLD = "com.android.app2";
-    private static int UID_OLD = 543;
-    private static int TYPE_OLD = 2;
-    private static long NOW = System.currentTimeMillis();
-    private static long ONE_DAY_BEFORE = NOW - DateUtils.DAY_IN_MILLIS;
-    private static long TWO_DAYS_BEFORE = NOW - 2 * DateUtils.DAY_IN_MILLIS;
-
-    private Context mContext;
-    private BatteryDatabaseManager mBatteryDatabaseManager;
-    private AppInfo mNewAppInfo;
-    private AppInfo mOldAppInfo;
-    private AppInfo mCombinedAppInfo;
-
-    @Before
-    public void setUp() {
-        MockitoAnnotations.initMocks(this);
-
-        mContext = RuntimeEnvironment.application;
-        mBatteryDatabaseManager = spy(BatteryDatabaseManager.getInstance(mContext));
-
-        mNewAppInfo = new AppInfo.Builder()
-                .setUid(UID_NEW)
-                .setPackageName(PACKAGE_NAME_NEW)
-                .addAnomalyType(TYPE_NEW)
-                .build();
-        mOldAppInfo = new AppInfo.Builder()
-                .setUid(UID_OLD)
-                .setPackageName(PACKAGE_NAME_OLD)
-                .addAnomalyType(TYPE_OLD)
-                .build();
-        mCombinedAppInfo = new AppInfo.Builder()
-                .setUid(UID_NEW)
-                .setPackageName(PACKAGE_NAME_NEW)
-                .addAnomalyType(TYPE_NEW)
-                .addAnomalyType(TYPE_OLD)
-                .build();
-    }
-
-    @After
-    public void cleanUp() {
-        DatabaseTestUtils.clearDb(mContext);
-    }
-
-    @Test
-    public void allAnomalyFunctions() {
-        mBatteryDatabaseManager.insertAnomaly(UID_NEW, PACKAGE_NAME_NEW, TYPE_NEW,
-                AnomalyDatabaseHelper.State.NEW, NOW);
-        mBatteryDatabaseManager.insertAnomaly(UID_OLD, PACKAGE_NAME_OLD, TYPE_OLD,
-                AnomalyDatabaseHelper.State.NEW, TWO_DAYS_BEFORE);
-
-        // In database, it contains two record
-        List<AppInfo> totalAppInfos = mBatteryDatabaseManager.queryAllAnomalies(0 /* timeMsAfter */,
-                AnomalyDatabaseHelper.State.NEW);
-        assertThat(totalAppInfos).containsExactly(mNewAppInfo, mOldAppInfo);
-
-        // Only one record shows up if we query by timestamp
-        List<AppInfo> appInfos = mBatteryDatabaseManager.queryAllAnomalies(ONE_DAY_BEFORE,
-                AnomalyDatabaseHelper.State.NEW);
-        assertThat(appInfos).containsExactly(mNewAppInfo);
-
-        mBatteryDatabaseManager.deleteAllAnomaliesBeforeTimeStamp(ONE_DAY_BEFORE);
-
-        // The obsolete record is removed from database
-        List<AppInfo> appInfos1 = mBatteryDatabaseManager.queryAllAnomalies(0 /* timeMsAfter */,
-                AnomalyDatabaseHelper.State.NEW);
-        assertThat(appInfos1).containsExactly(mNewAppInfo);
-    }
-
-    @Test
-    public void updateAnomalies_updateSuccessfully() {
-        mBatteryDatabaseManager.insertAnomaly(UID_NEW, PACKAGE_NAME_NEW, TYPE_NEW,
-                AnomalyDatabaseHelper.State.NEW, NOW);
-        mBatteryDatabaseManager.insertAnomaly(UID_OLD, PACKAGE_NAME_OLD, TYPE_OLD,
-                AnomalyDatabaseHelper.State.NEW, NOW);
-        final AppInfo appInfo = new AppInfo.Builder().setPackageName(PACKAGE_NAME_OLD).build();
-        final List<AppInfo> updateAppInfos = new ArrayList<>();
-        updateAppInfos.add(appInfo);
-
-        // Change state of PACKAGE_NAME_OLD to handled
-        mBatteryDatabaseManager.updateAnomalies(updateAppInfos,
-                AnomalyDatabaseHelper.State.HANDLED);
-
-        // The state of PACKAGE_NAME_NEW is still new
-        List<AppInfo> newAppInfos = mBatteryDatabaseManager.queryAllAnomalies(ONE_DAY_BEFORE,
-                AnomalyDatabaseHelper.State.NEW);
-        assertThat(newAppInfos).containsExactly(mNewAppInfo);
-
-        // The state of PACKAGE_NAME_OLD is changed to handled
-        List<AppInfo> handledAppInfos = mBatteryDatabaseManager.queryAllAnomalies(ONE_DAY_BEFORE,
-                AnomalyDatabaseHelper.State.HANDLED);
-        assertThat(handledAppInfos).containsExactly(mOldAppInfo);
-    }
-
-    @Test
-    public void queryAnomalies_removeDuplicateByUid() {
-        mBatteryDatabaseManager.insertAnomaly(UID_NEW, PACKAGE_NAME_NEW, TYPE_NEW,
-                AnomalyDatabaseHelper.State.NEW, NOW);
-        mBatteryDatabaseManager.insertAnomaly(UID_NEW, PACKAGE_NAME_NEW, TYPE_OLD,
-                AnomalyDatabaseHelper.State.NEW, NOW);
-
-        // Only contain one AppInfo with multiple types
-        List<AppInfo> newAppInfos = mBatteryDatabaseManager.queryAllAnomalies(ONE_DAY_BEFORE,
-                AnomalyDatabaseHelper.State.NEW);
-        assertThat(newAppInfos).containsExactly(mCombinedAppInfo);
-    }
-
-    @Test
-    public void allActionFunctions() {
-        final long timestamp = System.currentTimeMillis();
-        mBatteryDatabaseManager.insertAction(AnomalyDatabaseHelper.ActionType.RESTRICTION, UID_OLD,
-                PACKAGE_NAME_OLD, 0);
-        mBatteryDatabaseManager.insertAction(AnomalyDatabaseHelper.ActionType.RESTRICTION, UID_OLD,
-                PACKAGE_NAME_OLD, 1);
-        mBatteryDatabaseManager.insertAction(AnomalyDatabaseHelper.ActionType.RESTRICTION, UID_NEW,
-                PACKAGE_NAME_NEW, timestamp);
-
-        final SparseLongArray timeArray = mBatteryDatabaseManager.queryActionTime(
-                AnomalyDatabaseHelper.ActionType.RESTRICTION);
-        assertThat(timeArray.size()).isEqualTo(2);
-        assertThat(timeArray.get(UID_OLD)).isEqualTo(1);
-        assertThat(timeArray.get(UID_NEW)).isEqualTo(timestamp);
-
-        mBatteryDatabaseManager.deleteAction(AnomalyDatabaseHelper.ActionType.RESTRICTION, UID_NEW,
-                PACKAGE_NAME_NEW);
-        final SparseLongArray recentTimeArray = mBatteryDatabaseManager.queryActionTime(
-                AnomalyDatabaseHelper.ActionType.RESTRICTION);
-        assertThat(recentTimeArray.size()).isEqualTo(1);
-        assertThat(timeArray.get(UID_OLD)).isEqualTo(1);
-    }
-}