Merge "Prevent crash when rotating screen in Settings Search"
diff --git a/res/layout/search_inline_switch_item.xml b/res/layout/search_inline_switch_item.xml
index 40639b0..75943c4 100644
--- a/res/layout/search_inline_switch_item.xml
+++ b/res/layout/search_inline_switch_item.xml
@@ -48,7 +48,6 @@
             android:layout_height="wrap_content"
             android:textAppearance="?android:attr/textAppearanceListItemSecondary"
             android:textColor="?android:attr/textColorSecondary"
-            android:maxLength="60"
             android:maxLines="10"/>
 
         <include layout="@layout/search_breadcrumb_view"/>
@@ -60,4 +59,4 @@
         android:layout_height="match_parent"
         android:gravity="top"
         android:paddingStart="16dp"/>
-</LinearLayout>
\ No newline at end of file
+</LinearLayout>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index e5f4438..de6be1a 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -1634,6 +1634,8 @@
     <string name="wifi_cellular_data_fallback_summary">Use cellular data when Wi\u2011Fi has no Internet access. Data usage may apply.</string>
     <!-- Action bar text message to manually add a wifi network [CHAR LIMIT=20]-->
     <string name="wifi_add_network">Add network</string>
+    <!-- Action bar title to open additional Wi-Fi settings-->
+    <string name="wifi_configure_settings_preference_title">Wi\u2011Fi preferences</string>
     <!-- Header for the list of wifi networks-->
     <string name="wifi_access_points">Wi\u2011Fi networks</string>
     <!-- Menu option to do WPS Push Button [CHAR LIMIT=25]-->
@@ -8070,6 +8072,11 @@
         <item quantity="one"><xliff:g id="count">%d</xliff:g> app allowed access to your camera by your admin</item>
         <item quantity="other"><xliff:g id="count">%d</xliff:g> apps allowed access to your camera by your admin</item>
     </plurals>
+    <!-- Label indicating how many apps were set as default defaults for common actions (e.g. open browser, send e-mail) by the admin. [CHAR LIMIT=NONE] -->
+    <plurals name="enterprise_privacy_number_enterprise_set_default_apps">
+        <item quantity="one"><xliff:g id="count">%d</xliff:g> default app set by your admin</item>
+        <item quantity="other"><xliff:g id="count">%d</xliff:g> default apps set by your admin</item>
+    </plurals>
     <!-- Label explaining that an always-on VPN was set by the admin for the entire device. [CHAR LIMIT=NONE] -->
     <string name="enterprise_privacy_always_on_vpn_device">Always-on VPN turned on</string>
     <!-- Label explaining that an always-on VPN was set by the admin in the personal profile. [CHAR LIMIT=NONE] -->
@@ -8078,6 +8085,10 @@
     <string name="enterprise_privacy_always_on_vpn_work">Always-on VPN turned on in your work profile</string>
     <!-- Label explaining that a global HTTP proxy was set by the admin. [CHAR LIMIT=NONE] -->
     <string name="enterprise_privacy_global_http_proxy">Global HTTP proxy set</string>
+    <!-- Label explaining that the admin can lock the device and change the user's password. [CHAR LIMIT=NONE] -->
+    <string name="enterprise_privacy_lock_device">Admin can lock device and reset password</string>
+    <!-- Label explaining that the admin can wipe the device remotely. [CHAR LIMIT=NONE] -->
+    <string name="enterprise_privacy_wipe_device">Admin can delete all device data</string>
     <!-- Message indicating that the device is enterprise-managed by a Device Owner [CHAR LIMIT=NONE] -->
     <string name="do_disclosure_generic">This device is managed.</string>
     <!-- Message indicating that the device is enterprise-managed by a Device Owner [CHAR LIMIT=NONE] -->
diff --git a/res/xml/enterprise_privacy_settings.xml b/res/xml/enterprise_privacy_settings.xml
index 4bb2a8c..cc63d5f 100644
--- a/res/xml/enterprise_privacy_settings.xml
+++ b/res/xml/enterprise_privacy_settings.xml
@@ -76,6 +76,10 @@
                 settings:allowDividerBelow="true"
                 settings:multiLine="true"/>
         <com.android.settings.DividerPreference
+                android:key="number_enterprise_set_default_apps"
+                settings:allowDividerBelow="true"
+                settings:multiLine="true"/>
+        <com.android.settings.DividerPreference
                 android:key="always_on_vpn_primary_user"
                 settings:allowDividerBelow="true"
                 settings:multiLine="true"/>
@@ -92,5 +96,15 @@
     </PreferenceCategory>
 
     <PreferenceCategory android:title="@string/enterprise_privacy_device_access_category">
+        <com.android.settings.DividerPreference
+                android:key="lock_device"
+                android:title="@string/enterprise_privacy_lock_device"
+                settings:allowDividerBelow="true"
+                settings:multiLine="true"/>
+        <com.android.settings.DividerPreference
+                android:key="wipe_device"
+                android:title="@string/enterprise_privacy_wipe_device"
+                settings:allowDividerBelow="true"
+                settings:multiLine="true"/>
     </PreferenceCategory>
 </PreferenceScreen>
diff --git a/res/xml/wifi_configure_settings.xml b/res/xml/wifi_configure_settings.xml
index a43ea87..1e04749 100644
--- a/res/xml/wifi_configure_settings.xml
+++ b/res/xml/wifi_configure_settings.xml
@@ -17,11 +17,6 @@
 <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
         android:title="@string/wifi_configure_titlebar">
 
-    <Preference
-        android:key="saved_networks"
-        android:title="@string/wifi_saved_access_points_label"
-        android:fragment="com.android.settings.wifi.SavedAccessPointsWifiSettings" />
-
     <!-- android:dependency="enable_wifi" -->
     <ListPreference
         android:key="sleep_policy"
diff --git a/res/xml/wifi_settings.xml b/res/xml/wifi_settings.xml
index b4ab126..15743ea 100644
--- a/res/xml/wifi_settings.xml
+++ b/res/xml/wifi_settings.xml
@@ -14,14 +14,23 @@
      limitations under the License.
 -->
 
-<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
-                  xmlns:settings="http://schemas.android.com/apk/res/com.android.settings"
+<PreferenceScreen
+        xmlns:android="http://schemas.android.com/apk/res/android"
+        xmlns:settings="http://schemas.android.com/apk/res/com.android.settings"
         android:title="@string/wifi_settings"
         settings:keywords="@string/keywords_wifi">
 
-    <!-- Needed so PreferenceGroupAdapter allows AccessPointPreference to be
-         recycled. Removed in onResume -->
-    <com.android.settings.wifi.LongPressAccessPointPreference
-        android:key="dummy" />
+    <PreferenceCategory android:key="access_points"/>
 
+    <PreferenceCategory android:key="additional_settings">
+        <Preference
+                android:key="configure_settings"
+                android:title="@string/wifi_configure_settings_preference_title"
+                android:fragment="com.android.settings.wifi.ConfigureWifiSettings" />
+
+        <Preference
+                android:key="saved_networks"
+                android:title="@string/wifi_saved_access_points_label"
+                android:fragment="com.android.settings.wifi.SavedAccessPointsWifiSettings" />
+    </PreferenceCategory>
 </PreferenceScreen>
diff --git a/src/com/android/settings/DateTimeSettings.java b/src/com/android/settings/DateTimeSettings.java
index fc47fef..326f200 100644
--- a/src/com/android/settings/DateTimeSettings.java
+++ b/src/com/android/settings/DateTimeSettings.java
@@ -56,11 +56,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return null;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/DisplaySettings.java b/src/com/android/settings/DisplaySettings.java
index 91b193d..e7b44f6 100644
--- a/src/com/android/settings/DisplaySettings.java
+++ b/src/com/android/settings/DisplaySettings.java
@@ -68,11 +68,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return CategoryKey.CATEGORY_DISPLAY;
-    }
-
-    @Override
     protected int getPreferenceScreenResId() {
         if (mDashboardFeatureProvider.isEnabled()) {
             return R.xml.ia_display_settings;
diff --git a/src/com/android/settings/accounts/AccountDetailDashboardFragment.java b/src/com/android/settings/accounts/AccountDetailDashboardFragment.java
index 12f78ff..8143e96 100644
--- a/src/com/android/settings/accounts/AccountDetailDashboardFragment.java
+++ b/src/com/android/settings/accounts/AccountDetailDashboardFragment.java
@@ -22,15 +22,14 @@
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.support.annotation.VisibleForTesting;
-
 import android.support.v7.preference.Preference;
+
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.settings.R;
 import com.android.settings.Utils;
 import com.android.settings.core.PreferenceController;
 import com.android.settings.dashboard.DashboardFragment;
 import com.android.settingslib.accounts.AuthenticatorHelper;
-import com.android.settingslib.drawer.CategoryKey;
 import com.android.settingslib.drawer.Tile;
 
 import java.util.ArrayList;
@@ -62,8 +61,8 @@
         Bundle args = getArguments();
         final Activity activity = getActivity();
         UserHandle userHandle = Utils.getSecureTargetUser(activity.getActivityToken(),
-            (UserManager) getSystemService(Context.USER_SERVICE), args,
-            activity.getIntent().getExtras());
+                (UserManager) getSystemService(Context.USER_SERVICE), args,
+                activity.getIntent().getExtras());
         if (args != null) {
             if (args.containsKey(KEY_ACCOUNT)) {
                 mAccount = args.getParcelable(KEY_ACCOUNT);
@@ -94,11 +93,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return CategoryKey.CATEGORY_ACCOUNT;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
@@ -142,6 +136,6 @@
         }
         final AuthenticatorHelper helper = new AuthenticatorHelper(context, userHandle, null);
         headerPreference.setIcon(helper.getDrawableForType(context, mAccountType));
-   }
+    }
 
 }
\ No newline at end of file
diff --git a/src/com/android/settings/accounts/UserAndAccountDashboardFragment.java b/src/com/android/settings/accounts/UserAndAccountDashboardFragment.java
index 4113152..dbc0292 100644
--- a/src/com/android/settings/accounts/UserAndAccountDashboardFragment.java
+++ b/src/com/android/settings/accounts/UserAndAccountDashboardFragment.java
@@ -25,7 +25,6 @@
 import com.android.settings.dashboard.DashboardFragment;
 import com.android.settings.overlay.FeatureFactory;
 import com.android.settings.search.BaseSearchIndexProvider;
-import com.android.settingslib.drawer.CategoryKey;
 import com.android.settingslib.drawer.Tile;
 
 import java.util.ArrayList;
@@ -45,11 +44,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return CategoryKey.CATEGORY_ACCOUNT;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/applications/AdvancedAppSettings.java b/src/com/android/settings/applications/AdvancedAppSettings.java
index e8b621a..e59f94b 100644
--- a/src/com/android/settings/applications/AdvancedAppSettings.java
+++ b/src/com/android/settings/applications/AdvancedAppSettings.java
@@ -31,7 +31,6 @@
 import com.android.settings.dashboard.DashboardFragment;
 import com.android.settings.search.BaseSearchIndexProvider;
 import com.android.settings.search.Indexable;
-import com.android.settingslib.drawer.CategoryKey;
 
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -42,11 +41,6 @@
     static final String TAG = "AdvancedAppSettings";
 
     @Override
-    protected String getCategoryKey() {
-        return CategoryKey.CATEGORY_APPS_DEFAULT;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/applications/AppAndNotificationDashboardFragment.java b/src/com/android/settings/applications/AppAndNotificationDashboardFragment.java
index 5942897..5dda9c1 100644
--- a/src/com/android/settings/applications/AppAndNotificationDashboardFragment.java
+++ b/src/com/android/settings/applications/AppAndNotificationDashboardFragment.java
@@ -25,7 +25,6 @@
 import com.android.settings.dashboard.DashboardFragment;
 import com.android.settings.overlay.FeatureFactory;
 import com.android.settings.search.BaseSearchIndexProvider;
-import com.android.settingslib.drawer.CategoryKey;
 
 import java.util.Arrays;
 import java.util.List;
@@ -40,11 +39,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return CategoryKey.CATEGORY_APPS;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/applications/AppWithAdminGrantedPermissionsCounter.java b/src/com/android/settings/applications/AppWithAdminGrantedPermissionsCounter.java
index 331d384..52f1da5 100644
--- a/src/com/android/settings/applications/AppWithAdminGrantedPermissionsCounter.java
+++ b/src/com/android/settings/applications/AppWithAdminGrantedPermissionsCounter.java
@@ -17,7 +17,6 @@
 import android.app.admin.DevicePolicyManager;
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
-import android.content.pm.IPackageManager;
 import android.content.pm.PackageManager;
 import android.os.Build;
 import android.os.RemoteException;
@@ -33,11 +32,11 @@
 
     private final String[] mPermissions;
     private final PackageManagerWrapper mPackageManager;
-    private final IPackageManager mPackageManagerService;
+    private final IPackageManagerWrapper mPackageManagerService;
     private final DevicePolicyManagerWrapper mDevicePolicyManager;
 
     public AppWithAdminGrantedPermissionsCounter(Context context, String[] permissions,
-            PackageManagerWrapper packageManager, IPackageManager packageManagerService,
+            PackageManagerWrapper packageManager, IPackageManagerWrapper packageManagerService,
             DevicePolicyManagerWrapper devicePolicyManager) {
         super(context, packageManager);
         mPermissions = permissions;
diff --git a/src/com/android/settings/applications/ApplicationFeatureProvider.java b/src/com/android/settings/applications/ApplicationFeatureProvider.java
index 101ae91..fccbbd3 100644
--- a/src/com/android/settings/applications/ApplicationFeatureProvider.java
+++ b/src/com/android/settings/applications/ApplicationFeatureProvider.java
@@ -17,8 +17,11 @@
 package com.android.settings.applications;
 
 import android.app.Fragment;
+import android.content.Intent;
 import android.view.View;
 
+import java.util.Set;
+
 public interface ApplicationFeatureProvider {
 
     /**
@@ -55,9 +58,47 @@
             NumberOfAppsCallback callback);
 
     /**
+     * Return the persistent preferred activities configured by the admin for the current user and
+     * all its managed profiles. A persistent preferred activity is an activity that the admin
+     * configured to always handle a given intent (e.g. open browser), even if the user has other
+     * apps installed that would also be able to handle the intent.
+     *
+     * @param intent The intents for which to find persistent preferred activities
+     *
+     * @return the persistent preferred activites for the given intent
+     */
+    Set<PersistentPreferredActivityInfo> findPersistentPreferredActivities(Intent[] intents);
+
+    /**
      * Callback that receives the number of packages installed on the device.
      */
     interface NumberOfAppsCallback {
         void onNumberOfAppsResult(int num);
     }
+
+    public static class PersistentPreferredActivityInfo {
+        public final String packageName;
+        public final int userId;
+
+        public PersistentPreferredActivityInfo(String packageName, int userId) {
+            this.packageName = packageName;
+            this.userId = userId;
+        }
+
+        @Override
+        public boolean equals(Object other) {
+            if (!(other instanceof PersistentPreferredActivityInfo)) {
+                return false;
+            }
+            final PersistentPreferredActivityInfo otherActivityInfo
+                    = (PersistentPreferredActivityInfo) other;
+            return otherActivityInfo.packageName.equals(packageName)
+                    && otherActivityInfo.userId == userId;
+        }
+
+        @Override
+        public int hashCode() {
+            return packageName.hashCode() ^ userId;
+        }
+    }
 }
diff --git a/src/com/android/settings/applications/ApplicationFeatureProviderImpl.java b/src/com/android/settings/applications/ApplicationFeatureProviderImpl.java
index ff7f0f0..2d2bce0 100644
--- a/src/com/android/settings/applications/ApplicationFeatureProviderImpl.java
+++ b/src/com/android/settings/applications/ApplicationFeatureProviderImpl.java
@@ -18,25 +18,34 @@
 
 import android.app.Fragment;
 import android.content.Context;
-import android.content.pm.IPackageManager;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.content.pm.ComponentInfo;
+import android.content.pm.ProviderInfo;
+import android.content.pm.ResolveInfo;
+import android.content.pm.ServiceInfo;
 import android.content.pm.UserInfo;
+import android.os.RemoteException;
+import android.os.UserHandle;
 import android.os.UserManager;
+import android.util.ArraySet;
 import android.view.View;
 
 import com.android.settings.enterprise.DevicePolicyManagerWrapper;
 
 import java.util.List;
+import java.util.Set;
 
 public class ApplicationFeatureProviderImpl implements ApplicationFeatureProvider {
 
     private final Context mContext;
     private final PackageManagerWrapper mPm;
-    private final IPackageManager mPms;
+    private final IPackageManagerWrapper mPms;
     private final DevicePolicyManagerWrapper mDpm;
     private final UserManager mUm;
 
     public ApplicationFeatureProviderImpl(Context context, PackageManagerWrapper pm,
-            IPackageManager pms, DevicePolicyManagerWrapper dpm) {
+            IPackageManagerWrapper pms, DevicePolicyManagerWrapper dpm) {
         mContext = context.getApplicationContext();
         mPm = pm;
         mPms = pms;
@@ -61,6 +70,39 @@
                 callback).execute();
     }
 
+    @Override
+    public Set<PersistentPreferredActivityInfo> findPersistentPreferredActivities(
+            Intent[] intents) {
+        final Set<PersistentPreferredActivityInfo> activities = new ArraySet<>();
+        final List<UserHandle> users = mUm.getUserProfiles();
+        for (final Intent intent : intents) {
+            for (final UserHandle user : users) {
+                final int userId = user.getIdentifier();
+                try {
+                    final ResolveInfo resolveInfo = mPms.findPersistentPreferredActivity(intent,
+                            userId);
+                    if (resolveInfo != null) {
+                        ComponentInfo componentInfo = null;
+                        if (resolveInfo.activityInfo != null) {
+                            componentInfo = resolveInfo.activityInfo;
+                        } else if (resolveInfo.serviceInfo != null) {
+                            componentInfo = resolveInfo.serviceInfo;
+                        } else if (resolveInfo.providerInfo != null) {
+                            componentInfo = resolveInfo.providerInfo;
+                        }
+                        if (componentInfo != null) {
+                            activities.add(new PersistentPreferredActivityInfo(
+                                    componentInfo.packageName, userId));
+                        }
+                    }
+                } catch (RemoteException exception) {
+                }
+            }
+
+        }
+        return activities;
+    }
+
     private static class AllUserInstalledAppCounter extends InstalledAppCounter {
         private NumberOfAppsCallback mCallback;
 
@@ -86,7 +128,7 @@
         private NumberOfAppsCallback mCallback;
 
         AllUserAppWithAdminGrantedPermissionsCounter(Context context, String[] permissions,
-                PackageManagerWrapper packageManager, IPackageManager packageManagerService,
+                PackageManagerWrapper packageManager, IPackageManagerWrapper packageManagerService,
                 DevicePolicyManagerWrapper devicePolicyManager, NumberOfAppsCallback callback) {
             super(context, permissions, packageManager, packageManagerService, devicePolicyManager);
             mCallback = callback;
diff --git a/src/com/android/settings/applications/IPackageManagerWrapper.java b/src/com/android/settings/applications/IPackageManagerWrapper.java
new file mode 100644
index 0000000..f885985
--- /dev/null
+++ b/src/com/android/settings/applications/IPackageManagerWrapper.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2017 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.applications;
+
+import android.content.Intent;
+import android.content.pm.ResolveInfo;
+import android.os.RemoteException;
+
+/**
+ * This interface replicates a subset of the android.content.pm.IPackageManager (PMS). The interface
+ * exists so that we can use a thin wrapper around the PMS in production code and a mock in tests.
+ * We cannot directly mock or shadow the PMS, because some of the methods we rely on are newer than
+ * the API version supported by Robolectric.
+ */
+public interface IPackageManagerWrapper {
+
+    /**
+     * Calls {@code IPackageManager.checkUidPermission()}.
+     *
+     * @see android.content.pm.IPackageManager#checkUidPermission
+     */
+    int checkUidPermission(String permName, int uid) throws RemoteException;
+
+    /**
+     * Calls {@code IPackageManager.findPersistentPreferredActivity()}.
+     *
+     * @see android.content.pm.IPackageManager#findPersistentPreferredActivity
+     */
+    ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) throws RemoteException;
+}
diff --git a/src/com/android/settings/applications/IPackageManagerWrapperImpl.java b/src/com/android/settings/applications/IPackageManagerWrapperImpl.java
new file mode 100644
index 0000000..5ea15b9
--- /dev/null
+++ b/src/com/android/settings/applications/IPackageManagerWrapperImpl.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 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.applications;
+
+import android.content.Intent;
+import android.content.pm.IPackageManager;
+import android.content.pm.ResolveInfo;
+import android.os.RemoteException;
+
+public class IPackageManagerWrapperImpl implements IPackageManagerWrapper {
+
+    private final IPackageManager mPms;
+
+    public IPackageManagerWrapperImpl(IPackageManager pms) {
+        mPms = pms;
+    }
+
+    @Override
+    public int checkUidPermission(String permName, int uid) throws RemoteException {
+        return mPms.checkUidPermission(permName, uid);
+    }
+
+    @Override
+    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId)
+            throws RemoteException {
+        return mPms.findPersistentPreferredActivity(intent, userId);
+    }
+}
diff --git a/src/com/android/settings/connecteddevice/ConnectedDeviceDashboardFragment.java b/src/com/android/settings/connecteddevice/ConnectedDeviceDashboardFragment.java
index fe0e1d2..481a0eb 100644
--- a/src/com/android/settings/connecteddevice/ConnectedDeviceDashboardFragment.java
+++ b/src/com/android/settings/connecteddevice/ConnectedDeviceDashboardFragment.java
@@ -30,7 +30,6 @@
 import com.android.settings.overlay.FeatureFactory;
 import com.android.settings.search.BaseSearchIndexProvider;
 import com.android.settings.search.Indexable;
-import com.android.settingslib.drawer.CategoryKey;
 
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -48,11 +47,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return CategoryKey.CATEGORY_DEVICE;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
@@ -73,8 +67,7 @@
         mUsbPrefController = new UsbModePreferenceController(context, new UsbBackend(context));
         lifecycle.addObserver(mUsbPrefController);
         controllers.add(mUsbPrefController);
-        mBluetoothPreferenceController =
-            new BluetoothMasterSwitchPreferenceController(
+        mBluetoothPreferenceController = new BluetoothMasterSwitchPreferenceController(
                 context, Utils.getLocalBtManager(context));
         lifecycle.addObserver(mBluetoothPreferenceController);
         controllers.add(mBluetoothPreferenceController);
diff --git a/src/com/android/settings/dashboard/DashboardFragment.java b/src/com/android/settings/dashboard/DashboardFragment.java
index de86bd5..f8a27e0 100644
--- a/src/com/android/settings/dashboard/DashboardFragment.java
+++ b/src/com/android/settings/dashboard/DashboardFragment.java
@@ -194,7 +194,10 @@
     /**
      * Returns the CategoryKey for loading {@link DashboardCategory} for this fragment.
      */
-    protected abstract String getCategoryKey();
+    @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+    public String getCategoryKey() {
+        return DashboardFragmentRegistry.PARENT_TO_CATEGORY_KEY_MAP.get(getClass().getName());
+    }
 
     /**
      * Get the tag string for logging.
@@ -302,9 +305,9 @@
         final Context context = getContext();
         mSummaryLoader = new SummaryLoader(getActivity(), getCategoryKey());
         mSummaryLoader.setSummaryConsumer(this);
-        final TypedArray a = context.obtainStyledAttributes(new int[] {
-            mDashboardFeatureProvider.isEnabled() ? android.R.attr.colorControlNormal
-                : android.R.attr.colorAccent});
+        final TypedArray a = context.obtainStyledAttributes(new int[]{
+                mDashboardFeatureProvider.isEnabled() ? android.R.attr.colorControlNormal
+                        : android.R.attr.colorAccent});
         final int tintColor = a.getColor(0, context.getColor(android.R.color.white));
         a.recycle();
         final String pkgName = context.getPackageName();
@@ -319,7 +322,7 @@
                 continue;
             }
             if (pkgName != null && tile.intent != null
-                && !pkgName.equals(tile.intent.getComponent().getPackageName())) {
+                    && !pkgName.equals(tile.intent.getComponent().getPackageName())) {
                 // If this drawable is coming from outside Settings, tint it to match the color.
                 tile.icon.setTint(tintColor);
             }
diff --git a/src/com/android/settings/dashboard/DashboardFragmentRegistry.java b/src/com/android/settings/dashboard/DashboardFragmentRegistry.java
index 54d4fd0..a315836 100644
--- a/src/com/android/settings/dashboard/DashboardFragmentRegistry.java
+++ b/src/com/android/settings/dashboard/DashboardFragmentRegistry.java
@@ -21,13 +21,16 @@
 import com.android.settings.DevelopmentSettings;
 import com.android.settings.DisplaySettings;
 import com.android.settings.SecuritySettings;
+import com.android.settings.accounts.AccountDetailDashboardFragment;
 import com.android.settings.accounts.UserAndAccountDashboardFragment;
 import com.android.settings.applications.AdvancedAppSettings;
 import com.android.settings.applications.AppAndNotificationDashboardFragment;
 import com.android.settings.connecteddevice.ConnectedDeviceDashboardFragment;
 import com.android.settings.deviceinfo.StorageDashboardFragment;
+import com.android.settings.fuelgauge.PowerUsageSummary;
 import com.android.settings.inputmethod.InputAndGestureSettings;
 import com.android.settings.inputmethod.InputMethodAndLanguageSettings;
+import com.android.settings.language.LanguageAndRegionSettings;
 import com.android.settings.network.NetworkDashboardFragment;
 import com.android.settings.notification.SoundSettings;
 import com.android.settings.system.SystemDashboardFragment;
@@ -37,7 +40,6 @@
 
 /**
  * A registry to keep track of which page hosts which category.
- * TODO: Remove DashboardFragment#getCategoryKey() and just use this registry instead.
  */
 public class DashboardFragmentRegistry {
 
@@ -61,6 +63,8 @@
                 CategoryKey.CATEGORY_DEVICE);
         PARENT_TO_CATEGORY_KEY_MAP.put(AppAndNotificationDashboardFragment.class.getName(),
                 CategoryKey.CATEGORY_APPS);
+        PARENT_TO_CATEGORY_KEY_MAP.put(PowerUsageSummary.class.getName(),
+                CategoryKey.CATEGORY_BATTERY);
         PARENT_TO_CATEGORY_KEY_MAP.put(AdvancedAppSettings.class.getName(),
                 CategoryKey.CATEGORY_APPS_DEFAULT);
         PARENT_TO_CATEGORY_KEY_MAP.put(DisplaySettings.class.getName(),
@@ -71,7 +75,7 @@
                 CategoryKey.CATEGORY_STORAGE);
         PARENT_TO_CATEGORY_KEY_MAP.put(SecuritySettings.class.getName(),
                 CategoryKey.CATEGORY_SECURITY);
-        PARENT_TO_CATEGORY_KEY_MAP.put(UserAndAccountDashboardFragment.class.getName(),
+        PARENT_TO_CATEGORY_KEY_MAP.put(AccountDetailDashboardFragment.class.getName(),
                 CategoryKey.CATEGORY_ACCOUNT);
         PARENT_TO_CATEGORY_KEY_MAP.put(UserAndAccountDashboardFragment.class.getName(),
                 CategoryKey.CATEGORY_ACCOUNT);
@@ -81,6 +85,8 @@
                 InputAndGestureSettings.class.getName(), CategoryKey.CATEGORY_SYSTEM_INPUT);
         PARENT_TO_CATEGORY_KEY_MAP.put(InputMethodAndLanguageSettings.class.getName(),
                 CategoryKey.CATEGORY_SYSTEM_LANGUAGE);
+        PARENT_TO_CATEGORY_KEY_MAP.put(LanguageAndRegionSettings.class.getName(),
+                CategoryKey.CATEGORY_SYSTEM_LANGUAGE);
         PARENT_TO_CATEGORY_KEY_MAP.put(DevelopmentSettings.class.getName(),
                 CategoryKey.CATEGORY_SYSTEM_DEVELOPMENT);
 
diff --git a/src/com/android/settings/deviceinfo/StorageDashboardFragment.java b/src/com/android/settings/deviceinfo/StorageDashboardFragment.java
index 8fabd8d..59f9a84 100644
--- a/src/com/android/settings/deviceinfo/StorageDashboardFragment.java
+++ b/src/com/android/settings/deviceinfo/StorageDashboardFragment.java
@@ -101,11 +101,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return CategoryKey.CATEGORY_STORAGE;
-    }
-
-    @Override
     protected int getPreferenceScreenResId() {
         return R.xml.storage_dashboard_fragment;
     }
diff --git a/src/com/android/settings/enterprise/EnterprisePrivacySettings.java b/src/com/android/settings/enterprise/EnterprisePrivacySettings.java
index 208bf0c..75d3b10 100644
--- a/src/com/android/settings/enterprise/EnterprisePrivacySettings.java
+++ b/src/com/android/settings/enterprise/EnterprisePrivacySettings.java
@@ -24,7 +24,6 @@
 import com.android.settings.core.PreferenceController;
 import com.android.settings.dashboard.DashboardFragment;
 import com.android.settings.search.BaseSearchIndexProvider;
-import com.android.settings.search.Indexable.SearchIndexProvider;
 
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -40,11 +39,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return null;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
@@ -65,6 +59,7 @@
         controllers.add(new AdminGrantedLocationPermissionsPreferenceController(context));
         controllers.add(new AdminGrantedMicrophonePermissionPreferenceController(context));
         controllers.add(new AdminGrantedCameraPermissionPreferenceController(context));
+        controllers.add(new EnterpriseSetDefaultAppsPreferenceController(context));
         controllers.add(new AlwaysOnVpnPrimaryUserPreferenceController(context));
         controllers.add(new AlwaysOnVpnManagedProfilePreferenceController(context));
         controllers.add(new GlobalHttpProxyPreferenceController(context));
diff --git a/src/com/android/settings/enterprise/EnterpriseSetDefaultAppsPreferenceController.java b/src/com/android/settings/enterprise/EnterpriseSetDefaultAppsPreferenceController.java
new file mode 100644
index 0000000..23627cd
--- /dev/null
+++ b/src/com/android/settings/enterprise/EnterpriseSetDefaultAppsPreferenceController.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2017 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.enterprise;
+
+import android.content.Context;
+import android.content.Intent;
+import android.net.Uri;
+import android.provider.ContactsContract;
+import android.provider.MediaStore;
+import android.support.v7.preference.Preference;
+
+import com.android.settings.R;
+import com.android.settings.applications.ApplicationFeatureProvider;
+import com.android.settings.core.PreferenceController;
+import com.android.settings.overlay.FeatureFactory;
+
+public class EnterpriseSetDefaultAppsPreferenceController extends PreferenceController {
+
+    private static final String KEY_DEFAULT_APPS = "number_enterprise_set_default_apps";
+    private final ApplicationFeatureProvider mFeatureProvider;
+
+    public EnterpriseSetDefaultAppsPreferenceController(Context context) {
+        super(context);
+        mFeatureProvider = FeatureFactory.getFactory(context)
+                .getApplicationFeatureProvider(context);
+    }
+
+    @Override
+    public void updateState(Preference preference) {
+        // Browser
+        int num = mFeatureProvider.findPersistentPreferredActivities(new Intent[] {
+                buildIntent(Intent.ACTION_VIEW, Intent.CATEGORY_BROWSABLE, "http:", null)}).size();
+        // Camera
+        num += mFeatureProvider.findPersistentPreferredActivities(new Intent[] {
+                new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
+                new Intent(MediaStore.ACTION_VIDEO_CAPTURE)}).size();
+        // Map
+        num += mFeatureProvider.findPersistentPreferredActivities(new Intent[] {
+                buildIntent(Intent.ACTION_VIEW, null, "geo:", null)}).size();
+        // E-mail
+        num += mFeatureProvider.findPersistentPreferredActivities(new Intent[] {
+                new Intent(Intent.ACTION_SENDTO), new Intent(Intent.ACTION_SEND),
+                new Intent(Intent.ACTION_SEND_MULTIPLE)}).size();
+        // Calendar
+        num += mFeatureProvider.findPersistentPreferredActivities(new Intent[] {
+                buildIntent(Intent.ACTION_INSERT, null, null, "vnd.android.cursor.dir/event")})
+                .size();
+        // Contacts
+        num += mFeatureProvider.findPersistentPreferredActivities(new Intent[] {
+                buildIntent(Intent.ACTION_PICK, null, null,
+                        ContactsContract.Contacts.CONTENT_TYPE)}).size();
+        // Dialer
+        num += mFeatureProvider.findPersistentPreferredActivities(new Intent[] {
+                new Intent(Intent.ACTION_DIAL), new Intent(Intent.ACTION_CALL)}).size();
+
+        if (num == 0) {
+            preference.setVisible(false);
+        } else {
+            preference.setVisible(true);
+            preference.setTitle(mContext.getResources().getQuantityString(
+                    R.plurals.enterprise_privacy_number_enterprise_set_default_apps,
+                    num, num));
+        }
+    }
+
+    @Override
+    public boolean isAvailable() {
+        return true;
+    }
+
+    @Override
+    public String getPreferenceKey() {
+        return KEY_DEFAULT_APPS;
+    }
+
+    private static Intent buildIntent(String action, String category, String protocol,
+            String type) {
+        final Intent intent = new Intent(action);
+        if (category != null) {
+            intent.addCategory(category);
+        }
+        if (protocol != null) {
+            intent.setData(Uri.parse(protocol));
+        }
+        if (type != null) {
+            intent.setType(type);
+        }
+        return intent;
+    }
+}
diff --git a/src/com/android/settings/fuelgauge/PowerUsageDetail.java b/src/com/android/settings/fuelgauge/PowerUsageDetail.java
index dbc5360..7acb7ce 100644
--- a/src/com/android/settings/fuelgauge/PowerUsageDetail.java
+++ b/src/com/android/settings/fuelgauge/PowerUsageDetail.java
@@ -388,11 +388,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return null;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/fuelgauge/PowerUsageSummary.java b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
index c4a780f..db6bfb8 100644
--- a/src/com/android/settings/fuelgauge/PowerUsageSummary.java
+++ b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
@@ -37,6 +37,7 @@
 import android.view.Menu;
 import android.view.MenuInflater;
 import android.view.MenuItem;
+
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.internal.os.BatterySipper;
 import com.android.internal.os.BatterySipper.DrainType;
@@ -52,7 +53,6 @@
 import com.android.settings.overlay.FeatureFactory;
 import com.android.settings.search.BaseSearchIndexProvider;
 import com.android.settingslib.BatteryInfo;
-import com.android.settingslib.drawer.CategoryKey;
 
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -139,11 +139,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return CategoryKey.CATEGORY_BATTERY;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
@@ -414,8 +409,9 @@
                 pref.setTitle(entry.getLabel());
                 pref.setOrder(i + 1);
                 pref.setPercent(percentOfMax, percentOfTotal);
-                if ((sipper.drainType != DrainType.APP || sipper.uidObj.getUid() == Process.ROOT_UID)
-                         && sipper.drainType != DrainType.USER) {
+                if ((sipper.drainType != DrainType.APP
+                        || sipper.uidObj.getUid() == Process.ROOT_UID)
+                        && sipper.drainType != DrainType.USER) {
                     pref.setTint(colorControl);
                 }
                 addedSome = true;
@@ -579,7 +575,7 @@
             = new SummaryLoader.SummaryProviderFactory() {
         @Override
         public SummaryLoader.SummaryProvider createSummaryProvider(Activity activity,
-                                                                   SummaryLoader summaryLoader) {
+                SummaryLoader summaryLoader) {
             return new SummaryProvider(activity, summaryLoader);
         }
     };
diff --git a/src/com/android/settings/gestures/DoubleTapPowerSettings.java b/src/com/android/settings/gestures/DoubleTapPowerSettings.java
index c31e999..9251f0b 100644
--- a/src/com/android/settings/gestures/DoubleTapPowerSettings.java
+++ b/src/com/android/settings/gestures/DoubleTapPowerSettings.java
@@ -40,11 +40,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return null;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/gestures/DoubleTapScreenSettings.java b/src/com/android/settings/gestures/DoubleTapScreenSettings.java
index d203fbc..f374f9e 100644
--- a/src/com/android/settings/gestures/DoubleTapScreenSettings.java
+++ b/src/com/android/settings/gestures/DoubleTapScreenSettings.java
@@ -42,11 +42,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return null;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/gestures/DoubleTwistGestureSettings.java b/src/com/android/settings/gestures/DoubleTwistGestureSettings.java
index 1303ca1..5f5b873 100644
--- a/src/com/android/settings/gestures/DoubleTwistGestureSettings.java
+++ b/src/com/android/settings/gestures/DoubleTwistGestureSettings.java
@@ -40,11 +40,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return null;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/gestures/GestureSettings.java b/src/com/android/settings/gestures/GestureSettings.java
index 9b71b96..db6925e 100644
--- a/src/com/android/settings/gestures/GestureSettings.java
+++ b/src/com/android/settings/gestures/GestureSettings.java
@@ -122,11 +122,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return null;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
@@ -170,7 +165,7 @@
 
                     List<PreferenceController> preferenceControllers =
                             getPreferenceControllers(context);
-                    for(PreferenceController controller : preferenceControllers) {
+                    for (PreferenceController controller : preferenceControllers) {
                         controller.updateNonIndexableKeys(result);
                     }
                     return result;
diff --git a/src/com/android/settings/gestures/PickupGestureSettings.java b/src/com/android/settings/gestures/PickupGestureSettings.java
index 8c0f74c..08e61fa 100644
--- a/src/com/android/settings/gestures/PickupGestureSettings.java
+++ b/src/com/android/settings/gestures/PickupGestureSettings.java
@@ -42,11 +42,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return null;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/gestures/SwipeToNotificationSettings.java b/src/com/android/settings/gestures/SwipeToNotificationSettings.java
index fba074e..155412c 100644
--- a/src/com/android/settings/gestures/SwipeToNotificationSettings.java
+++ b/src/com/android/settings/gestures/SwipeToNotificationSettings.java
@@ -40,11 +40,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return null;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/inputmethod/InputAndGestureSettings.java b/src/com/android/settings/inputmethod/InputAndGestureSettings.java
index 4ad5af2..5b2c51a 100644
--- a/src/com/android/settings/inputmethod/InputAndGestureSettings.java
+++ b/src/com/android/settings/inputmethod/InputAndGestureSettings.java
@@ -34,7 +34,6 @@
 import com.android.settings.gestures.SwipeToNotificationPreferenceController;
 import com.android.settings.overlay.FeatureFactory;
 import com.android.settings.search.BaseSearchIndexProvider;
-import com.android.settingslib.drawer.CategoryKey;
 
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -52,11 +51,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return CategoryKey.CATEGORY_SYSTEM_INPUT;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java b/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java
index 587d039..121af98 100644
--- a/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java
+++ b/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java
@@ -38,7 +38,6 @@
 import com.android.settings.search.BaseSearchIndexProvider;
 import com.android.settings.search.Indexable;
 import com.android.settings.search.SearchIndexableRaw;
-import com.android.settingslib.drawer.CategoryKey;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -61,11 +60,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return CategoryKey.CATEGORY_SYSTEM_LANGUAGE;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/language/LanguageAndRegionSettings.java b/src/com/android/settings/language/LanguageAndRegionSettings.java
index 7e92e05..649b2ff 100644
--- a/src/com/android/settings/language/LanguageAndRegionSettings.java
+++ b/src/com/android/settings/language/LanguageAndRegionSettings.java
@@ -24,7 +24,6 @@
 import com.android.settings.core.PreferenceController;
 import com.android.settings.dashboard.DashboardFragment;
 import com.android.settings.inputmethod.SpellCheckerPreferenceController;
-import com.android.settingslib.drawer.CategoryKey;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -39,11 +38,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return CategoryKey.CATEGORY_SYSTEM_LANGUAGE;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/network/NetworkDashboardFragment.java b/src/com/android/settings/network/NetworkDashboardFragment.java
index 89dfa02..7e6de96 100644
--- a/src/com/android/settings/network/NetworkDashboardFragment.java
+++ b/src/com/android/settings/network/NetworkDashboardFragment.java
@@ -27,7 +27,6 @@
 import com.android.settings.dashboard.DashboardFragment;
 import com.android.settings.overlay.FeatureFactory;
 import com.android.settings.search.BaseSearchIndexProvider;
-import com.android.settingslib.drawer.CategoryKey;
 
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -47,11 +46,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return CategoryKey.CATEGORY_NETWORK;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/notification/ConfigureNotificationSettings.java b/src/com/android/settings/notification/ConfigureNotificationSettings.java
index fd59c97..2a737d4 100644
--- a/src/com/android/settings/notification/ConfigureNotificationSettings.java
+++ b/src/com/android/settings/notification/ConfigureNotificationSettings.java
@@ -40,11 +40,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return "";
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/notification/OtherSoundSettings.java b/src/com/android/settings/notification/OtherSoundSettings.java
index 15e7f8c..5c409d3 100644
--- a/src/com/android/settings/notification/OtherSoundSettings.java
+++ b/src/com/android/settings/notification/OtherSoundSettings.java
@@ -47,11 +47,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return null;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/notification/SoundSettings.java b/src/com/android/settings/notification/SoundSettings.java
index a55278d..1cf0ae6 100644
--- a/src/com/android/settings/notification/SoundSettings.java
+++ b/src/com/android/settings/notification/SoundSettings.java
@@ -20,7 +20,6 @@
 import android.app.NotificationManager;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
-import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
@@ -43,7 +42,7 @@
 import com.android.settings.dashboard.SummaryLoader;
 import com.android.settings.overlay.FeatureFactory;
 import com.android.settings.search.BaseSearchIndexProvider;
-import com.android.settingslib.drawer.CategoryKey;
+
 import java.text.NumberFormat;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -103,11 +102,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return CategoryKey.CATEGORY_SOUND;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
diff --git a/src/com/android/settings/overlay/FeatureFactoryImpl.java b/src/com/android/settings/overlay/FeatureFactoryImpl.java
index 2c81241..c45bf0e 100644
--- a/src/com/android/settings/overlay/FeatureFactoryImpl.java
+++ b/src/com/android/settings/overlay/FeatureFactoryImpl.java
@@ -25,6 +25,7 @@
 
 import com.android.settings.applications.ApplicationFeatureProvider;
 import com.android.settings.applications.ApplicationFeatureProviderImpl;
+import com.android.settings.applications.IPackageManagerWrapperImpl;
 import com.android.settings.applications.PackageManagerWrapperImpl;
 import com.android.settings.core.instrumentation.MetricsFeatureProvider;
 import com.android.settings.core.instrumentation.MetricsFeatureProviderImpl;
@@ -90,7 +91,7 @@
         if (mApplicationFeatureProvider == null) {
             mApplicationFeatureProvider = new ApplicationFeatureProviderImpl(context,
                     new PackageManagerWrapperImpl(context.getPackageManager()),
-                    AppGlobals.getPackageManager(),
+                    new IPackageManagerWrapperImpl(AppGlobals.getPackageManager()),
                     new DevicePolicyManagerWrapperImpl((DevicePolicyManager) context
                             .getSystemService(Context.DEVICE_POLICY_SERVICE)));
         }
diff --git a/src/com/android/settings/system/SystemDashboardFragment.java b/src/com/android/settings/system/SystemDashboardFragment.java
index b06d403..c46bc6f 100644
--- a/src/com/android/settings/system/SystemDashboardFragment.java
+++ b/src/com/android/settings/system/SystemDashboardFragment.java
@@ -30,7 +30,6 @@
 import com.android.settings.overlay.FeatureFactory;
 import com.android.settings.search.BaseSearchIndexProvider;
 import com.android.settings.search.Indexable;
-import com.android.settingslib.drawer.CategoryKey;
 
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -57,11 +56,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        return CategoryKey.CATEGORY_SYSTEM;
-    }
-
-    @Override
     protected List<PreferenceController> getPreferenceControllers(Context context) {
         final List<PreferenceController> controllers = new ArrayList<>();
         controllers.add(new SystemUpdatePreferenceController(context, UserManager.get(context)));
diff --git a/src/com/android/settings/wifi/ConfigureWifiSettings.java b/src/com/android/settings/wifi/ConfigureWifiSettings.java
index 6cbdb29..682662a 100644
--- a/src/com/android/settings/wifi/ConfigureWifiSettings.java
+++ b/src/com/android/settings/wifi/ConfigureWifiSettings.java
@@ -15,8 +15,6 @@
  */
 package com.android.settings.wifi;
 
-import static android.content.Context.WIFI_SERVICE;
-
 import android.content.Context;
 import android.net.wifi.WifiManager;
 import android.provider.SearchIndexableResource;
@@ -32,6 +30,8 @@
 import java.util.Arrays;
 import java.util.List;
 
+import static android.content.Context.WIFI_SERVICE;
+
 public class ConfigureWifiSettings extends DashboardFragment {
 
     private static final String TAG = "ConfigureWifiSettings";
@@ -44,12 +44,6 @@
     }
 
     @Override
-    protected String getCategoryKey() {
-        // We don't want to inject any external settings into this screen.
-        return null;
-    }
-
-    @Override
     protected String getLogTag() {
         return TAG;
     }
@@ -64,7 +58,6 @@
         mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
         final List<PreferenceController> controllers = new ArrayList<>();
         controllers.add(new WifiInfoPreferenceController(context, getLifecycle(), mWifiManager));
-        controllers.add(new SavedNetworkPreferenceController(context, mWifiManager));
         controllers.add(new CellularFallbackPreferenceController(context));
         controllers.add(new AllowRecommendationPreferenceController(context));
         controllers.add(new NotifyOpenNetworksPreferenceController(context, getLifecycle()));
diff --git a/src/com/android/settings/wifi/LinkablePreference.java b/src/com/android/settings/wifi/LinkablePreference.java
new file mode 100644
index 0000000..6b1b87d
--- /dev/null
+++ b/src/com/android/settings/wifi/LinkablePreference.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2017 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.wifi;
+
+import android.content.Context;
+import android.support.annotation.Nullable;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceViewHolder;
+import android.text.Spannable;
+import android.text.style.TextAppearanceSpan;
+import android.util.AttributeSet;
+import android.widget.TextView;
+import com.android.settings.LinkifyUtils;
+
+/**
+ * A preference with a title that can have linkable content on click.
+ */
+public class LinkablePreference extends Preference {
+
+    private LinkifyUtils.OnClickListener mClickListener;
+    private CharSequence mContentTitle;
+    private CharSequence mContentDescription;
+
+    public LinkablePreference(Context ctx, AttributeSet attrs, int defStyle) {
+        super(ctx, attrs, defStyle);
+        setSelectable(false);
+    }
+
+    public LinkablePreference(Context ctx, AttributeSet attrs) {
+        super(ctx, attrs);
+        setSelectable(false);
+    }
+
+    public LinkablePreference(Context ctx) {
+        super(ctx);
+        setSelectable(false);
+    }
+
+    @Override
+    public void onBindViewHolder(PreferenceViewHolder view) {
+        super.onBindViewHolder(view);
+
+        TextView textView = (TextView) view.findViewById(android.R.id.title);
+        if (textView == null || mContentTitle == null || mClickListener == null) {
+            return;
+        }
+
+        textView.setSingleLine(false);
+        StringBuilder contentBuilder = new StringBuilder().append(mContentTitle);
+        if (mContentDescription != null) {
+            contentBuilder.append("\n\n");
+            contentBuilder.append(mContentDescription);
+        }
+
+        boolean linked = LinkifyUtils.linkify(textView, contentBuilder, mClickListener);
+        if (linked && mContentTitle != null) {
+            // Embolden and enlarge the title.
+            Spannable boldSpan = (Spannable) textView.getText();
+            boldSpan.setSpan(
+                    new TextAppearanceSpan(
+                            getContext(), android.R.style.TextAppearance_Medium),
+                    0,
+                    mContentTitle.length(),
+                    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
+            textView.setText(boldSpan);
+        }
+    }
+
+    /**
+     * Sets the linkable text for the Preference title.
+     * @param contentTitle text to set the Preference title.
+     * @param contentDescription description text to append underneath title, can be null.
+     * @param clickListener OnClickListener for the link portion of the text.
+     */
+    public void setText(
+            CharSequence contentTitle,
+            @Nullable CharSequence contentDescription,
+            LinkifyUtils.OnClickListener clickListener) {
+        mContentTitle = contentTitle;
+        mContentDescription = contentDescription;
+        mClickListener = clickListener;
+        // sets the title so that the title TextView is not hidden in super.onBindViewHolder()
+        super.setTitle(contentTitle);
+    }
+
+    /**
+     * Sets the title of the LinkablePreference. resets linkable text for reusability.
+     */
+    @Override
+    public void setTitle(int titleResId) {
+        mContentTitle = null;
+        mContentDescription = null;
+        super.setTitle(titleResId);
+    }
+
+    /**
+     * Sets the title of the LinkablePreference. resets linkable text for reusability.
+     */
+    @Override
+    public void setTitle(CharSequence title) {
+        mContentTitle = null;
+        mContentDescription = null;
+        super.setTitle(title);
+    }
+}
diff --git a/src/com/android/settings/wifi/SavedNetworkPreferenceController.java b/src/com/android/settings/wifi/SavedNetworkPreferenceController.java
deleted file mode 100644
index c3ad355..0000000
--- a/src/com/android/settings/wifi/SavedNetworkPreferenceController.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2017 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.wifi;
-
-import android.content.Context;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiManager;
-
-import com.android.settings.core.PreferenceController;
-
-import java.util.List;
-
-/**
- * {@link PreferenceController} that opens saved network subsetting.
- */
-public class SavedNetworkPreferenceController extends PreferenceController {
-
-    private static final String KEY_SAVED_NETWORKS = "saved_networks";
-
-    private final WifiManager mWifiManager;
-
-    public SavedNetworkPreferenceController(Context context, WifiManager wifiManager) {
-        super(context);
-        mWifiManager = wifiManager;
-    }
-
-    @Override
-    public boolean isAvailable() {
-        final List<WifiConfiguration> config = mWifiManager.getConfiguredNetworks();
-        return config != null && !config.isEmpty();
-    }
-
-    @Override
-    public String getPreferenceKey() {
-        return KEY_SAVED_NETWORKS;
-    }
-}
diff --git a/src/com/android/settings/wifi/WifiSettings.java b/src/com/android/settings/wifi/WifiSettings.java
index 1dd18bd..4fd93b5 100644
--- a/src/com/android/settings/wifi/WifiSettings.java
+++ b/src/com/android/settings/wifi/WifiSettings.java
@@ -40,11 +40,10 @@
 import android.os.Process;
 import android.provider.Settings;
 import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceCategory;
 import android.support.v7.preference.PreferenceManager;
 import android.support.v7.preference.PreferenceViewHolder;
-import android.text.Spannable;
 import android.text.TextUtils;
-import android.text.style.TextAppearanceSpan;
 import android.util.Log;
 import android.view.ContextMenu;
 import android.view.ContextMenu.ContextMenuInfo;
@@ -53,8 +52,6 @@
 import android.view.MenuItem;
 import android.view.View;
 import android.widget.ProgressBar;
-import android.widget.TextView;
-import android.widget.TextView.BufferType;
 import android.widget.Toast;
 
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
@@ -102,7 +99,6 @@
     private static final int MENU_ID_FORGET = Menu.FIRST + 7;
     private static final int MENU_ID_MODIFY = Menu.FIRST + 8;
     private static final int MENU_ID_WRITE_NFC = Menu.FIRST + 9;
-    private static final int MENU_ID_CONFIGURE = Menu.FIRST + 10;
 
     public static final int WIFI_DIALOG_ID = 1;
     /* package */ static final int WPS_PBC_DIALOG_ID = 2;
@@ -115,6 +111,9 @@
     private static final String SAVED_WIFI_NFC_DIALOG_STATE = "wifi_nfc_dlg_state";
 
     private static final String PREF_KEY_EMPTY_WIFI_LIST = "wifi_empty_list";
+    private static final String PREF_KEY_ACCESS_POINTS = "access_points";
+    private static final String PREF_KEY_ADDITIONAL_SETTINGS = "additional_settings";
+    private static final String PREF_KEY_SAVED_NETWORKS = "saved_networks";
 
     protected WifiManager mWifiManager;
     private WifiManager.ActionListener mConnectListener;
@@ -152,7 +151,12 @@
     private HandlerThread mBgThread;
 
     private AccessPointPreference.UserBadgeCache mUserBadgeCache;
+
+    private PreferenceCategory mAccessPointsPreferenceCategory;
+    private PreferenceCategory mAdditionalSettingsPreferenceCategory;
     private Preference mAddPreference;
+    private Preference mSavedNetworksPreference;
+    private LinkablePreference mStatusMessagePreference;
 
     private MenuItem mScanMenuItem;
 
@@ -177,9 +181,18 @@
         getPreferenceManager().setPreferenceComparisonCallback(
                 new PreferenceManager.SimplePreferenceComparisonCallback());
         addPreferencesFromResource(R.xml.wifi_settings);
-        mAddPreference = new Preference(getContext());
+
+        mAccessPointsPreferenceCategory =
+                (PreferenceCategory) findPreference(PREF_KEY_ACCESS_POINTS);
+        mAdditionalSettingsPreferenceCategory =
+                (PreferenceCategory) findPreference(PREF_KEY_ADDITIONAL_SETTINGS);
+        mSavedNetworksPreference = findPreference(PREF_KEY_SAVED_NETWORKS);
+
+        Context prefContext = getPrefContext();
+        mAddPreference = new Preference(prefContext);
         mAddPreference.setIcon(R.drawable.ic_menu_add_inset);
         mAddPreference.setTitle(R.string.wifi_add_network);
+        mStatusMessagePreference = new LinkablePreference(prefContext);
 
         mUserBadgeCache = new AccessPointPreference.UserBadgeCache(getPackageManager());
 
@@ -305,7 +318,7 @@
     /**
      * @return new WifiEnabler or null (as overridden by WifiSettingsForSetupWizard)
      */
-    /* package */ WifiEnabler createWifiEnabler() {
+    private WifiEnabler createWifiEnabler() {
         final SettingsActivity activity = (SettingsActivity) getActivity();
         return new WifiEnabler(activity, activity.getSwitchBar(), mMetricsFeatureProvider);
     }
@@ -314,7 +327,6 @@
     public void onResume() {
         final Activity activity = getActivity();
         super.onResume();
-        removePreference("dummy");
         if (mWifiEnabler != null) {
             mWifiEnabler.resume(activity);
         }
@@ -346,14 +358,13 @@
      * @param menu
      */
     void addOptionsMenuItems(Menu menu) {
-        final boolean wifiIsEnabled = mWifiTracker.isWifiEnabled();
-        mScanMenuItem = menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.menu_stats_refresh);
-        mScanMenuItem.setEnabled(wifiIsEnabled)
-               .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
         menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced)
                 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
-        menu.add(Menu.NONE, MENU_ID_CONFIGURE, 0, R.string.wifi_menu_configure)
-                .setIcon(R.drawable.ic_settings_24dp)
+
+        final boolean wifiIsEnabled = mWifiTracker.isWifiEnabled();
+        mScanMenuItem = menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.menu_stats_refresh)
+                .setIcon(com.android.internal.R.drawable.ic_menu_refresh);
+        mScanMenuItem.setEnabled(wifiIsEnabled)
                 .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
     }
 
@@ -424,18 +435,6 @@
                             null);
                 }
                 return true;
-            case MENU_ID_CONFIGURE:
-                if (getActivity() instanceof SettingsActivity) {
-                    ((SettingsActivity) getActivity()).startPreferencePanel(
-                            ConfigureWifiSettings.class.getCanonicalName(), null,
-                            R.string.wifi_configure_titlebar, null, this, 0);
-                } else {
-                    startFragment(this, ConfigureWifiSettings.class.getCanonicalName(),
-                            R.string.wifi_configure_titlebar, -1 /* Do not request a results */,
-                            null);
-                }
-                return true;
-
         }
         return super.onOptionsItemSelected(item);
     }
@@ -622,10 +621,10 @@
         // Safeguard from some delayed event handling
         if (getActivity() == null) return;
         if (isUiRestricted()) {
+            mAccessPointsPreferenceCategory.removeAll();
             if (!isUiRestrictedByOnlyAdmin()) {
                 addMessagePreference(R.string.wifi_empty_list_user_restricted);
             }
-            getPreferenceScreen().removeAll();
             return;
         }
         final int wifiState = mWifiManager.getWifiState();
@@ -638,7 +637,8 @@
 
                 boolean hasAvailableAccessPoints = false;
                 int index = 0;
-                cacheRemoveAllPrefs(getPreferenceScreen());
+                mAccessPointsPreferenceCategory.removePreference(mStatusMessagePreference);
+                cacheRemoveAllPrefs(mAccessPointsPreferenceCategory);
                 for (AccessPoint accessPoint : accessPoints) {
                     // Ignore access points that are out of range.
                     if (accessPoint.getLevel() != -1) {
@@ -665,12 +665,12 @@
                             onPreferenceTreeClick(preference);
                             mOpenSsid = null;
                         }
-                        getPreferenceScreen().addPreference(preference);
+                        mAccessPointsPreferenceCategory.addPreference(preference);
                         accessPoint.setListener(this);
                         preference.refresh();
                     }
                 }
-                removeCachedPrefs(getPreferenceScreen());
+                removeCachedPrefs(mAccessPointsPreferenceCategory);
                 if (!hasAvailableAccessPoints) {
                     setProgressBarVisible(true);
                     Preference pref = new Preference(getContext()) {
@@ -683,14 +683,16 @@
                     };
                     pref.setSelectable(false);
                     pref.setSummary(R.string.wifi_empty_list_wifi_on);
-                    pref.setOrder(0);
+                    pref.setOrder(index++);
                     pref.setKey(PREF_KEY_EMPTY_WIFI_LIST);
-                    getPreferenceScreen().addPreference(pref);
-                    mAddPreference.setOrder(1);
-                    getPreferenceScreen().addPreference(mAddPreference);
+                    mAccessPointsPreferenceCategory.addPreference(pref);
+                    mAddPreference.setOrder(index++);
+                    mAccessPointsPreferenceCategory.addPreference(mAddPreference);
+                    setSavedNetworkPreferenceVisibility();
                 } else {
                     mAddPreference.setOrder(index++);
-                    getPreferenceScreen().addPreference(mAddPreference);
+                    mAccessPointsPreferenceCategory.addPreference(mAddPreference);
+                    setSavedNetworkPreferenceVisibility();
                     setProgressBarVisible(false);
                 }
                 if (mScanMenuItem != null) {
@@ -699,7 +701,7 @@
                 break;
 
             case WifiManager.WIFI_STATE_ENABLING:
-                getPreferenceScreen().removeAll();
+                mAccessPointsPreferenceCategory.removeAll();
                 setProgressBarVisible(true);
                 break;
 
@@ -710,6 +712,7 @@
 
             case WifiManager.WIFI_STATE_DISABLED:
                 setOffMessage();
+                setSavedNetworkPreferenceVisibility();
                 setProgressBarVisible(false);
                 if (mScanMenuItem != null) {
                     mScanMenuItem.setEnabled(false);
@@ -718,17 +721,20 @@
         }
     }
 
+    private void setSavedNetworkPreferenceVisibility() {
+        if (mWifiTracker.doSavedNetworksExist()) {
+            mAdditionalSettingsPreferenceCategory.addPreference(mSavedNetworksPreference);
+        } else {
+            mAdditionalSettingsPreferenceCategory.removePreference(mSavedNetworksPreference);
+        }
+    }
+
     private void setOffMessage() {
         if (isUiRestricted()) {
             if (!isUiRestrictedByOnlyAdmin()) {
                 addMessagePreference(R.string.wifi_empty_list_user_restricted);
             }
-            getPreferenceScreen().removeAll();
-            return;
-        }
-
-        TextView emptyTextView = getEmptyTextView();
-        if (emptyTextView == null) {
+            mAccessPointsPreferenceCategory.removeAll();
             return;
         }
 
@@ -744,35 +750,27 @@
         if (!wifiScanningMode) {
             // Show only the brief text if the user is not allowed to configure scanning settings,
             // or the scanning mode has been turned off.
-            emptyTextView.setText(briefText, BufferType.SPANNABLE);
+            mStatusMessagePreference.setTitle(briefText);
         } else {
-            // Append the description of scanning settings with link.
-            final StringBuilder contentBuilder = new StringBuilder();
-            contentBuilder.append(briefText);
-            contentBuilder.append("\n\n");
-            contentBuilder.append(getText(R.string.wifi_scan_notify_text));
-            LinkifyUtils.linkify(emptyTextView, contentBuilder, new LinkifyUtils.OnClickListener() {
+            LinkifyUtils.OnClickListener clickListener = new LinkifyUtils.OnClickListener() {
                 @Override
                 public void onClick() {
-                    final SettingsActivity activity =
-                            (SettingsActivity) WifiSettings.this.getActivity();
+                    final SettingsActivity activity = (SettingsActivity) getActivity();
                     activity.startPreferencePanel(ScanningSettings.class.getName(), null,
                             R.string.location_scanning_screen_title, null, null, 0);
                 }
-            });
+            };
+            mStatusMessagePreference.setText(
+                    briefText, getText(R.string.wifi_scan_notify_text), clickListener);
         }
-        // Embolden and enlarge the brief description anyway.
-        Spannable boldSpan = (Spannable) emptyTextView.getText();
-        boldSpan.setSpan(
-                new TextAppearanceSpan(getActivity(), android.R.style.TextAppearance_Medium), 0,
-                briefText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
-        getPreferenceScreen().removeAll();
+        mAccessPointsPreferenceCategory.removeAll();
+        mAccessPointsPreferenceCategory.addPreference(mStatusMessagePreference);
     }
 
     private void addMessagePreference(int messageId) {
-        TextView emptyTextView = getEmptyTextView();
-        if (emptyTextView != null) emptyTextView.setText(messageId);
-        getPreferenceScreen().removeAll();
+        mStatusMessagePreference.setTitle(messageId);
+        mAccessPointsPreferenceCategory.removeAll();
+        mAccessPointsPreferenceCategory.addPreference(mStatusMessagePreference);
     }
 
     protected void setProgressBarVisible(boolean visible) {
diff --git a/tests/robotests/src/com/android/settings/accounts/AccountDetailDashboardFragmentTest.java b/tests/robotests/src/com/android/settings/accounts/AccountDetailDashboardFragmentTest.java
index 3ba4d02..31090be 100644
--- a/tests/robotests/src/com/android/settings/accounts/AccountDetailDashboardFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/accounts/AccountDetailDashboardFragmentTest.java
@@ -82,7 +82,8 @@
 
     @Test
     public void testCategory_isAccount() {
-        assertThat(mFragment.getCategoryKey()).isEqualTo(CategoryKey.CATEGORY_ACCOUNT);
+        assertThat(new AccountDetailDashboardFragment().getCategoryKey())
+                .isEqualTo(CategoryKey.CATEGORY_ACCOUNT);
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/applications/AppWithAdminGrantedPermissionsCounterTest.java b/tests/robotests/src/com/android/settings/applications/AppWithAdminGrantedPermissionsCounterTest.java
index 9fc416d..3dd3a65 100644
--- a/tests/robotests/src/com/android/settings/applications/AppWithAdminGrantedPermissionsCounterTest.java
+++ b/tests/robotests/src/com/android/settings/applications/AppWithAdminGrantedPermissionsCounterTest.java
@@ -18,7 +18,6 @@
 
 import android.app.admin.DevicePolicyManager;
 import android.content.Context;
-import android.content.pm.IPackageManager;
 import android.content.pm.PackageManager;
 import android.content.pm.UserInfo;
 import android.os.Build;
@@ -79,7 +78,7 @@
 
     @Mock private Context mContext;
     @Mock private PackageManagerWrapper mPackageManager;
-    @Mock private IPackageManager mPackageManagerService;
+    @Mock private IPackageManagerWrapper mPackageManagerService;
     @Mock private DevicePolicyManagerWrapper mDevicePolicyManager;
     private List<UserInfo> mUsersToCount;
 
diff --git a/tests/robotests/src/com/android/settings/applications/ApplicationFeatureProviderImplTest.java b/tests/robotests/src/com/android/settings/applications/ApplicationFeatureProviderImplTest.java
index aba4a12..2f344dc 100644
--- a/tests/robotests/src/com/android/settings/applications/ApplicationFeatureProviderImplTest.java
+++ b/tests/robotests/src/com/android/settings/applications/ApplicationFeatureProviderImplTest.java
@@ -18,12 +18,15 @@
 
 import android.app.admin.DevicePolicyManager;
 import android.content.Context;
-import android.content.pm.IPackageManager;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
 import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
 import android.content.pm.UserInfo;
 import android.os.Build;
 import android.os.UserHandle;
 import android.os.UserManager;
+import android.util.ArraySet;
 
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
@@ -39,10 +42,11 @@
 import org.robolectric.shadows.ShadowApplication;
 
 import java.util.Arrays;
+import java.util.Set;
 
 import static com.google.common.truth.Truth.assertThat;
 import static org.mockito.Mockito.when;
-import org.robolectric.shadows.ShadowApplication;
+
 /**
  * Tests for {@link ApplicationFeatureProviderImpl}.
  */
@@ -66,7 +70,7 @@
     private @Mock UserManager mUserManager;
     private @Mock Context mContext;
     private @Mock PackageManagerWrapper mPackageManager;
-    @Mock private IPackageManager mPackageManagerService;
+    @Mock private IPackageManagerWrapper mPackageManagerService;
     @Mock private DevicePolicyManagerWrapper mDevicePolicyManager;
 
     private ApplicationFeatureProvider mProvider;
@@ -139,6 +143,43 @@
 
     }
 
+    @Test
+    public void testFindPersistentPreferredActivities() throws Exception {
+        when(mUserManager.getUserProfiles()).thenReturn(Arrays.asList(new UserHandle(MAIN_USER_ID),
+                new UserHandle(MANAGED_PROFILE_ID)));
+
+        final Intent viewIntent = new Intent(Intent.ACTION_VIEW);
+        final Intent editIntent = new Intent(Intent.ACTION_EDIT);
+        final Intent sendIntent = new Intent(Intent.ACTION_SEND);
+
+        final ResolveInfo app1 = createResolveInfo(APP_1);
+        final ResolveInfo app2 = createResolveInfo(APP_2);
+        when(mPackageManagerService.findPersistentPreferredActivity(viewIntent, MAIN_USER_ID))
+                .thenReturn(app1);
+        when(mPackageManagerService.findPersistentPreferredActivity(viewIntent, MANAGED_PROFILE_ID))
+                .thenReturn(app1);
+        when(mPackageManagerService.findPersistentPreferredActivity(editIntent, MAIN_USER_ID))
+                .thenReturn(null);
+        when(mPackageManagerService.findPersistentPreferredActivity(editIntent, MANAGED_PROFILE_ID))
+                .thenReturn(app2);
+        when(mPackageManagerService.findPersistentPreferredActivity(sendIntent, MAIN_USER_ID))
+                .thenReturn(app1);
+        when(mPackageManagerService.findPersistentPreferredActivity(sendIntent, MANAGED_PROFILE_ID))
+                .thenReturn(null);
+
+        final Set<ApplicationFeatureProvider.PersistentPreferredActivityInfo> expectedActivities
+                = new ArraySet<>();
+        expectedActivities.add(new ApplicationFeatureProvider.PersistentPreferredActivityInfo(APP_1,
+                MAIN_USER_ID));
+        expectedActivities.add(new ApplicationFeatureProvider.PersistentPreferredActivityInfo(APP_1,
+                MANAGED_PROFILE_ID));
+        expectedActivities.add(new ApplicationFeatureProvider.PersistentPreferredActivityInfo(APP_2,
+                MANAGED_PROFILE_ID));
+
+        assertThat(mProvider.findPersistentPreferredActivities(
+                new Intent[] {viewIntent, editIntent, sendIntent})).isEqualTo(expectedActivities);
+    }
+
     private void setUpUsersAndInstalledApps() {
         when(mUserManager.getUsers(true)).thenReturn(Arrays.asList(
                 new UserInfo(MAIN_USER_ID, "main", UserInfo.FLAG_ADMIN),
@@ -156,4 +197,12 @@
                         ApplicationTestUtils.buildInfo(APP_2_UID, APP_2, 0 /* flags */,
                                 Build.VERSION_CODES.LOLLIPOP)));
     }
+
+    private ResolveInfo createResolveInfo(String packageName) {
+        final ActivityInfo activityInfo = new ActivityInfo();
+        activityInfo.packageName = packageName;
+        final ResolveInfo resolveInfo = new ResolveInfo();
+        resolveInfo.activityInfo = activityInfo;
+        return resolveInfo;
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/dashboard/DashboardFragmentTest.java b/tests/robotests/src/com/android/settings/dashboard/DashboardFragmentTest.java
index d479e0a..327575e 100644
--- a/tests/robotests/src/com/android/settings/dashboard/DashboardFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/dashboard/DashboardFragmentTest.java
@@ -26,7 +26,6 @@
 import com.android.settings.core.PreferenceController;
 import com.android.settings.overlay.FeatureFactory;
 import com.android.settings.testutils.FakeFeatureFactory;
-import com.android.settingslib.drawer.CategoryKey;
 import com.android.settingslib.drawer.DashboardCategory;
 import com.android.settingslib.drawer.Tile;
 
@@ -200,11 +199,6 @@
         }
 
         @Override
-        protected String getCategoryKey() {
-            return CategoryKey.CATEGORY_HOMEPAGE;
-        }
-
-        @Override
         public PreferenceScreen getPreferenceScreen() {
             return mScreen;
         }
diff --git a/tests/robotests/src/com/android/settings/enterprise/EnterpriseInstalledPackagesPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/EnterpriseInstalledPackagesPreferenceControllerTest.java
index 3dd1fd7..b55b512 100644
--- a/tests/robotests/src/com/android/settings/enterprise/EnterpriseInstalledPackagesPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/EnterpriseInstalledPackagesPreferenceControllerTest.java
@@ -81,6 +81,10 @@
         final Preference preference = new Preference(mContext, null, 0, 0);
         preference.setVisible(true);
 
+        setNumberOfEnterpriseInstalledPackages(0);
+        mController.updateState(preference);
+        assertThat(preference.isVisible()).isFalse();
+
         setNumberOfEnterpriseInstalledPackages(20);
         when(mContext.getResources().getQuantityString(
                 R.plurals.enterprise_privacy_number_enterprise_installed_packages, 20, 20))
@@ -88,10 +92,6 @@
         mController.updateState(preference);
         assertThat(preference.getTitle()).isEqualTo("20 packages");
         assertThat(preference.isVisible()).isTrue();
-
-        setNumberOfEnterpriseInstalledPackages(0);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isFalse();
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/enterprise/EnterprisePrivacySettingsTest.java b/tests/robotests/src/com/android/settings/enterprise/EnterprisePrivacySettingsTest.java
index de4d02e..2559769 100644
--- a/tests/robotests/src/com/android/settings/enterprise/EnterprisePrivacySettingsTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/EnterprisePrivacySettingsTest.java
@@ -73,7 +73,7 @@
         final List<PreferenceController> controllers = mSettings.getPreferenceControllers(
                 ShadowApplication.getInstance().getApplicationContext());
         assertThat(controllers).isNotNull();
-        assertThat(controllers.size()).isEqualTo(11);
+        assertThat(controllers.size()).isEqualTo(12);
         assertThat(controllers.get(0)).isInstanceOf(InstalledPackagesPreferenceController.class);
         assertThat(controllers.get(1)).isInstanceOf(NetworkLogsPreferenceController.class);
         assertThat(controllers.get(2)).isInstanceOf(BugReportsPreferenceController.class);
@@ -87,9 +87,11 @@
         assertThat(controllers.get(7)).isInstanceOf(
                 AdminGrantedCameraPermissionPreferenceController.class);
         assertThat(controllers.get(8)).isInstanceOf(
-                AlwaysOnVpnPrimaryUserPreferenceController.class);
+                EnterpriseSetDefaultAppsPreferenceController.class);
         assertThat(controllers.get(9)).isInstanceOf(
+                AlwaysOnVpnPrimaryUserPreferenceController.class);
+        assertThat(controllers.get(10)).isInstanceOf(
                 AlwaysOnVpnManagedProfilePreferenceController.class);
-        assertThat(controllers.get(10)).isInstanceOf(GlobalHttpProxyPreferenceController.class);
+        assertThat(controllers.get(11)).isInstanceOf(GlobalHttpProxyPreferenceController.class);
     }
 }
diff --git a/tests/robotests/src/com/android/settings/enterprise/EnterpriseSetDefaultAppsPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/EnterpriseSetDefaultAppsPreferenceControllerTest.java
new file mode 100644
index 0000000..84520a5
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/enterprise/EnterpriseSetDefaultAppsPreferenceControllerTest.java
@@ -0,0 +1,170 @@
+/*
+ * Copyright (C) 2017 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.enterprise;
+
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.Resources;
+import android.net.Uri;
+import android.provider.ContactsContract;
+import android.provider.MediaStore;
+import android.support.v7.preference.Preference;
+import android.util.ArraySet;
+
+import com.android.settings.R;
+import com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.TestConfig;
+import com.android.settings.applications.ApplicationFeatureProvider;
+import com.android.settings.testutils.FakeFeatureFactory;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentMatcher;
+import org.mockito.Answers;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.annotation.Config;
+
+import java.util.Set;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Mockito.anyObject;
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests for {@link EnterpriseSetDefaultAppsPreferenceController}.
+ */
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public final class EnterpriseSetDefaultAppsPreferenceControllerTest {
+
+    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
+    private Context mContext;
+    private FakeFeatureFactory mFeatureFactory;
+
+    private EnterpriseSetDefaultAppsPreferenceController mController;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        FakeFeatureFactory.setupForTest(mContext);
+        mFeatureFactory = (FakeFeatureFactory) FakeFeatureFactory.getFactory(mContext);
+        mController = new EnterpriseSetDefaultAppsPreferenceController(mContext);
+    }
+
+    private static Intent buildIntent(String action, String category, String protocol,
+            String type) {
+        final Intent intent = new Intent(action);
+        if (category != null) {
+            intent.addCategory(category);
+        }
+        if (protocol != null) {
+            intent.setData(Uri.parse(protocol));
+        }
+        if (type != null) {
+            intent.setType(type);
+        }
+        return intent;
+    }
+
+    private void setEnterpriseSetDefaultApps(Intent[] intents, int number) {
+        final Set<ApplicationFeatureProvider.PersistentPreferredActivityInfo> apps
+                = new ArraySet<>(number);
+        for (int i = 0; i < number; i++) {
+            apps.add(new ApplicationFeatureProvider.PersistentPreferredActivityInfo("app", i));
+        }
+        when(mFeatureFactory.applicationFeatureProvider.findPersistentPreferredActivities(
+                argThat(new MatchesIntents(intents)))).thenReturn(apps);
+    }
+
+    @Test
+    public void testUpdateState() {
+        final Preference preference = new Preference(mContext, null, 0, 0);
+        preference.setVisible(true);
+
+        when(mFeatureFactory.applicationFeatureProvider.findPersistentPreferredActivities(
+                anyObject())).thenReturn(
+                        new ArraySet<ApplicationFeatureProvider.PersistentPreferredActivityInfo>());
+        mController.updateState(preference);
+        assertThat(preference.isVisible()).isFalse();
+
+        setEnterpriseSetDefaultApps(new Intent[] {buildIntent(Intent.ACTION_VIEW,
+                Intent.CATEGORY_BROWSABLE, "http:", null)}, 1);
+        setEnterpriseSetDefaultApps(new Intent[] {new Intent(MediaStore.ACTION_IMAGE_CAPTURE),
+                new Intent(MediaStore.ACTION_VIDEO_CAPTURE)}, 2);
+        setEnterpriseSetDefaultApps(new Intent[] {buildIntent(Intent.ACTION_VIEW, null, "geo:",
+                null)}, 4);
+        setEnterpriseSetDefaultApps(new Intent[] {new Intent(Intent.ACTION_SENDTO),
+                new Intent(Intent.ACTION_SEND), new Intent(Intent.ACTION_SEND_MULTIPLE)}, 8);
+        setEnterpriseSetDefaultApps(new Intent[] {buildIntent(Intent.ACTION_INSERT, null, null,
+                "vnd.android.cursor.dir/event")}, 16);
+        setEnterpriseSetDefaultApps(new Intent[] {buildIntent(Intent.ACTION_PICK, null, null,
+                ContactsContract.Contacts.CONTENT_TYPE)}, 32);
+        setEnterpriseSetDefaultApps(new Intent[] {new Intent(Intent.ACTION_DIAL),
+                new Intent(Intent.ACTION_CALL)}, 64);
+        when(mContext.getResources().getQuantityString(
+                R.plurals.enterprise_privacy_number_enterprise_set_default_apps, 127, 127))
+                .thenReturn("127 apps");
+        mController.updateState(preference);
+        assertThat(preference.getTitle()).isEqualTo("127 apps");
+        assertThat(preference.isVisible()).isTrue();
+    }
+
+    @Test
+    public void testIsAvailable() {
+        assertThat(mController.isAvailable()).isTrue();
+    }
+
+    @Test
+    public void testHandlePreferenceTreeClick() {
+        assertThat(mController.handlePreferenceTreeClick(new Preference(mContext, null, 0, 0)))
+                .isFalse();
+    }
+
+    @Test
+    public void testGetPreferenceKey() {
+        assertThat(mController.getPreferenceKey())
+                .isEqualTo("number_enterprise_set_default_apps");
+    }
+
+    private static class MatchesIntents extends ArgumentMatcher<Intent[]> {
+        private final Intent[] mExpectedIntents;
+
+        MatchesIntents(Intent[] intents) {
+            mExpectedIntents = intents;
+        }
+
+        @Override
+        public boolean matches(Object object) {
+            final Intent[] actualIntents = (Intent[]) object;
+            if (actualIntents == null) {
+                return false;
+            }
+            if (actualIntents.length != mExpectedIntents.length) {
+                return false;
+            }
+            for (int i = 0; i < mExpectedIntents.length; i++) {
+                if (!mExpectedIntents[i].filterEquals(actualIntents[i])) {
+                    return false;
+                }
+            }
+            return true;
+        }
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/network/NetworkDashboardFragmentTest.java b/tests/robotests/src/com/android/settings/network/NetworkDashboardFragmentTest.java
index b30e3ff..dc96ed6 100644
--- a/tests/robotests/src/com/android/settings/network/NetworkDashboardFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/network/NetworkDashboardFragmentTest.java
@@ -21,6 +21,7 @@
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
 import com.android.settings.accounts.UserAndAccountDashboardFragment;
+import com.android.settings.dashboard.DashboardFragmentRegistry;
 import com.android.settings.testutils.FakeFeatureFactory;
 import com.android.settingslib.drawer.CategoryKey;
 import org.junit.Before;
diff --git a/tests/robotests/src/com/android/settings/wifi/SavedNetworkPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/wifi/SavedNetworkPreferenceControllerTest.java
deleted file mode 100644
index 657c21e..0000000
--- a/tests/robotests/src/com/android/settings/wifi/SavedNetworkPreferenceControllerTest.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2017 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.wifi;
-
-import android.content.Context;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiManager;
-
-import com.android.settings.SettingsRobolectricTestRunner;
-import com.android.settings.TestConfig;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.robolectric.annotation.Config;
-
-import java.util.List;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-@RunWith(SettingsRobolectricTestRunner.class)
-@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
-public class SavedNetworkPreferenceControllerTest {
-
-    @Mock
-    private Context mContext;
-    @Mock
-    private WifiManager mWifiManager;
-
-    private SavedNetworkPreferenceController mController;
-
-    @Before
-    public void setUp() {
-        MockitoAnnotations.initMocks(this);
-
-        mController = new SavedNetworkPreferenceController(mContext, mWifiManager);
-    }
-
-    @Test
-    public void isAvailable_noSavedNetwork_shouldReturnFalse() {
-        when(mWifiManager.getConfiguredNetworks()).thenReturn(null);
-        assertThat(mController.isAvailable()).isFalse();
-    }
-
-    @Test
-    public void isAvailable_hasSavedNetwork_shouldReturnTrue() {
-        List<WifiConfiguration> configs = mock(List.class);
-        when(configs.isEmpty()).thenReturn(false);
-        when(mWifiManager.getConfiguredNetworks()).thenReturn(configs);
-
-        assertThat(mController.isAvailable()).isTrue();
-    }
-}