Merge "Misc search summary text updates."
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 7b5ea52..07d8e23 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -1941,7 +1941,7 @@
                   android:label="@string/development_settings_title"
                   android:targetActivity="Settings$DevelopmentSettingsActivity">
             <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
-                android:value="com.android.settings.DevelopmentSettings" />
+                android:value="com.android.settings.development.DevelopmentSettings" />
         </activity-alias>
 
         <activity android:name=".development.AppPicker"
@@ -2496,6 +2496,18 @@
                 android:value="com.android.settings.applications.PictureInPictureSettings" />
         </activity>
 
+        <activity android:name="Settings$AppPictureInPictureSettingsActivity"
+            android:label="@string/picture_in_picture_title"
+            android:taskAffinity="">
+            <intent-filter>
+                <action android:name="android.settings.PICTURE_IN_PICTURE_SETTINGS" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <data android:scheme="package" />
+            </intent-filter>
+            <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
+                android:value="com.android.settings.applications.PictureInPictureDetails" />
+        </activity>
+
         <activity android:name="Settings$ZenAccessSettingsActivity"
                   android:label="@string/manage_zen_access_title"
                   android:taskAffinity="">
diff --git a/res/layout/app_details.xml b/res/layout/app_details.xml
index 15cb38a..00d4cca 100644
--- a/res/layout/app_details.xml
+++ b/res/layout/app_details.xml
@@ -18,7 +18,7 @@
 <LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/app_snippet"
-    style="@style/AppInfoHeader"
+    style="@style/EntityHeader"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_gravity="center_horizontal|top"
@@ -79,7 +79,7 @@
 
             <TextView
                 android:id="@+id/app_detail_title"
-                style="@style/TextAppearance.AppInfoTitle"
+                style="@style/TextAppearance.EntityHeaderTitle"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:singleLine="false"
@@ -89,22 +89,24 @@
 
             <TextView
                 android:id="@+id/install_type"
-                style="@style/TextAppearance.AppInfoSummary"
                 android:visibility="gone"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:gravity="start"
                 android:singleLine="true"
-                android:ellipsize="marquee"/>
+                android:ellipsize="marquee"
+                android:textAppearance="@android:style/TextAppearance.Material.Body1"
+                android:textColor="?android:attr/textColorSecondary"/>
 
             <TextView
                 android:id="@+id/app_detail_summary"
-                style="@style/TextAppearance.AppInfoSummary"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:gravity="start"
                 android:singleLine="true"
-                android:ellipsize="marquee"/>
+                android:ellipsize="marquee"
+                android:textAppearance="@android:style/TextAppearance.Material.Body1"
+                android:textColor="?android:attr/textColorSecondary"/>
 
         </LinearLayout>
 
diff --git a/res/layout/battery_usage_graph.xml b/res/layout/battery_usage_graph.xml
index bd6e7a5..80f966b 100644
--- a/res/layout/battery_usage_graph.xml
+++ b/res/layout/battery_usage_graph.xml
@@ -18,6 +18,7 @@
     xmlns:settings="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
+    android:paddingTop="16dp"
     android:paddingStart="@dimen/preference_no_icon_padding_start"
     android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
     android:orientation="vertical">
@@ -26,22 +27,16 @@
         android:id="@+id/charge"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
+        android:layout_marginBottom="16dp"
         android:textAppearance="?android:attr/textAppearanceLarge"
         android:textSize="36sp"
         android:textColor="?android:attr/colorAccent" />
 
-    <TextView
-        android:id="@+id/estimation"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:paddingBottom="8dp"
-        android:textAppearance="?android:attr/textAppearanceMedium"
-        android:textColor="?android:attr/textColorSecondary" />
-
     <com.android.settingslib.graph.UsageView
         android:id="@+id/battery_usage"
         android:layout_width="match_parent"
         android:layout_height="141dp"
+        android:layout_marginBottom="16dp"
         settings:sideLabels="@array/battery_labels"
         android:colorAccent="?android:attr/colorAccent"
         android:gravity="end"
diff --git a/res/layout/storage_item.xml b/res/layout/storage_item.xml
index de73543..520f5ce 100644
--- a/res/layout/storage_item.xml
+++ b/res/layout/storage_item.xml
@@ -31,25 +31,25 @@
         android:layout_height="wrap_content"
         android:orientation="horizontal">
 
-      <TextView
-          android:id="@android:id/title"
-          android:layout_width="0dp"
-          android:layout_height="wrap_content"
-          android:layout_weight="1"
-          android:singleLine="true"
-          android:textAppearance="@android:style/TextAppearance.Material.Subhead"
-          android:textAlignment="viewStart"
-          android:ellipsize="marquee"
-          android:fadingEdge="horizontal" />
+        <TextView
+            android:id="@android:id/title"
+            android:layout_width="0dp"
+            android:layout_height="wrap_content"
+            android:layout_weight="1"
+            android:singleLine="true"
+            android:textAppearance="@android:style/TextAppearance.Material.Subhead"
+            android:textAlignment="viewStart"
+            android:ellipsize="marquee"
+            android:fadingEdge="horizontal" />
 
-      <TextView
-          android:id="@android:id/summary"
-          android:layout_width="wrap_content"
-          android:layout_height="wrap_content"
-          android:textAlignment="viewStart"
-          android:textAppearance="@android:style/TextAppearance.Material.Body1"
-          android:textColor="?android:attr/textColorSecondaryNoDisable"
-          android:maxLines="10" />
+        <TextView
+            android:id="@android:id/summary"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:textAlignment="viewStart"
+            android:textAppearance="@android:style/TextAppearance.Material.Body1"
+            android:textColor="?android:attr/textColorSecondaryNoDisable"
+            android:maxLines="10" />
 
     </LinearLayout>
 
diff --git a/res/layout/storage_item_alternate.xml b/res/layout/storage_item_alternate.xml
deleted file mode 100644
index b41c82b..0000000
--- a/res/layout/storage_item_alternate.xml
+++ /dev/null
@@ -1,56 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 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.
--->
-
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-              android:layout_width="match_parent"
-              android:layout_height="wrap_content"
-              android:orientation="vertical"
-              android:minHeight="?android:attr/listPreferredItemHeightSmall"
-              android:gravity="center_vertical"
-              android:paddingStart="@dimen/preference_no_icon_padding_start"
-              android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
-              android:paddingTop="16dip"
-              android:paddingBottom="16dip"
-              android:background="?android:attr/selectableItemBackground">
-
-    <LinearLayout
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:orientation="horizontal">
-
-        <TextView
-            android:id="@android:id/title"
-            android:layout_width="0dp"
-            android:layout_height="wrap_content"
-            android:layout_weight="1"
-            android:singleLine="true"
-            android:textAppearance="@android:style/TextAppearance.Material.Subhead"
-            android:textAlignment="viewStart"
-            android:ellipsize="marquee"
-            android:fadingEdge="horizontal" />
-
-        <TextView
-            android:id="@android:id/summary"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:textAlignment="viewStart"
-            android:textAppearance="@android:style/TextAppearance.Material.Body1"
-            android:textColor="?android:attr/textColorSecondaryNoDisable"
-            android:maxLines="10" />
-
-    </LinearLayout>
-
-</LinearLayout>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 29cef39..b6507d0 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -71,7 +71,7 @@
     <!-- Wifi Calling provisioning flag on. Only shown in diagnostic screen, so precise translation is not needed. -->
     <string name="wfc_provisioned_switch_string">Wifi Calling Provisioned</string>
 
-    <!-- Cell Radio Power. Only shown in diagnostic screen, so precise translation is not needed. -->
+    <!-- Title for controlling on/off for Mobile phone's radio power. Only shown in diagnostic screen, so precise translation is not needed. -->
     <string name="radio_info_radio_power">Mobile Radio Power</string>
 
     <!-- Phone Info screen. Menu item label.  Used for diagnostic info screens, precise translation isn't needed -->
@@ -629,7 +629,7 @@
     <string name="calls_title">Calls</string>
     <!-- check box SMS Messges title [CHAR LIMIT=30] -->
     <string name="sms_messages_title">SMS messages</string>
-    <!-- check box cellular data summary [CHAR LIMIT=41] -->
+    <!-- check box cellular data summary [CHAR LIMIT=85] -->
     <string name="cellular_data_summary">Allow data usage over mobile network</string>
     <!-- check box to allow data usage when roaming [CHAR LIMIT=41] -->
     <string name="allow_data_usage_title">Allow data usage when roaming</string>
@@ -1300,12 +1300,12 @@
     <!-- Toast shown when lock pattern or password successfully setup. [CHAR LIMIT=64] -->
     <string name="lock_setup" msgid="5507462851158901718">Setup is complete.</string>
 
-    <!-- In the security screen, the header title for settings related to device admins -->
-    <string name="device_admin_title">Device administration</string>
-
     <!-- Title of preference to manage device admins -->
     <string name="manage_device_admin">Device admin apps</string>
 
+    <!-- Summary of preference to manage device administrators, informing the user that currently no device administrator apps are installed and active -->
+    <string name="number_of_device_admins_none">No active apps</string>
+
     <!-- Summary of preference to manage device administrators, informing the user how many device administrator apps are installed and active -->
     <plurals name="number_of_device_admins">
         <item quantity="one"><xliff:g id="count">%d</xliff:g> active app</item>
@@ -1639,7 +1639,7 @@
     <string name="wifi_switch_away_when_unvalidated">Switch to mobile data if Wi\u2011Fi loses Internet access.</string>
     <!-- Preference title for option to automatically switch away from bad wifi networks [CHAR LIMIT=60]-->
     <string name="wifi_cellular_data_fallback_title">Switch to mobile data automatically</string>
-    <!-- Preference summary for option to automatically switch away from bad wifi networks [CHAR LIMIT=None]-->
+    <!-- Preference summary to automatically switch away from bad wifi networks [CHAR LIMIT=None]-->
     <string name="wifi_cellular_data_fallback_summary">Use mobile 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>
@@ -1806,7 +1806,8 @@
 
     <!-- Dialog text to tell the user that the selected network has lost Internet access, and asking the user whether they want to avoid this network. -->
     <string name="lost_internet_access_title">Wi\u2011Fi is not connected to the Internet</string>
-    <string name="lost_internet_access_text">You can switch to the mobile network whenever Wi\u2011Fi has a bad connection. Data usage may apply.</string>
+    <string name="lost_internet_access_text">You can switch to the mobile network whenever Wi\u2011Fi has a bad connection. Data usage charges may apply.</string>
+    <!-- Button text to let user switch to mobile data -->
     <string name="lost_internet_access_switch">Switch to mobile</string>
     <string name="lost_internet_access_cancel">Stay on Wi\u2011Fi</string>
     <string name="lost_internet_access_persist">Never show again</string>
@@ -3366,20 +3367,25 @@
     <string name="install_applications">Unknown sources</string>
     <!-- Applications settings screen, setting check box title. If checked, the system allows installation of applications that are downloaded from random places, such as web sites.  [CHAR LIMIT=30] -->
     <string name="install_applications_title">Allow all app sources</string>
-    <!-- Applications settings screen, setting check box summary.  This is the summary for "Unknown sources" checkbox  [CHAR LIMIT=65] -->
-    <string name="install_unknown_applications_title">Lets you install apps from sources other than Google Play</string>
-    <!-- Applications settings screen, setting check box summary.  This is the summary for "Unknown sources" checkbox  -->
-    <string name="install_unknown_applications">Allow installation of apps from unknown sources</string>
-    <!-- Applications settings screen, message text of alert that appears if user selects the "Unknown sources" check box -->
-    <string name="install_all_warning" product="tablet">Your tablet and personal data are more vulnerable to attack by apps
- from unknown sources. You agree that you are solely responsible for any
- damage to your tablet or loss of data that may result from using
- these apps.</string>
-    <!-- Applications settings screen, message text of alert that appears if user selects the "Unknown sources" check box -->
-    <string name="install_all_warning" product="default">Your phone and personal data are more vulnerable to attack by apps
- from unknown sources. You agree that you are solely responsible for any
- damage to your phone or loss of data that may result from using
- these apps.</string>
+
+    <!-- Warning that appears below the unknown sources switch in settings -->
+    <string name="install_all_warning" product="tablet">
+        Your tablet and personal data are more vulnerable
+        to attack by unknown apps. By installing apps from
+        this source, you agree that you are responsible for
+        any damage to your tablet or loss of data that may
+        result from their use.
+    </string>
+
+    <!-- Warning that appears below the unknown sources switch in settings -->
+    <string name="install_all_warning" product="default">
+        Your phone and personal data are more vulnerable
+        to attack by unknown apps. By installing apps from
+        this source, you agree that you are responsible for
+        any damage to your phone or loss of data that may
+        result from their use.
+    </string>
+
     <!-- Applications settings screen, setting check box title. If checked, applications show more settings options. -->
     <string name="advanced_settings">Advanced settings</string>
     <!-- Applications settings screen, setting check box summary.  This is the summary for "Advanced settings" checkbox  -->
@@ -3811,7 +3817,7 @@
     <!-- Title for the 'keyboard and input methods' preference category. [CHAR LIMIT=45] -->
     <string name="keyboard_and_input_methods_category">Keyboard and input methods</string>
     <!-- Title for the 'virtual keyboard' preference sub-screen. [CHAR LIMIT=35] -->
-    <string name="virtual_keyboard_category">Virtual keyboard</string>
+    <string name="virtual_keyboard_category">Virtual keyboards</string>
     <!-- Title for the 'available virtual keyboard' preference sub-screen. [CHAR LIMIT=35] -->
     <string name="available_virtual_keyboard_category">Available virtual keyboard</string>
     <!-- Title for the button to trigger the 'Manage keyboards' preference sub-screen, where the user can turn on/off installed virtual keyboards.[CHAR LIMIT=35] -->
@@ -5281,7 +5287,7 @@
     <!-- Checkbox label that restricts background data usage of a specific application. [CHAR LIMIT=40] -->
     <string name="data_usage_app_restrict_background">Background data</string>
     <!-- Summary message for checkbox that restricts background data usage of a specific application. [CHAR LIMIT=NONE] -->
-    <string name="data_usage_app_restrict_background_summary">Enable usage of Mobile data in the background</string>
+    <string name="data_usage_app_restrict_background_summary">Enable usage of mobile data in the background</string>
     <!-- Summary message for checkbox that restricts background data usage of a specific application when no networks have been limited. [CHAR LIMIT=84] -->
     <string name="data_usage_app_restrict_background_summary_disabled">To restrict background data for this app, first set a mobile data limit.</string>
     <!-- Title of dialog shown when user restricts background data usage of a specific application. [CHAR LIMIT=48] -->
@@ -6463,8 +6469,17 @@
     <!-- Apps > App Details > Advanced section string title. [CHAR LIMIT=NONE] -->
     <string name="picture_in_picture_app_detail_title">Picture-in-picture</string>
 
-    <!-- Apps > App Details > Advanced section string description. [CHAR LIMIT=NONE] -->
-    <string name="picture_in_picture_app_detail_summary">Permit entering picture-in-picture when leaving app</string>
+    <!-- Apps > App Details > Picture-in-picture > Switch title. [CHAR LIMIT=NONE] -->
+    <string name="picture_in_picture_app_detail_switch">Allow picture-in-picture</string>
+
+    <!-- Apps > App Details > Picture-in-picture > Description. [CHAR LIMIT=NONE] -->
+    <string name="picture_in_picture_app_detail_summary">Allow this app to create a picture-in-picture window while the app is open or after you leave it (for example, to continue watching a video).  This window displays on top of other apps you're using.</string>
+
+    <!-- Summary of app allowed to enter picture-in-picture. [CHAR LIMIT=60] -->
+    <string name="picture_in_picture_on">Yes</string>
+
+    <!-- Summary of app not allowed to enter picture-in-picture. [CHAR LIMIT=60] -->
+    <string name="picture_in_picture_off">No</string>
 
     <!-- Sound & notification > Advanced section: Title for managing Do Not Disturb access option. [CHAR LIMIT=40] -->
     <string name="manage_zen_access_title">Do Not Disturb access</string>
@@ -7387,9 +7402,9 @@
     <string name="system_alert_window_off">No</string>
 
     <!-- Title for settings screen for controlling apps that can install other apps on device [CHAR LIMIT=50] -->
-    <string name="install_other_apps">Install other apps</string>
+    <string name="install_other_apps">Install unknown apps</string>
     <!-- Keywords for setting screen for controlling apps that can install other apps on device -->
-    <string name="keywords_install_other_apps">install apps external unknown sources</string>
+    <string name="keywords_install_other_apps">install apps unknown sources</string>
 
     <!-- Write Settings settings -->
     <!-- Settings title in main settings screen for WRITE_SETTINGS [CHAR LIMIT=30] -->
@@ -7422,7 +7437,7 @@
     <!-- Summary of app not trusted to install apps [CHAR LIMIT=45] -->
     <string name="external_source_untrusted">No</string>
     <!-- Title of switch preference that controls whether an external app source is trusted or not [CHAR LIMIT=50] -->
-    <string name="external_source_switch_title">Trust apps from this source</string>
+    <string name="external_source_switch_title">Allow app installs</string>
 
     <!-- Title of setting that controls gesture to open camera [CHAR LIMIT=40] -->
     <string name="camera_gesture_title">Double twist for camera</string>
@@ -8172,7 +8187,7 @@
     <!-- Enterprise Privacy --> <skip />
 
     <!-- Title of setting on security settings screen. This will take the user to a screen with information about admin powers and their impact on the user's privacy on a managed device. Shown on enterprise-managed devices only. Note: "Device" is singular and refers to the device (e.g. phone or tablet) that the user is holding in their hand. -->
-    <string name="enterprise_privacy_settings">Managed device details</string>
+    <string name="enterprise_privacy_settings">Managed device info</string>
     <!-- Summary for Enterprise Privacy settings, explaining what the user can expect to find under it [CHAR LIMIT=NONE]-->
     <string name="enterprise_privacy_settings_summary_generic">Changes &amp; settings managed by your organization</string>
     <!-- Summary for Enterprise Privacy settings, explaining what the user can expect to find under it [CHAR LIMIT=NONE]-->
@@ -8212,13 +8227,13 @@
     <!-- Label indicating that the admin installed one or more apps on the device. -->
     <string name="enterprise_privacy_enterprise_installed_packages">Apps installed</string>
     <!-- Label indicating that the admin granted one or more apps access to the device's location. [CHAR LIMIT=NONE] -->
-    <string name="enterprise_privacy_location_access">Apps allowed to access your location</string>
+    <string name="enterprise_privacy_location_access">Location permissions</string>
     <!-- Label indicating that the admin granted one or more apps access to the microphone. [CHAR LIMIT=NONE] -->
-    <string name="enterprise_privacy_microphone_access">Apps allowed to access your microphone</string>
+    <string name="enterprise_privacy_microphone_access">Microphone permissions</string>
     <!-- Label indicating that the admin granted one or more apps access to the camera. [CHAR LIMIT=NONE] -->
-    <string name="enterprise_privacy_camera_access">Apps allowed to access your camera</string>
+    <string name="enterprise_privacy_camera_access">Camera permissions</string>
     <!-- Label indicating that the admin set one or more apps as defaults for common actions (e.g. open browser, send e-mail). [CHAR LIMIT=NONE] -->
-    <string name="enterprise_privacy_enterprise_set_default_apps">Default apps set</string>
+    <string name="enterprise_privacy_enterprise_set_default_apps">Default apps</string>
     <!-- Label explaining that the current input method was set by the admin. [CHAR LIMIT=NONE] -->
     <string name="enterprise_privacy_input_method">Default keyboard</string>
     <!-- Summary indicating the input method set by the admin. [CHAR LIMIT=NONE] -->
@@ -8231,30 +8246,17 @@
     <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 installed trusted CA certificates for the current user. [CHAR LIMIT=NONE] -->
-    <plurals name="enterprise_privacy_ca_certs_user">
-        <item quantity="one">Trusted CA Certificate installed</item>
-        <item quantity="other">Trusted CA Certificates installed</item>
-    </plurals>
-    <!-- Label explaining that the admin installed trusted CA certificates for the personal profile. [CHAR LIMIT=NONE] -->
-    <plurals name="enterprise_privacy_ca_certs_personal">
-        <item quantity="one">Trusted CA Certificate installed in your personal profile</item>
-        <item quantity="other">Trusted CA Certificates installed in your personal profile</item>
-    </plurals>
+    <!-- Label explaining that the admin installed trusted CA certificates. [CHAR LIMIT=NONE] -->
+    <string name="enterprise_privacy_ca_certs">Trusted credentials</string>
     <!-- Summary indicating the number of trusted CA certificates installed by the admin. [CHAR LIMIT=NONE] -->
     <plurals name="enterprise_privacy_number_ca_certs">
-        <item quantity="one"><xliff:g id="count">%d</xliff:g> certificate</item>
-        <item quantity="other"><xliff:g id="count">%d</xliff:g> certificates</item>
+        <item quantity="one"><xliff:g id="count">%d</xliff:g> CA certificate</item>
+        <item quantity="other"><xliff:g id="count">%d</xliff:g> CA certificates</item>
     </plurals>
     <!-- Summary indicating the number of trusted CA certificates installed by the admin. [CHAR LIMIT=NONE] -->
     <plurals name="enterprise_privacy_number_ca_certs_actionable">
-        <item quantity="one"><xliff:g id="count">%d</xliff:g> certificate. Tap to view.</item>
-        <item quantity="other"><xliff:g id="count">%d</xliff:g> certificates. Tap to view.</item>
-    </plurals>
-    <!-- Label explaining that the admin installed trusted CA certificates for the work profile. [CHAR LIMIT=NONE] -->
-    <plurals name="enterprise_privacy_ca_certs_work">
-        <item quantity="one">Trusted CA Certificate installed in your work profile</item>
-        <item quantity="other">Trusted CA Certificates installed in your work profile</item>
+        <item quantity="one"><xliff:g id="count">%d</xliff:g> CA certificate. Tap to view.</item>
+        <item quantity="other"><xliff:g id="count">%d</xliff:g> CA certificates. Tap to view.</item>
     </plurals>
     <!-- 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 the device and reset password</string>
diff --git a/res/values/styles.xml b/res/values/styles.xml
index 95efaec..fa40932 100644
--- a/res/values/styles.xml
+++ b/res/values/styles.xml
@@ -428,19 +428,6 @@
         <item name="android:textSize">24sp</item>
     </style>
 
-    <style name="AppInfoHeader" parent="EntityHeader">
-        <item name="android:background">?android:attr/colorAccent</item>
-    </style>
-
-    <style name="TextAppearance.AppInfoTitle" parent="TextAppearance.EntityHeaderTitle">
-        <item name="android:textColor">?android:attr/textColorPrimaryInverse</item>
-    </style>
-
-    <style name="TextAppearance.AppInfoSummary"
-           parent="@android:style/TextAppearance.Material.Body1">
-        <item name="android:textColor">?android:attr/textColorPrimaryInverse</item>
-    </style>
-
     <style name="AppActionPrimaryButton" parent="android:Widget.Material.Button.Colored"/>
 
     <style name="LockPatternStyle">
diff --git a/res/xml/enterprise_privacy_settings.xml b/res/xml/enterprise_privacy_settings.xml
index 68403c5..e6246c2 100644
--- a/res/xml/enterprise_privacy_settings.xml
+++ b/res/xml/enterprise_privacy_settings.xml
@@ -90,10 +90,8 @@
                 android:title="@string/enterprise_privacy_global_http_proxy"
                 settings:multiLine="true"/>
         <com.android.settings.DividerPreference
-                android:key="ca_certs_current_user"
-                settings:multiLine="true"/>
-        <com.android.settings.DividerPreference
-                android:key="ca_certs_managed_profile"
+                android:key="ca_certs"
+                android:title="@string/enterprise_privacy_ca_certs"
                 settings:multiLine="true"/>
     </PreferenceCategory>
 
diff --git a/res/xml/security_settings_misc.xml b/res/xml/security_settings_misc.xml
index e058b3e..943f04c 100644
--- a/res/xml/security_settings_misc.xml
+++ b/res/xml/security_settings_misc.xml
@@ -33,9 +33,7 @@
 
     </PreferenceCategory>
 
-    <PreferenceCategory android:key="device_admin_category"
-            android:title="@string/device_admin_title"
-            android:persistent="false">
+    <PreferenceCategory>
 
         <Preference android:key="manage_device_admin"
                 android:title="@string/manage_device_admin"
diff --git a/res/xml/special_access.xml b/res/xml/special_access.xml
index 8bf5c56..6eaede9 100644
--- a/res/xml/special_access.xml
+++ b/res/xml/special_access.xml
@@ -79,6 +79,7 @@
         android:title="@string/picture_in_picture_title"
         android:fragment="com.android.settings.applications.PictureInPictureSettings"
         settings:keywords="@string/picture_in_picture_keywords" />
+
     <Preference
         android:key="premium_sms"
         android:title="@string/premium_sms_access"
diff --git a/res/xml/storage_dashboard_fragment.xml b/res/xml/storage_dashboard_fragment.xml
index bf8483f..64a2aba 100644
--- a/res/xml/storage_dashboard_fragment.xml
+++ b/res/xml/storage_dashboard_fragment.xml
@@ -30,28 +30,28 @@
         android:order="1"
         settings:allowDividerAbove="true"
         settings:allowDividerBelow="true"/>
-    <com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate
+    <com.android.settings.deviceinfo.StorageItemPreference
         android:key="pref_photos_videos"
         android:title="@string/storage_photos_videos"
-        android:order="2"
-        settings:allowDividerAbove="true" />
-    <com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate
+        settings:allowDividerAbove="true"
+        android:order="2" />
+    <com.android.settings.deviceinfo.StorageItemPreference
         android:key="pref_music_audio"
         android:title="@string/storage_music_audio"
         android:order="3" />
-    <com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate
+    <com.android.settings.deviceinfo.StorageItemPreference
         android:key="pref_games"
         android:title="@string/storage_games"
         android:order="4" />
-    <com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate
+    <com.android.settings.deviceinfo.StorageItemPreference
         android:key="pref_other_apps"
         android:title="@string/storage_other_apps"
         android:order="5" />
-    <com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate
+    <com.android.settings.deviceinfo.StorageItemPreference
         android:key="pref_files"
         android:title="@string/storage_files"
         android:order="6" />
-    <com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate
+    <com.android.settings.deviceinfo.StorageItemPreference
         android:key="pref_system"
         android:title="@string/storage_detail_system"
         android:order="100" />
diff --git a/res/xml/storage_profile_fragment.xml b/res/xml/storage_profile_fragment.xml
index d0c5c3a..c675744 100644
--- a/res/xml/storage_profile_fragment.xml
+++ b/res/xml/storage_profile_fragment.xml
@@ -18,24 +18,24 @@
 <PreferenceScreen
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:title="@string/storage_settings">
-    <com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate
+    <com.android.settings.deviceinfo.StorageItemPreference
         android:key="pref_photos_videos"
         android:title="@string/storage_photos_videos">
-    </com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate>
-    <com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate
+    </com.android.settings.deviceinfo.StorageItemPreference>
+    <com.android.settings.deviceinfo.StorageItemPreference
         android:key="pref_music_audio"
         android:title="@string/storage_music_audio">
-    </com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate>
-    <com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate
+    </com.android.settings.deviceinfo.StorageItemPreference>
+    <com.android.settings.deviceinfo.StorageItemPreference
         android:key="pref_games"
         android:title="@string/storage_games">
-    </com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate>
-    <com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate
+    </com.android.settings.deviceinfo.StorageItemPreference>
+    <com.android.settings.deviceinfo.StorageItemPreference
         android:key="pref_other_apps"
         android:title="@string/storage_other_apps">
-    </com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate>
-    <com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate
+    </com.android.settings.deviceinfo.StorageItemPreference>
+    <com.android.settings.deviceinfo.StorageItemPreference
         android:key="pref_files"
         android:title="@string/storage_files">
-    </com.android.settings.deviceinfo.storage.StorageItemPreferenceAlternate>
+    </com.android.settings.deviceinfo.StorageItemPreference>
 </PreferenceScreen>
diff --git a/src/com/android/settings/SecuritySettings.java b/src/com/android/settings/SecuritySettings.java
index edefaf7..1cb763b 100644
--- a/src/com/android/settings/SecuritySettings.java
+++ b/src/com/android/settings/SecuritySettings.java
@@ -102,7 +102,6 @@
     private static final String KEY_UNLOCK_SET_OR_CHANGE_PROFILE = "unlock_set_or_change_profile";
     private static final String KEY_VISIBLE_PATTERN_PROFILE = "visiblepattern_profile";
     private static final String KEY_SECURITY_CATEGORY = "security_category";
-    private static final String KEY_DEVICE_ADMIN_CATEGORY = "device_admin_category";
     private static final String KEY_MANAGE_TRUST_AGENTS = "manage_trust_agents";
     private static final String KEY_UNIFICATION = "unification";
 
@@ -351,10 +350,6 @@
         // Credential storage
         final UserManager um = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
 
-        // Application install
-        PreferenceGroup deviceAdminCategory = (PreferenceGroup)
-                root.findPreference(KEY_DEVICE_ADMIN_CATEGORY);
-
         // Advanced Security features
         Preference manageAgents = root.findPreference(KEY_MANAGE_TRUST_AGENTS);
         if (manageAgents != null && !mLockPatternUtils.isSecure(MY_USER_ID)) {
diff --git a/src/com/android/settings/Settings.java b/src/com/android/settings/Settings.java
index f2d6452..8f645f8 100644
--- a/src/com/android/settings/Settings.java
+++ b/src/com/android/settings/Settings.java
@@ -95,6 +95,7 @@
     public static class NotificationAccessSettingsActivity extends SettingsActivity { /* empty */ }
     public static class VrListenersSettingsActivity extends SettingsActivity { /* empty */ }
     public static class PictureInPictureSettingsActivity extends SettingsActivity { /* empty */ }
+    public static class AppPictureInPictureSettingsActivity extends SettingsActivity { /* empty */ }
     public static class ZenAccessSettingsActivity extends SettingsActivity { /* empty */ }
     public static class ConditionProviderSettingsActivity extends SettingsActivity { /* empty */ }
     public static class UsbSettingsActivity extends SettingsActivity { /* empty */ }
diff --git a/src/com/android/settings/applications/AppStateInstallAppsBridge.java b/src/com/android/settings/applications/AppStateInstallAppsBridge.java
index 39a31e6..cc7fb62 100644
--- a/src/com/android/settings/applications/AppStateInstallAppsBridge.java
+++ b/src/com/android/settings/applications/AppStateInstallAppsBridge.java
@@ -43,12 +43,10 @@
 
     private final IPackageManager mIpm;
     private final AppOpsManager mAppOpsManager;
-    private final Context mContext;
 
     public AppStateInstallAppsBridge(Context context, ApplicationsState appState,
             Callback callback) {
         super(appState, callback);
-        mContext = context;
         mIpm = AppGlobals.getPackageManager();
         mAppOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
     }
diff --git a/src/com/android/settings/applications/ApplicationFeatureProvider.java b/src/com/android/settings/applications/ApplicationFeatureProvider.java
index 7dce793..51e79d8 100644
--- a/src/com/android/settings/applications/ApplicationFeatureProvider.java
+++ b/src/com/android/settings/applications/ApplicationFeatureProvider.java
@@ -54,9 +54,10 @@
      *
      * @param permissions Only consider apps that have been granted one or more of these permissions
      *        by the admin, either at run-time or install-time
+     * @param async Whether to count asynchronously in a background thread
      * @param callback The callback to invoke with the result
      */
-    void calculateNumberOfAppsWithAdminGrantedPermissions(String[] permissions,
+    void calculateNumberOfAppsWithAdminGrantedPermissions(String[] permissions, boolean async,
             NumberOfAppsCallback callback);
 
     /**
diff --git a/src/com/android/settings/applications/ApplicationFeatureProviderImpl.java b/src/com/android/settings/applications/ApplicationFeatureProviderImpl.java
index 5ba228f..77c9f3e 100644
--- a/src/com/android/settings/applications/ApplicationFeatureProviderImpl.java
+++ b/src/com/android/settings/applications/ApplicationFeatureProviderImpl.java
@@ -69,9 +69,15 @@
 
     @Override
     public void calculateNumberOfAppsWithAdminGrantedPermissions(String[] permissions,
-            NumberOfAppsCallback callback) {
-        new AllUserAppWithAdminGrantedPermissionsCounter(mContext, permissions, mPm, mPms, mDpm,
-                callback).execute();
+            boolean async, NumberOfAppsCallback callback) {
+        final AllUserAppWithAdminGrantedPermissionsCounter counter =
+                new AllUserAppWithAdminGrantedPermissionsCounter(mContext, permissions, mPm, mPms,
+                        mDpm, callback);
+        if (async) {
+            counter.execute();
+        } else {
+            counter.executeInForeground();
+        }
     }
 
     @Override
diff --git a/src/com/android/settings/applications/InstalledAppDetails.java b/src/com/android/settings/applications/InstalledAppDetails.java
index 08be7f7..e00ba92 100755
--- a/src/com/android/settings/applications/InstalledAppDetails.java
+++ b/src/com/android/settings/applications/InstalledAppDetails.java
@@ -52,7 +52,6 @@
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.support.annotation.VisibleForTesting;
-import android.support.v14.preference.SwitchPreference;
 import android.support.v7.preference.Preference;
 import android.support.v7.preference.Preference.OnPreferenceClickListener;
 import android.support.v7.preference.PreferenceCategory;
@@ -1041,17 +1040,16 @@
                 category.addPreference(pref);
             }
             if (hasPictureInPictureActivities) {
-                final SwitchPreference pref = new SwitchPreference(getPrefContext());
-                pref.setPersistent(false);
+                Preference pref = new Preference(getPrefContext());
                 pref.setTitle(R.string.picture_in_picture_app_detail_title);
-                pref.setSummary(R.string.picture_in_picture_app_detail_summary);
-                pref.setChecked(PictureInPictureSettings.getEnterPipOnHideStateForPackage(
-                        getContext(), mPackageInfo.applicationInfo.uid, mPackageName));
-                pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
+                pref.setKey("picture_in_picture");
+                pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                     @Override
-                    public boolean onPreferenceChange(Preference preference, Object newValue) {
-                        PictureInPictureSettings.setEnterPipOnHideStateForPackage(getContext(),
-                                mPackageInfo.applicationInfo.uid, mPackageName, (Boolean) newValue);
+                    public boolean onPreferenceClick(Preference preference) {
+                        AppInfoBase.startAppInfoFragment(PictureInPictureDetails.class,
+                                R.string.picture_in_picture_app_detail_title, mPackageName,
+                                mPackageInfo.applicationInfo.uid, InstalledAppDetails.this,
+                                -1, getMetricsCategory());
                         return true;
                     }
                 });
@@ -1164,6 +1162,11 @@
         if (pref != null) {
             pref.setSummary(DrawOverlayDetails.getSummary(getContext(), mAppEntry));
         }
+        pref = findPreference("picture_in_picture");
+        if (pref != null) {
+            pref.setSummary(PictureInPictureDetails.getPreferenceSummary(getContext(),
+                    mPackageInfo.applicationInfo.uid, mPackageName));
+        }
         pref = findPreference("write_settings_apps");
         if (pref != null) {
             pref.setSummary(WriteSettingsDetails.getSummary(getContext(), mAppEntry));
diff --git a/src/com/android/settings/applications/PictureInPictureDetails.java b/src/com/android/settings/applications/PictureInPictureDetails.java
new file mode 100644
index 0000000..41f006a
--- /dev/null
+++ b/src/com/android/settings/applications/PictureInPictureDetails.java
@@ -0,0 +1,138 @@
+/*
+ * 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 static android.app.AppOpsManager.MODE_ALLOWED;
+import static android.app.AppOpsManager.MODE_ERRORED;
+import static android.app.AppOpsManager.OP_PICTURE_IN_PICTURE;
+
+import android.app.AlertDialog;
+import android.app.AppOpsManager;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.provider.Settings;
+import android.support.v14.preference.SwitchPreference;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.Preference.OnPreferenceChangeListener;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.settings.R;
+import com.android.settings.overlay.FeatureFactory;
+
+public class PictureInPictureDetails extends AppInfoWithHeader
+        implements OnPreferenceChangeListener {
+
+    private static final String KEY_APP_OPS_SETTINGS_SWITCH = "app_ops_settings_switch";
+    private static final String KEY_APP_OPS_SETTINGS_PREFS = "app_ops_settings_preference";
+    private static final String KEY_APP_OPS_SETTINGS_DESC = "app_ops_settings_description";
+    private static final String LOG_TAG = "PictureInPictureDetails";
+
+    private SwitchPreference mSwitchPref;
+    private Preference mOverlayDesc;
+    private Intent mSettingsIntent;
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        // find preferences
+        addPreferencesFromResource(R.xml.app_ops_permissions_details);
+        mSwitchPref = (SwitchPreference) findPreference(KEY_APP_OPS_SETTINGS_SWITCH);
+        mOverlayDesc = findPreference(KEY_APP_OPS_SETTINGS_DESC);
+        getPreferenceScreen().removePreference(findPreference(KEY_APP_OPS_SETTINGS_PREFS));
+
+        // set title/summary for all of them
+        getPreferenceScreen().setTitle(R.string.picture_in_picture_app_detail_title);
+        mSwitchPref.setTitle(R.string.picture_in_picture_app_detail_switch);
+        mOverlayDesc.setSummary(R.string.picture_in_picture_app_detail_summary);
+
+        // install event listeners
+        mSwitchPref.setOnPreferenceChangeListener(this);
+
+        mSettingsIntent = new Intent(Intent.ACTION_MAIN)
+                .setAction(Settings.ACTION_PICTURE_IN_PICTURE_SETTINGS);
+    }
+
+    @Override
+    public boolean onPreferenceChange(Preference preference, Object newValue) {
+        if (preference == mSwitchPref) {
+            logSpecialPermissionChange((Boolean) newValue, mPackageName);
+            setEnterPipStateForPackage(getActivity(), mPackageInfo.applicationInfo.uid, mPackageName,
+                    (Boolean) newValue);
+            return true;
+        }
+        return false;
+    }
+
+    @Override
+    protected boolean refreshUi() {
+        boolean isAllowed = getEnterPipStateForPackage(getActivity(),
+                mPackageInfo.applicationInfo.uid, mPackageName);
+        mSwitchPref.setChecked(isAllowed);
+        return true;
+    }
+
+    @Override
+    protected AlertDialog createDialog(int id, int errorCode) {
+        return null;
+    }
+
+    @Override
+    public int getMetricsCategory() {
+        return MetricsEvent.SETTINGS_MANAGE_PICTURE_IN_PICTURE;
+    }
+
+    /**
+     * Sets whether the app associated with the given {@param packageName} is allowed to enter
+     * picture-in-picture.
+     */
+    static void setEnterPipStateForPackage(Context context, int uid, String packageName,
+            boolean value) {
+        final AppOpsManager appOps = context.getSystemService(AppOpsManager.class);
+        final int newMode = value ? MODE_ALLOWED : MODE_ERRORED;
+        appOps.setMode(OP_PICTURE_IN_PICTURE, uid, packageName, newMode);
+    }
+
+    /**
+     * @return whether the app associated with the given {@param packageName} is allowed to enter
+     *         picture-in-picture.
+     */
+    static boolean getEnterPipStateForPackage(Context context, int uid, String packageName) {
+        final AppOpsManager appOps = context.getSystemService(AppOpsManager.class);
+        return appOps.checkOpNoThrow(OP_PICTURE_IN_PICTURE, uid, packageName) == MODE_ALLOWED;
+    }
+
+    /**
+     * @return the summary for the current state of whether the app associated with the given
+     *         {@param packageName} is allowed to enter picture-in-picture.
+     */
+    static int getPreferenceSummary(Context context, int uid, String packageName) {
+        final boolean enabled = PictureInPictureDetails.getEnterPipStateForPackage(context, uid,
+                packageName);
+        return enabled ? R.string.picture_in_picture_on : R.string.picture_in_picture_off;
+    }
+
+    @VisibleForTesting
+    void logSpecialPermissionChange(boolean newState, String packageName) {
+        int logCategory = newState
+                ? MetricsEvent.APP_PICTURE_IN_PICTURE_ALLOW
+                : MetricsEvent.APP_PICTURE_IN_PICTURE_DENY;
+        FeatureFactory.getFactory(getContext())
+                .getMetricsFeatureProvider().action(getContext(), logCategory, packageName);
+    }
+}
diff --git a/src/com/android/settings/applications/PictureInPictureSettings.java b/src/com/android/settings/applications/PictureInPictureSettings.java
index df73572..b1c544a 100644
--- a/src/com/android/settings/applications/PictureInPictureSettings.java
+++ b/src/com/android/settings/applications/PictureInPictureSettings.java
@@ -15,13 +15,9 @@
  */
 package com.android.settings.applications;
 
-import static android.app.AppOpsManager.MODE_ALLOWED;
-import static android.app.AppOpsManager.MODE_ERRORED;
-import static android.app.AppOpsManager.OP_ENTER_PICTURE_IN_PICTURE_ON_HIDE;
 import static android.content.pm.PackageManager.GET_ACTIVITIES;
 
 import android.annotation.Nullable;
-import android.app.AppOpsManager;
 import android.content.Context;
 import android.content.pm.ActivityInfo;
 import android.content.pm.ApplicationInfo;
@@ -30,8 +26,8 @@
 import android.content.pm.PackageManager;
 import android.os.Bundle;
 import android.os.UserHandle;
-import android.support.v14.preference.SwitchPreference;
 import android.support.v7.preference.Preference;
+import android.support.v7.preference.Preference.OnPreferenceClickListener;
 import android.support.v7.preference.PreferenceScreen;
 import android.util.ArrayMap;
 import android.view.View;
@@ -40,7 +36,6 @@
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.settings.R;
 import com.android.settings.notification.EmptyTextSettings;
-import com.android.settings.overlay.FeatureFactory;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -98,28 +93,6 @@
         return false;
     }
 
-    /**
-     * Sets whether the app associated with the given {@param packageName} is allowed to enter
-     * picture-in-picture when it is hidden.
-     */
-    static void setEnterPipOnHideStateForPackage(Context context, int uid, String packageName,
-            boolean value) {
-        final AppOpsManager appOps = context.getSystemService(AppOpsManager.class);
-        final int newMode = value ? MODE_ALLOWED : MODE_ERRORED;
-        appOps.setMode(OP_ENTER_PICTURE_IN_PICTURE_ON_HIDE,
-                uid, packageName, newMode);
-    }
-
-    /**
-     * @return whether the app associated with the given {@param packageName} is allowed to enter
-     *         picture-in-picture when it is hidden.
-     */
-    static boolean getEnterPipOnHideStateForPackage(Context context, int uid, String packageName) {
-        final AppOpsManager appOps = context.getSystemService(AppOpsManager.class);
-        return appOps.checkOpNoThrow(OP_ENTER_PICTURE_IN_PICTURE_ON_HIDE,
-                uid, packageName) == MODE_ALLOWED;
-    }
-
     @Override
     public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
@@ -147,8 +120,8 @@
             if (checkPackageHasPictureInPictureActivities(packageInfo.packageName,
                     packageInfo.activities)) {
                 final String packageName = packageInfo.applicationInfo.packageName;
-                final boolean state = getEnterPipOnHideStateForPackage(mContext,
-                        packageInfo.applicationInfo.uid, packageName);
+                final boolean state = PictureInPictureDetails.getEnterPipStateForPackage(
+                        mContext, packageInfo.applicationInfo.uid, packageName);
                 pipApps.add(packageInfo.applicationInfo);
                 packageToState.put(packageName, state);
             }
@@ -160,17 +133,18 @@
         for (final ApplicationInfo appInfo : pipApps) {
             final String packageName = appInfo.packageName;
             final CharSequence label = appInfo.loadLabel(mPackageManager);
-            final SwitchPreference pref = new SwitchPreference(prefContext);
-            pref.setPersistent(false);
+
+            final Preference pref = new Preference(prefContext);
             pref.setIcon(appInfo.loadIcon(mPackageManager));
             pref.setTitle(label);
-            pref.setChecked(packageToState.get(packageName));
-            pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
+            pref.setSummary(PictureInPictureDetails.getPreferenceSummary(prefContext,
+                    appInfo.uid, packageName));
+            pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                 @Override
-                public boolean onPreferenceChange(Preference preference, Object newValue) {
-                    logSpecialPermissionChange((Boolean) newValue, packageName);
-                    setEnterPipOnHideStateForPackage(mContext, appInfo.uid, packageName,
-                            (Boolean) newValue);
+                public boolean onPreferenceClick(Preference preference) {
+                    AppInfoBase.startAppInfoFragment(PictureInPictureDetails.class,
+                            R.string.picture_in_picture_app_detail_title, packageName, appInfo.uid,
+                            PictureInPictureSettings.this, -1, getMetricsCategory());
                     return true;
                 }
             });
@@ -188,13 +162,4 @@
     public int getMetricsCategory() {
         return MetricsEvent.SETTINGS_MANAGE_PICTURE_IN_PICTURE;
     }
-
-    @VisibleForTesting
-    void logSpecialPermissionChange(boolean newState, String packageName) {
-        int logCategory = newState
-                ? MetricsEvent.APP_PICTURE_IN_PICTURE_ON_HIDE_ALLOW
-                : MetricsEvent.APP_PICTURE_IN_PICTURE_ON_HIDE_DENY;
-        FeatureFactory.getFactory(getContext())
-                .getMetricsFeatureProvider().action(getContext(), logCategory, packageName);
-    }
 }
diff --git a/src/com/android/settings/bluetooth/BluetoothPairingService.java b/src/com/android/settings/bluetooth/BluetoothPairingService.java
index a24a3f0..5dfd283 100644
--- a/src/com/android/settings/bluetooth/BluetoothPairingService.java
+++ b/src/com/android/settings/bluetooth/BluetoothPairingService.java
@@ -80,6 +80,7 @@
         Log.d(TAG, "Dismiss pairing for " + mDevice.getAddress() + " (" + mDevice.getName() + "), Cancelled.");
       }
       stopForeground(true);
+      stopSelf();
     }
   };
 
@@ -89,6 +90,12 @@
 
   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
+    if (intent == null) {
+      Log.e(TAG, "Can't start: null intent!");
+      stopSelf();
+      return START_NOT_STICKY;
+    }
+
     Resources res = getResources();
     Notification.Builder builder = new Notification.Builder(this)
         .setSmallIcon(android.R.drawable.stat_sys_data_bluetooth)
@@ -99,6 +106,12 @@
 
     mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
 
+    if (mDevice.getBondState() != BluetoothDevice.BOND_BONDING) {
+      Log.w(TAG, "Device " + mDevice + " not bonding: " + mDevice.getBondState());
+      stopSelf();
+      return START_NOT_STICKY;
+    }
+
     String name = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
     if (TextUtils.isEmpty(name)) {
       BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
@@ -119,7 +132,7 @@
     registerReceiver(mCancelReceiver, filter);
 
     startForeground(NOTIFICATION_ID, builder.getNotification());
-    return START_STICKY;
+    return START_REDELIVER_INTENT;
   }
 
   @Override
diff --git a/src/com/android/settings/core/gateway/SettingsGateway.java b/src/com/android/settings/core/gateway/SettingsGateway.java
index fb2c9ce..467b848 100644
--- a/src/com/android/settings/core/gateway/SettingsGateway.java
+++ b/src/com/android/settings/core/gateway/SettingsGateway.java
@@ -52,6 +52,7 @@
 import com.android.settings.applications.ManageApplications;
 import com.android.settings.applications.ManageDomainUrls;
 import com.android.settings.applications.NotificationApps;
+import com.android.settings.applications.PictureInPictureDetails;
 import com.android.settings.applications.PictureInPictureSettings;
 import com.android.settings.applications.ProcessStatsSummary;
 import com.android.settings.applications.ProcessStatsUi;
@@ -218,6 +219,7 @@
             WallpaperTypeSettings.class.getName(),
             VrListenerSettings.class.getName(),
             PictureInPictureSettings.class.getName(),
+            PictureInPictureDetails.class.getName(),
             ManagedProfileSettings.class.getName(),
             ChooseAccountActivity.class.getName(),
             IccLockSettings.class.getName(),
diff --git a/src/com/android/settings/datausage/DataUsageList.java b/src/com/android/settings/datausage/DataUsageList.java
index e12f89e..de92154 100644
--- a/src/com/android/settings/datausage/DataUsageList.java
+++ b/src/com/android/settings/datausage/DataUsageList.java
@@ -477,7 +477,7 @@
 
         final ConnectivityManager conn = ConnectivityManager.from(context);
         final TelephonyManager tele = TelephonyManager.from(context);
-        final int slotId = SubscriptionManager.getSlotId(subId);
+        final int slotId = SubscriptionManager.getSlotIndex(subId);
         final boolean isReady = tele.getSimState(slotId) == SIM_STATE_READY;
 
         boolean retVal = conn.isNetworkSupported(TYPE_MOBILE) && isReady;
diff --git a/src/com/android/settings/deviceinfo/StorageDashboardFragment.java b/src/com/android/settings/deviceinfo/StorageDashboardFragment.java
index 133c56c..18393ac 100644
--- a/src/com/android/settings/deviceinfo/StorageDashboardFragment.java
+++ b/src/com/android/settings/deviceinfo/StorageDashboardFragment.java
@@ -114,6 +114,16 @@
         mSummaryController.updateBytes(usedBytes, totalSize);
         mPreferenceController.setVolume(mVolume);
         mPreferenceController.setSystemSize(systemSize);
+
+        mPreferenceController.setTotalSize(totalSize);
+        for (int i = 0, size = mSecondaryUsers.size(); i < size; i++) {
+            PreferenceController controller = mSecondaryUsers.get(i);
+            if (controller instanceof SecondaryUserController) {
+                SecondaryUserController userController = (SecondaryUserController) controller;
+                userController.setTotalSize(totalSize);
+
+            }
+        }
     }
 
     @Override
diff --git a/src/com/android/settings/deviceinfo/StorageItemPreference.java b/src/com/android/settings/deviceinfo/StorageItemPreference.java
index b15794e..763b6d4 100644
--- a/src/com/android/settings/deviceinfo/StorageItemPreference.java
+++ b/src/com/android/settings/deviceinfo/StorageItemPreference.java
@@ -20,6 +20,7 @@
 import android.support.v7.preference.Preference;
 import android.support.v7.preference.PreferenceViewHolder;
 import android.text.format.Formatter;
+import android.util.AttributeSet;
 import android.view.View;
 import android.widget.ProgressBar;
 
@@ -28,13 +29,18 @@
 public class StorageItemPreference extends Preference {
     public int userHandle;
 
-    private ProgressBar progressBar;
+    private ProgressBar mProgressBar;
     private static final int PROGRESS_MAX = 100;
-    private int progress = -1;
+    private int mProgressPercent = -1;
 
     public StorageItemPreference(Context context) {
-        super(context);
+        this(context, null);
+    }
+
+    public StorageItemPreference(Context context, AttributeSet attrs) {
+        super(context, attrs);
         setLayoutResource(R.layout.storage_item);
+        setSummary(R.string.memory_calculating_size);
     }
 
     public void setStorageSize(long size, long total) {
@@ -42,30 +48,30 @@
                 ? String.valueOf(0)
                 : Formatter.formatFileSize(getContext(), size));
         if (total == 0) {
-            progress = 0;
+            mProgressPercent = 0;
         } else {
-            progress = (int)(size * PROGRESS_MAX / total);
+            mProgressPercent = (int)(size * PROGRESS_MAX / total);
         }
         updateProgressBar();
     }
 
     protected void updateProgressBar() {
-        if (progressBar == null)
+        if (mProgressBar == null)
             return;
 
-        if (progress == -1) {
-            progressBar.setVisibility(View.GONE);
+        if (mProgressPercent == -1) {
+            mProgressBar.setVisibility(View.GONE);
             return;
         }
 
-        progressBar.setVisibility(View.VISIBLE);
-        progressBar.setMax(PROGRESS_MAX);
-        progressBar.setProgress(progress);
+        mProgressBar.setVisibility(View.VISIBLE);
+        mProgressBar.setMax(PROGRESS_MAX);
+        mProgressBar.setProgress(mProgressPercent);
     }
 
     @Override
     public void onBindViewHolder(PreferenceViewHolder view) {
-        progressBar = (ProgressBar) view.findViewById(android.R.id.progress);
+        mProgressBar = (ProgressBar) view.findViewById(android.R.id.progress);
         updateProgressBar();
         super.onBindViewHolder(view);
     }
diff --git a/src/com/android/settings/deviceinfo/storage/SecondaryUserController.java b/src/com/android/settings/deviceinfo/storage/SecondaryUserController.java
index 4fd9e52..eb589ca 100644
--- a/src/com/android/settings/deviceinfo/storage/SecondaryUserController.java
+++ b/src/com/android/settings/deviceinfo/storage/SecondaryUserController.java
@@ -28,6 +28,7 @@
 import com.android.settings.Utils;
 import com.android.settings.applications.UserManagerWrapper;
 import com.android.settings.core.PreferenceController;
+import com.android.settings.deviceinfo.StorageItemPreference;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -46,8 +47,9 @@
     private static final int SIZE_NOT_SET = -1;
 
     private @NonNull UserInfo mUser;
-    private @Nullable StorageItemPreferenceAlternate mStoragePreference;
+    private @Nullable StorageItemPreference mStoragePreference;
     private long mSize;
+    private long mTotalSizeBytes;
 
     /**
      * Adds the appropriate controllers to a controller list for handling all secondary users on
@@ -98,14 +100,14 @@
     @Override
     public void displayPreference(PreferenceScreen screen) {
         if (mStoragePreference == null) {
-            mStoragePreference = new StorageItemPreferenceAlternate(screen.getContext());
+            mStoragePreference = new StorageItemPreference(screen.getContext());
 
             PreferenceGroup group =
                     (PreferenceGroup) screen.findPreference(TARGET_PREFERENCE_GROUP_KEY);
             mStoragePreference.setTitle(mUser.name);
             mStoragePreference.setKey(PREFERENCE_KEY_BASE + mUser.id);
             if (mSize != SIZE_NOT_SET) {
-                mStoragePreference.setStorageSize(mSize);
+                mStoragePreference.setStorageSize(mSize, mTotalSizeBytes);
             }
             group.setVisible(true);
             group.addPreference(mStoragePreference);
@@ -137,10 +139,18 @@
     public void setSize(long size) {
         mSize = size;
         if (mStoragePreference != null) {
-            mStoragePreference.setStorageSize(mSize);
+            mStoragePreference.setStorageSize(mSize, mTotalSizeBytes);
         }
     }
 
+    /**
+     * Sets the total size for the preference for the progress bar.
+     * @param totalSizeBytes Total size in bytes.
+     */
+    public void setTotalSize(long totalSizeBytes) {
+        mTotalSizeBytes = totalSizeBytes;
+    }
+
     public void handleResult(SparseArray<StorageAsyncLoader.AppsStorageResult> stats) {
         int userId = getUser().id;
         StorageAsyncLoader.AppsStorageResult result = stats.get(userId);
diff --git a/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceAlternate.java b/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceAlternate.java
deleted file mode 100644
index d5a36b9..0000000
--- a/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceAlternate.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2011 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.deviceinfo.storage;
-
-import android.content.Context;
-import android.support.v7.preference.Preference;
-import android.text.format.Formatter;
-import android.util.AttributeSet;
-
-import com.android.settings.R;
-
-public class StorageItemPreferenceAlternate extends Preference {
-    public StorageItemPreferenceAlternate(Context context) {
-        this(context, null);
-    }
-
-    public StorageItemPreferenceAlternate(Context context, AttributeSet attrs) {
-        super(context, attrs);
-        setLayoutResource(R.layout.storage_item_alternate);
-        setSummary(R.string.memory_calculating_size);
-    }
-
-    public void setStorageSize(long size) {
-        setSummary(size == 0
-                ? String.valueOf(0)
-                : Formatter.formatFileSize(getContext(), size));
-    }
-}
\ No newline at end of file
diff --git a/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceController.java b/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceController.java
index 36cf73e..eec9487 100644
--- a/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceController.java
+++ b/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceController.java
@@ -35,6 +35,7 @@
 import com.android.settings.applications.ManageApplications;
 import com.android.settings.core.PreferenceController;
 import com.android.settings.core.instrumentation.MetricsFeatureProvider;
+import com.android.settings.deviceinfo.StorageItemPreference;
 import com.android.settings.overlay.FeatureFactory;
 import com.android.settingslib.deviceinfo.StorageMeasurement;
 import com.android.settingslib.deviceinfo.StorageVolumeProvider;
@@ -71,13 +72,14 @@
     private VolumeInfo mVolume;
     private int mUserId;
     private long mSystemSize;
+    private long mTotalSize;
 
-    private StorageItemPreferenceAlternate mPhotoPreference;
-    private StorageItemPreferenceAlternate mAudioPreference;
-    private StorageItemPreferenceAlternate mGamePreference;
-    private StorageItemPreferenceAlternate mAppPreference;
-    private StorageItemPreferenceAlternate mFilePreference;
-    private StorageItemPreferenceAlternate mSystemPreference;
+    private StorageItemPreference mPhotoPreference;
+    private StorageItemPreference mAudioPreference;
+    private StorageItemPreference mGamePreference;
+    private StorageItemPreference mAppPreference;
+    private StorageItemPreference mFilePreference;
+    private StorageItemPreference mSystemPreference;
 
     private static final String AUTHORITY_MEDIA = "com.android.providers.media.documents";
 
@@ -164,37 +166,38 @@
 
     @Override
     public void displayPreference(PreferenceScreen screen) {
-        mPhotoPreference = (StorageItemPreferenceAlternate) screen.findPreference(PHOTO_KEY);
-        mAudioPreference = (StorageItemPreferenceAlternate) screen.findPreference(AUDIO_KEY);
-        mGamePreference = (StorageItemPreferenceAlternate) screen.findPreference(GAME_KEY);
-        mAppPreference = (StorageItemPreferenceAlternate) screen.findPreference(OTHER_APPS_KEY);
-        mSystemPreference = (StorageItemPreferenceAlternate) screen.findPreference(SYSTEM_KEY);
-        mFilePreference = (StorageItemPreferenceAlternate) screen.findPreference(FILES_KEY);
+        mPhotoPreference = (StorageItemPreference) screen.findPreference(PHOTO_KEY);
+        mAudioPreference = (StorageItemPreference) screen.findPreference(AUDIO_KEY);
+        mGamePreference = (StorageItemPreference) screen.findPreference(GAME_KEY);
+        mAppPreference = (StorageItemPreference) screen.findPreference(OTHER_APPS_KEY);
+        mSystemPreference = (StorageItemPreference) screen.findPreference(SYSTEM_KEY);
+        mFilePreference = (StorageItemPreference) screen.findPreference(FILES_KEY);
     }
 
     public void onLoadFinished(StorageAsyncLoader.AppsStorageResult data) {
         // TODO(b/35927909): Figure out how to split out apps which are only installed for work
         //       profiles in order to attribute those app's code bytes only to that profile.
         mPhotoPreference.setStorageSize(
-                data.externalStats.imageBytes + data.externalStats.videoBytes);
-        mAudioPreference.setStorageSize(data.musicAppsSize + data.externalStats.audioBytes);
-        mGamePreference.setStorageSize(data.gamesSize);
-        mAppPreference.setStorageSize(data.otherAppsSize);
+                data.externalStats.imageBytes + data.externalStats.videoBytes, mTotalSize);
+        mAudioPreference.setStorageSize(
+                data.musicAppsSize + data.externalStats.audioBytes, mTotalSize);
+        mGamePreference.setStorageSize(data.gamesSize, mTotalSize);
+        mAppPreference.setStorageSize(data.otherAppsSize, mTotalSize);
         if (mSystemPreference != null) {
-            mSystemPreference.setStorageSize(mSystemSize + data.systemSize);
+            mSystemPreference.setStorageSize(mSystemSize + data.systemSize, mTotalSize);
         }
 
         long unattributedBytes = data.externalStats.totalBytes - data.externalStats.audioBytes
                 - data.externalStats.videoBytes - data.externalStats.imageBytes;
-        mFilePreference.setStorageSize(unattributedBytes);
+        mFilePreference.setStorageSize(unattributedBytes, mTotalSize);
     }
 
-    /**
-     * Sets the system size for the system size preference.
-     * @param systemSize the size of the system in bytes
-     */
-    public void setSystemSize(long systemSize) {
-        mSystemSize = systemSize;
+    public void setSystemSize(long systemSizeBytes) {
+        mSystemSize = systemSizeBytes;
+    }
+
+    public void setTotalSize(long totalSizeBytes) {
+        mTotalSize = totalSizeBytes;
     }
 
     /**
diff --git a/src/com/android/settings/deviceinfo/storage/UserProfileController.java b/src/com/android/settings/deviceinfo/storage/UserProfileController.java
index 963784d..ef8b21e 100644
--- a/src/com/android/settings/deviceinfo/storage/UserProfileController.java
+++ b/src/com/android/settings/deviceinfo/storage/UserProfileController.java
@@ -29,6 +29,7 @@
 import com.android.internal.util.Preconditions;
 import com.android.settings.Utils;
 import com.android.settings.core.PreferenceController;
+import com.android.settings.deviceinfo.StorageItemPreference;
 import com.android.settings.deviceinfo.StorageProfileFragment;
 import com.android.settingslib.drawer.SettingsDrawerActivity;
 
@@ -38,8 +39,9 @@
 public class UserProfileController extends PreferenceController implements
         StorageAsyncLoader.ResultHandler {
     private static final String PREFERENCE_KEY_BASE = "pref_profile_";
-    private StorageItemPreferenceAlternate mStoragePreference;
+    private StorageItemPreference mStoragePreference;
     private UserInfo mUser;
+    private long mTotalSizeBytes;
     private final int mPreferenceOrder;
 
     public UserProfileController(Context context, UserInfo info, int preferenceOrder) {
@@ -60,7 +62,7 @@
 
     @Override
     public void displayPreference(PreferenceScreen screen) {
-        mStoragePreference = new StorageItemPreferenceAlternate(screen.getContext());
+        mStoragePreference = new StorageItemPreference(screen.getContext());
         mStoragePreference.setOrder(mPreferenceOrder);
         mStoragePreference.setKey(PREFERENCE_KEY_BASE + mUser.id);
         mStoragePreference.setTitle(mUser.name);
@@ -91,16 +93,20 @@
         int userId = mUser.id;
         StorageAsyncLoader.AppsStorageResult result = stats.get(userId);
         if (result != null) {
-            setSize(result.externalStats.totalBytes);
+            setSize(result.externalStats.totalBytes, mTotalSizeBytes);
         }
     }
 
     /**
      * Sets the size for the preference using a byte count.
      */
-    public void setSize(long size) {
+    public void setSize(long size, long totalSize) {
         if (mStoragePreference != null) {
-            mStoragePreference.setStorageSize(size);
+            mStoragePreference.setStorageSize(size, totalSize);
         }
     }
+
+    public void setTotalSize(long totalSize) {
+        mTotalSizeBytes = totalSize;
+    }
 }
diff --git a/src/com/android/settings/enterprise/AdminGrantedCameraPermissionPreferenceController.java b/src/com/android/settings/enterprise/AdminGrantedCameraPermissionPreferenceController.java
index 8394262..003ed11 100644
--- a/src/com/android/settings/enterprise/AdminGrantedCameraPermissionPreferenceController.java
+++ b/src/com/android/settings/enterprise/AdminGrantedCameraPermissionPreferenceController.java
@@ -17,14 +17,18 @@
 import android.Manifest;
 import android.content.Context;
 
+import com.android.settings.core.lifecycle.Lifecycle;
+
 public class AdminGrantedCameraPermissionPreferenceController extends
         AdminGrantedPermissionsPreferenceControllerBase {
 
     private static final String KEY_ENTERPRISE_PRIVACY_NUMBER_CAMERA_ACCESS_PACKAGES
             = "enterprise_privacy_number_camera_access_packages";
 
-    public AdminGrantedCameraPermissionPreferenceController(Context context) {
-        super(context, new String[] {Manifest.permission.CAMERA}, Manifest.permission_group.CAMERA);
+    public AdminGrantedCameraPermissionPreferenceController(Context context, Lifecycle lifecycle,
+            boolean async) {
+        super(context, lifecycle, async, new String[] {Manifest.permission.CAMERA},
+                Manifest.permission_group.CAMERA);
     }
 
     @Override
diff --git a/src/com/android/settings/enterprise/AdminGrantedLocationPermissionsPreferenceController.java b/src/com/android/settings/enterprise/AdminGrantedLocationPermissionsPreferenceController.java
index 4dfc4be..5343483 100644
--- a/src/com/android/settings/enterprise/AdminGrantedLocationPermissionsPreferenceController.java
+++ b/src/com/android/settings/enterprise/AdminGrantedLocationPermissionsPreferenceController.java
@@ -17,14 +17,17 @@
 import android.Manifest;
 import android.content.Context;
 
+import com.android.settings.core.lifecycle.Lifecycle;
+
 public class AdminGrantedLocationPermissionsPreferenceController extends
         AdminGrantedPermissionsPreferenceControllerBase {
 
     private static final String KEY_ENTERPRISE_PRIVACY_NUMBER_LOCATION_ACCESS_PACKAGES
             = "enterprise_privacy_number_location_access_packages";
 
-    public AdminGrantedLocationPermissionsPreferenceController(Context context) {
-        super(context, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION,
+    public AdminGrantedLocationPermissionsPreferenceController(Context context, Lifecycle lifecycle,
+            boolean async) {
+        super(context, lifecycle, async, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION,
                 Manifest.permission.ACCESS_FINE_LOCATION}, Manifest.permission_group.LOCATION);
     }
 
diff --git a/src/com/android/settings/enterprise/AdminGrantedMicrophonePermissionPreferenceController.java b/src/com/android/settings/enterprise/AdminGrantedMicrophonePermissionPreferenceController.java
index e2ab555..64396c5 100644
--- a/src/com/android/settings/enterprise/AdminGrantedMicrophonePermissionPreferenceController.java
+++ b/src/com/android/settings/enterprise/AdminGrantedMicrophonePermissionPreferenceController.java
@@ -17,14 +17,17 @@
 import android.Manifest;
 import android.content.Context;
 
+import com.android.settings.core.lifecycle.Lifecycle;
+
 public class AdminGrantedMicrophonePermissionPreferenceController extends
         AdminGrantedPermissionsPreferenceControllerBase {
 
     private static final String KEY_ENTERPRISE_PRIVACY_NUMBER_MICROPHONE_ACCESS_PACKAGES
             = "enterprise_privacy_number_microphone_access_packages";
 
-    public AdminGrantedMicrophonePermissionPreferenceController(Context context) {
-        super(context, new String[] {Manifest.permission.RECORD_AUDIO},
+    public AdminGrantedMicrophonePermissionPreferenceController(Context context,
+            Lifecycle lifecycle, boolean async) {
+        super(context, lifecycle, async, new String[] {Manifest.permission.RECORD_AUDIO},
                 Manifest.permission_group.MICROPHONE);
     }
 
diff --git a/src/com/android/settings/enterprise/AdminGrantedPermissionsPreferenceControllerBase.java b/src/com/android/settings/enterprise/AdminGrantedPermissionsPreferenceControllerBase.java
index 5263817..c60d7e0 100644
--- a/src/com/android/settings/enterprise/AdminGrantedPermissionsPreferenceControllerBase.java
+++ b/src/com/android/settings/enterprise/AdminGrantedPermissionsPreferenceControllerBase.java
@@ -1,3 +1,4 @@
+
 /*
  * Copyright (C) 2017 The Android Open Source Project
  *
@@ -20,28 +21,32 @@
 
 import com.android.settings.R;
 import com.android.settings.applications.ApplicationFeatureProvider;
-import com.android.settings.core.PreferenceController;
+import com.android.settings.core.DynamicAvailabilityPreferenceController;
+import com.android.settings.core.lifecycle.Lifecycle;
 import com.android.settings.overlay.FeatureFactory;
 
-public abstract class AdminGrantedPermissionsPreferenceControllerBase extends PreferenceController {
+public abstract class AdminGrantedPermissionsPreferenceControllerBase
+        extends DynamicAvailabilityPreferenceController {
 
     private final String[] mPermissions;
     private final String mPermissionGroup;
     private final ApplicationFeatureProvider mFeatureProvider;
+    private final boolean mAsync;
 
-    public AdminGrantedPermissionsPreferenceControllerBase(Context context,
-                                                           String[] permissions,
-                                                           String permissionGroup) {
-        super(context);
+    public AdminGrantedPermissionsPreferenceControllerBase(Context context, Lifecycle lifecycle,
+            boolean async, String[] permissions, String permissionGroup) {
+        super(context, lifecycle);
         mPermissions = permissions;
         mPermissionGroup = permissionGroup;
         mFeatureProvider = FeatureFactory.getFactory(context)
                 .getApplicationFeatureProvider(context);
+        mAsync = async;
     }
 
     @Override
     public void updateState(Preference preference) {
         mFeatureProvider.calculateNumberOfAppsWithAdminGrantedPermissions(mPermissions,
+                true /* async */,
                 (num) -> {
                     if (num == 0) {
                         preference.setVisible(false);
@@ -55,7 +60,22 @@
 
     @Override
     public boolean isAvailable() {
-        return true;
+        if (mAsync) {
+            // When called on the main UI thread, we must not block. Since calculating the number of
+            // apps that the admin has granted a given permissions takes a bit of time, we always
+            // return true here and determine the pref's actual visibility asynchronously in
+            // updateState().
+            return true;
+        }
+
+        // When called by the search indexer, we are on a background thread that we can block. Also,
+        // changes to the pref's visibility made in updateState() would not be seen by the indexer.
+        // We block and return synchronously whether the admin has granted the given permissions to
+        // any apps or not.
+        final Boolean[] haveAppsWithAdminGrantedPermissions = { null };
+        mFeatureProvider.calculateNumberOfAppsWithAdminGrantedPermissions(mPermissions,
+                false /* async */, (num) -> haveAppsWithAdminGrantedPermissions[0] = num > 0);
+        return haveAppsWithAdminGrantedPermissions[0];
     }
 
     @Override
diff --git a/src/com/android/settings/enterprise/AlwaysOnVpnManagedProfilePreferenceController.java b/src/com/android/settings/enterprise/AlwaysOnVpnManagedProfilePreferenceController.java
index 52625ec..4796b75 100644
--- a/src/com/android/settings/enterprise/AlwaysOnVpnManagedProfilePreferenceController.java
+++ b/src/com/android/settings/enterprise/AlwaysOnVpnManagedProfilePreferenceController.java
@@ -14,30 +14,26 @@
 package com.android.settings.enterprise;
 
 import android.content.Context;
-import android.support.v7.preference.Preference;
 
-import com.android.settings.core.PreferenceController;
+import com.android.settings.core.DynamicAvailabilityPreferenceController;
+import com.android.settings.core.lifecycle.Lifecycle;
 import com.android.settings.overlay.FeatureFactory;
 
-public class AlwaysOnVpnManagedProfilePreferenceController extends PreferenceController {
+public class AlwaysOnVpnManagedProfilePreferenceController
+        extends DynamicAvailabilityPreferenceController {
 
     private static final String KEY_ALWAYS_ON_VPN_MANAGED_PROFILE = "always_on_vpn_managed_profile";
     private final EnterprisePrivacyFeatureProvider mFeatureProvider;
 
-    public AlwaysOnVpnManagedProfilePreferenceController(Context context) {
-        super(context);
+    public AlwaysOnVpnManagedProfilePreferenceController(Context context, Lifecycle lifecycle) {
+        super(context, lifecycle);
         mFeatureProvider = FeatureFactory.getFactory(context)
                 .getEnterprisePrivacyFeatureProvider(context);
     }
 
     @Override
-    public void updateState(Preference preference) {
-        preference.setVisible(mFeatureProvider.isAlwaysOnVpnSetInManagedProfile());
-    }
-
-    @Override
     public boolean isAvailable() {
-        return true;
+        return mFeatureProvider.isAlwaysOnVpnSetInManagedProfile();
     }
 
     @Override
diff --git a/src/com/android/settings/enterprise/AlwaysOnVpnPrimaryUserPreferenceController.java b/src/com/android/settings/enterprise/AlwaysOnVpnPrimaryUserPreferenceController.java
index c7ffeaf..e5823fe 100644
--- a/src/com/android/settings/enterprise/AlwaysOnVpnPrimaryUserPreferenceController.java
+++ b/src/com/android/settings/enterprise/AlwaysOnVpnPrimaryUserPreferenceController.java
@@ -17,16 +17,18 @@
 import android.support.v7.preference.Preference;
 
 import com.android.settings.R;
-import com.android.settings.core.PreferenceController;
+import com.android.settings.core.DynamicAvailabilityPreferenceController;
+import com.android.settings.core.lifecycle.Lifecycle;
 import com.android.settings.overlay.FeatureFactory;
 
-public class AlwaysOnVpnPrimaryUserPreferenceController extends PreferenceController {
+public class AlwaysOnVpnPrimaryUserPreferenceController
+        extends DynamicAvailabilityPreferenceController {
 
     private static final String KEY_ALWAYS_ON_VPN_PRIMARY_USER = "always_on_vpn_primary_user";
     private final EnterprisePrivacyFeatureProvider mFeatureProvider;
 
-    public AlwaysOnVpnPrimaryUserPreferenceController(Context context) {
-        super(context);
+    public AlwaysOnVpnPrimaryUserPreferenceController(Context context, Lifecycle lifecycle) {
+        super(context, lifecycle);
         mFeatureProvider = FeatureFactory.getFactory(context)
                 .getEnterprisePrivacyFeatureProvider(context);
     }
@@ -36,12 +38,11 @@
         preference.setTitle(mFeatureProvider.isInCompMode()
                 ? R.string.enterprise_privacy_always_on_vpn_personal
                 : R.string.enterprise_privacy_always_on_vpn_device);
-        preference.setVisible(mFeatureProvider.isAlwaysOnVpnSetInPrimaryUser());
     }
 
     @Override
     public boolean isAvailable() {
-        return true;
+        return mFeatureProvider.isAlwaysOnVpnSetInPrimaryUser();
     }
 
     @Override
diff --git a/src/com/android/settings/enterprise/CaCertsCurrentUserPreferenceController.java b/src/com/android/settings/enterprise/CaCertsCurrentUserPreferenceController.java
deleted file mode 100644
index c8ea551..0000000
--- a/src/com/android/settings/enterprise/CaCertsCurrentUserPreferenceController.java
+++ /dev/null
@@ -1,60 +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.enterprise;
-
-import android.content.Context;
-import android.content.res.Resources;
-import android.support.v7.preference.Preference;
-
-import com.android.settings.R;
-import com.android.settings.core.PreferenceController;
-import com.android.settings.overlay.FeatureFactory;
-
-public class CaCertsCurrentUserPreferenceController extends PreferenceController {
-
-    private static final String CA_CERTS_CURRENT_USER = "ca_certs_current_user";
-    private final EnterprisePrivacyFeatureProvider mFeatureProvider;
-
-    public CaCertsCurrentUserPreferenceController(Context context) {
-        super(context);
-        mFeatureProvider = FeatureFactory.getFactory(context)
-                .getEnterprisePrivacyFeatureProvider(context);
-    }
-
-    @Override
-    public void updateState(Preference preference) {
-        final int certs = mFeatureProvider.getNumberOfOwnerInstalledCaCertsInCurrentUser();
-        if (certs == 0) {
-            preference.setVisible(false);
-            return;
-        }
-        preference.setTitle(mContext.getResources().getQuantityString(
-                mFeatureProvider.isInCompMode() ? R.plurals.enterprise_privacy_ca_certs_personal :
-                        R.plurals.enterprise_privacy_ca_certs_user, certs));
-        preference.setSummary(mContext.getResources().getQuantityString(
-                R.plurals.enterprise_privacy_number_ca_certs, certs, certs));
-        preference.setVisible(true);
-    }
-
-    @Override
-    public boolean isAvailable() {
-        return true;
-    }
-
-    @Override
-    public String getPreferenceKey() {
-        return CA_CERTS_CURRENT_USER;
-    }
-}
diff --git a/src/com/android/settings/enterprise/CaCertsManagedProfilePreferenceController.java b/src/com/android/settings/enterprise/CaCertsPreferenceController.java
similarity index 64%
rename from src/com/android/settings/enterprise/CaCertsManagedProfilePreferenceController.java
rename to src/com/android/settings/enterprise/CaCertsPreferenceController.java
index 33224ae..d020676 100644
--- a/src/com/android/settings/enterprise/CaCertsManagedProfilePreferenceController.java
+++ b/src/com/android/settings/enterprise/CaCertsPreferenceController.java
@@ -19,41 +19,37 @@
 import android.support.v7.preference.Preference;
 
 import com.android.settings.R;
-import com.android.settings.core.PreferenceController;
+import com.android.settings.core.DynamicAvailabilityPreferenceController;
+import com.android.settings.core.lifecycle.Lifecycle;
 import com.android.settings.overlay.FeatureFactory;
 
-public class CaCertsManagedProfilePreferenceController extends PreferenceController {
+public class CaCertsPreferenceController extends DynamicAvailabilityPreferenceController {
 
-    private static final String KEY_CA_CERTS_MANAGED_PROFILE = "ca_certs_managed_profile";
+    private static final String CA_CERTS = "ca_certs";
     private final EnterprisePrivacyFeatureProvider mFeatureProvider;
 
-    public CaCertsManagedProfilePreferenceController(Context context) {
-        super(context);
+    public CaCertsPreferenceController(Context context, Lifecycle lifecycle) {
+        super(context, lifecycle);
         mFeatureProvider = FeatureFactory.getFactory(context)
                 .getEnterprisePrivacyFeatureProvider(context);
     }
 
     @Override
     public void updateState(Preference preference) {
-        final int certs = mFeatureProvider.getNumberOfOwnerInstalledCaCertsInManagedProfile();
-        if (certs == 0) {
-            preference.setVisible(false);
-            return;
-        }
-        preference.setTitle(mContext.getResources().getQuantityString(
-                R.plurals.enterprise_privacy_ca_certs_work, certs));
+        final int certs =
+                mFeatureProvider.getNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile();
         preference.setSummary(mContext.getResources().getQuantityString(
                 R.plurals.enterprise_privacy_number_ca_certs, certs, certs));
-        preference.setVisible(true);
     }
 
     @Override
     public boolean isAvailable() {
-        return true;
+        return mFeatureProvider.getNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile()
+                > 0;
     }
 
     @Override
     public String getPreferenceKey() {
-        return KEY_CA_CERTS_MANAGED_PROFILE;
+        return CA_CERTS;
     }
 }
diff --git a/src/com/android/settings/enterprise/EnterprisePrivacyFeatureProvider.java b/src/com/android/settings/enterprise/EnterprisePrivacyFeatureProvider.java
index 2270efa..4478865 100644
--- a/src/com/android/settings/enterprise/EnterprisePrivacyFeatureProvider.java
+++ b/src/com/android/settings/enterprise/EnterprisePrivacyFeatureProvider.java
@@ -98,15 +98,9 @@
 
     /**
      * Returns the number of CA certificates that the Device Owner or Profile Owner installed in
-     * the current user.
+     * the current user and the user's managed profile (if any).
      */
-    int getNumberOfOwnerInstalledCaCertsInCurrentUser();
-
-    /**
-     * Returns the number of CA certificates that the Profile Owner installed in the current user's
-     * managed profile (if any).
-     */
-    int getNumberOfOwnerInstalledCaCertsInManagedProfile();
+    int getNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile();
 
     /**
      * Returns the number of Device Admin apps active in the current user and the user's managed
diff --git a/src/com/android/settings/enterprise/EnterprisePrivacyFeatureProviderImpl.java b/src/com/android/settings/enterprise/EnterprisePrivacyFeatureProviderImpl.java
index 6cff807..69eaa2e 100644
--- a/src/com/android/settings/enterprise/EnterprisePrivacyFeatureProviderImpl.java
+++ b/src/com/android/settings/enterprise/EnterprisePrivacyFeatureProviderImpl.java
@@ -189,19 +189,20 @@
     }
 
     @Override
-    public int getNumberOfOwnerInstalledCaCertsInCurrentUser() {
-        final List<String> certs = mDpm.getOwnerInstalledCaCerts(new UserHandle(MY_USER_ID));
-        return certs != null ? certs.size() : 0;
-    }
-
-    @Override
-    public int getNumberOfOwnerInstalledCaCertsInManagedProfile() {
-        final int userId = getManagedProfileUserId();
-        if (userId == UserHandle.USER_NULL) {
-            return 0;
+    public int getNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile() {
+        int num = 0;
+        List<String> certs = mDpm.getOwnerInstalledCaCerts(new UserHandle(MY_USER_ID));
+        if (certs != null) {
+            num += certs.size();
         }
-        final List<String> certs = mDpm.getOwnerInstalledCaCerts(new UserHandle(userId));
-        return certs != null ? certs.size() : 0;
+        final int userId = getManagedProfileUserId();
+        if (userId != UserHandle.USER_NULL) {
+            certs = mDpm.getOwnerInstalledCaCerts(new UserHandle(userId));
+            if (certs != null) {
+                num += certs.size();
+            }
+        }
+        return num;
     }
 
     @Override
diff --git a/src/com/android/settings/enterprise/EnterprisePrivacySettings.java b/src/com/android/settings/enterprise/EnterprisePrivacySettings.java
index 0fb341a..55ec3ea 100644
--- a/src/com/android/settings/enterprise/EnterprisePrivacySettings.java
+++ b/src/com/android/settings/enterprise/EnterprisePrivacySettings.java
@@ -64,18 +64,21 @@
         controllers.add(new SecurityLogsPreferenceController(context));
         controllers.add(new EnterpriseInstalledPackagesPreferenceController(context, lifecycle,
                 async));
-        controllers.add(new AdminGrantedLocationPermissionsPreferenceController(context));
-        controllers.add(new AdminGrantedMicrophonePermissionPreferenceController(context));
-        controllers.add(new AdminGrantedCameraPermissionPreferenceController(context));
+        controllers.add(new AdminGrantedLocationPermissionsPreferenceController(context, lifecycle,
+                async));
+        controllers.add(new AdminGrantedMicrophonePermissionPreferenceController(context, lifecycle,
+                async));
+        controllers.add(new AdminGrantedCameraPermissionPreferenceController(context, lifecycle,
+                async));
         controllers.add(new EnterpriseSetDefaultAppsPreferenceController(context, lifecycle));
-        controllers.add(new AlwaysOnVpnPrimaryUserPreferenceController(context));
-        controllers.add(new AlwaysOnVpnManagedProfilePreferenceController(context));
-        controllers.add(new GlobalHttpProxyPreferenceController(context));
-        controllers.add(new CaCertsCurrentUserPreferenceController(context));
-        controllers.add(new CaCertsManagedProfilePreferenceController(context));
-        controllers.add(new FailedPasswordWipePrimaryUserPreferenceController(context));
-        controllers.add(new FailedPasswordWipeManagedProfilePreferenceController(context));
-        controllers.add(new ImePreferenceController(context));
+        controllers.add(new AlwaysOnVpnPrimaryUserPreferenceController(context, lifecycle));
+        controllers.add(new AlwaysOnVpnManagedProfilePreferenceController(context, lifecycle));
+        controllers.add(new GlobalHttpProxyPreferenceController(context, lifecycle));
+        controllers.add(new CaCertsPreferenceController(context, lifecycle));
+        controllers.add(new FailedPasswordWipePrimaryUserPreferenceController(context, lifecycle));
+        controllers.add(new FailedPasswordWipeManagedProfilePreferenceController(context,
+                lifecycle));
+        controllers.add(new ImePreferenceController(context, lifecycle));
         return controllers;
     }
 
diff --git a/src/com/android/settings/enterprise/FailedPasswordWipeManagedProfilePreferenceController.java b/src/com/android/settings/enterprise/FailedPasswordWipeManagedProfilePreferenceController.java
index 5a0e7c8..205d7c1 100644
--- a/src/com/android/settings/enterprise/FailedPasswordWipeManagedProfilePreferenceController.java
+++ b/src/com/android/settings/enterprise/FailedPasswordWipeManagedProfilePreferenceController.java
@@ -14,6 +14,7 @@
 package com.android.settings.enterprise;
 
 import android.content.Context;
+import com.android.settings.core.lifecycle.Lifecycle;
 
 public class FailedPasswordWipeManagedProfilePreferenceController
         extends FailedPasswordWipePreferenceControllerBase {
@@ -21,8 +22,9 @@
     private static final String KEY_FAILED_PASSWORD_WIPE_MANAGED_PROFILE
             = "failed_password_wipe_managed_profile";
 
-    public FailedPasswordWipeManagedProfilePreferenceController(Context context) {
-        super(context);
+    public FailedPasswordWipeManagedProfilePreferenceController(Context context,
+            Lifecycle lifecycle) {
+        super(context, lifecycle);
     }
 
     @Override
diff --git a/src/com/android/settings/enterprise/FailedPasswordWipePreferenceControllerBase.java b/src/com/android/settings/enterprise/FailedPasswordWipePreferenceControllerBase.java
index ee4aecf..2f35da6 100644
--- a/src/com/android/settings/enterprise/FailedPasswordWipePreferenceControllerBase.java
+++ b/src/com/android/settings/enterprise/FailedPasswordWipePreferenceControllerBase.java
@@ -19,15 +19,17 @@
 import android.support.v7.preference.Preference;
 
 import com.android.settings.R;
-import com.android.settings.core.PreferenceController;
+import com.android.settings.core.DynamicAvailabilityPreferenceController;
+import com.android.settings.core.lifecycle.Lifecycle;
 import com.android.settings.overlay.FeatureFactory;
 
-public abstract class FailedPasswordWipePreferenceControllerBase extends PreferenceController {
+public abstract class FailedPasswordWipePreferenceControllerBase
+        extends DynamicAvailabilityPreferenceController {
 
     protected final EnterprisePrivacyFeatureProvider mFeatureProvider;
 
-    public FailedPasswordWipePreferenceControllerBase(Context context) {
-        super(context);
+    public FailedPasswordWipePreferenceControllerBase(Context context, Lifecycle lifecycle) {
+        super(context, lifecycle);
         mFeatureProvider = FeatureFactory.getFactory(context)
                 .getEnterprisePrivacyFeatureProvider(context);
     }
@@ -37,18 +39,13 @@
     @Override
     public void updateState(Preference preference) {
         final int failedPasswordsBeforeWipe = getMaximumFailedPasswordsBeforeWipe();
-        if (failedPasswordsBeforeWipe == 0) {
-            preference.setVisible(false);
-        } else {
-            preference.setVisible(true);
-            preference.setSummary(mContext.getResources().getQuantityString(
-                    R.plurals.enterprise_privacy_number_failed_password_wipe,
-                    failedPasswordsBeforeWipe, failedPasswordsBeforeWipe));
-        }
+        preference.setSummary(mContext.getResources().getQuantityString(
+                R.plurals.enterprise_privacy_number_failed_password_wipe,
+                failedPasswordsBeforeWipe, failedPasswordsBeforeWipe));
     }
 
     @Override
     public boolean isAvailable() {
-        return true;
+        return getMaximumFailedPasswordsBeforeWipe() > 0;
     }
 }
diff --git a/src/com/android/settings/enterprise/FailedPasswordWipePrimaryUserPreferenceController.java b/src/com/android/settings/enterprise/FailedPasswordWipePrimaryUserPreferenceController.java
index 44c6383..2e18f89 100644
--- a/src/com/android/settings/enterprise/FailedPasswordWipePrimaryUserPreferenceController.java
+++ b/src/com/android/settings/enterprise/FailedPasswordWipePrimaryUserPreferenceController.java
@@ -15,14 +15,16 @@
 
 import android.content.Context;
 
+import com.android.settings.core.lifecycle.Lifecycle;
+
 public class FailedPasswordWipePrimaryUserPreferenceController
         extends FailedPasswordWipePreferenceControllerBase {
 
     private static final String KEY_FAILED_PASSWORD_WIPE_PRIMARY_USER
             = "failed_password_wipe_primary_user";
 
-    public FailedPasswordWipePrimaryUserPreferenceController(Context context) {
-        super(context);
+    public FailedPasswordWipePrimaryUserPreferenceController(Context context, Lifecycle lifecycle) {
+        super(context, lifecycle);
     }
 
     @Override
diff --git a/src/com/android/settings/enterprise/GlobalHttpProxyPreferenceController.java b/src/com/android/settings/enterprise/GlobalHttpProxyPreferenceController.java
index e2f2ab9..6ee7fc4 100644
--- a/src/com/android/settings/enterprise/GlobalHttpProxyPreferenceController.java
+++ b/src/com/android/settings/enterprise/GlobalHttpProxyPreferenceController.java
@@ -14,30 +14,25 @@
 package com.android.settings.enterprise;
 
 import android.content.Context;
-import android.support.v7.preference.Preference;
 
-import com.android.settings.core.PreferenceController;
+import com.android.settings.core.DynamicAvailabilityPreferenceController;
+import com.android.settings.core.lifecycle.Lifecycle;
 import com.android.settings.overlay.FeatureFactory;
 
-public class GlobalHttpProxyPreferenceController extends PreferenceController {
+public class GlobalHttpProxyPreferenceController extends DynamicAvailabilityPreferenceController {
 
     private static final String KEY_GLOBAL_HTTP_PROXY = "global_http_proxy";
     private final EnterprisePrivacyFeatureProvider mFeatureProvider;
 
-    public GlobalHttpProxyPreferenceController(Context context) {
-        super(context);
+    public GlobalHttpProxyPreferenceController(Context context, Lifecycle lifecycle) {
+        super(context, lifecycle);
         mFeatureProvider = FeatureFactory.getFactory(context)
                 .getEnterprisePrivacyFeatureProvider(context);
     }
 
     @Override
-    public void updateState(Preference preference) {
-        preference.setVisible(mFeatureProvider.isGlobalHttpProxySet());
-    }
-
-    @Override
     public boolean isAvailable() {
-        return true;
+        return mFeatureProvider.isGlobalHttpProxySet();
     }
 
     @Override
diff --git a/src/com/android/settings/enterprise/ImePreferenceController.java b/src/com/android/settings/enterprise/ImePreferenceController.java
index 3c0cc26..b090bed 100644
--- a/src/com/android/settings/enterprise/ImePreferenceController.java
+++ b/src/com/android/settings/enterprise/ImePreferenceController.java
@@ -19,35 +19,31 @@
 import android.support.v7.preference.Preference;
 
 import com.android.settings.R;
-import com.android.settings.core.PreferenceController;
+import com.android.settings.core.DynamicAvailabilityPreferenceController;
+import com.android.settings.core.lifecycle.Lifecycle;
 import com.android.settings.overlay.FeatureFactory;
 
-public class ImePreferenceController extends PreferenceController {
+public class ImePreferenceController extends DynamicAvailabilityPreferenceController {
 
     private static final String KEY_INPUT_METHOD = "input_method";
     private final EnterprisePrivacyFeatureProvider mFeatureProvider;
 
-    public ImePreferenceController(Context context) {
-        super(context);
+    public ImePreferenceController(Context context, Lifecycle lifecycle) {
+        super(context, lifecycle);
         mFeatureProvider = FeatureFactory.getFactory(context)
                 .getEnterprisePrivacyFeatureProvider(context);
     }
 
     @Override
     public void updateState(Preference preference) {
-        final String ownerSetIme = mFeatureProvider.getImeLabelIfOwnerSet();
-        if (ownerSetIme == null) {
-            preference.setVisible(false);
-            return;
-        }
         preference.setSummary(mContext.getResources().getString(
-            R.string.enterprise_privacy_input_method_name, ownerSetIme));
-        preference.setVisible(true);
+            R.string.enterprise_privacy_input_method_name,
+            mFeatureProvider.getImeLabelIfOwnerSet()));
     }
 
     @Override
     public boolean isAvailable() {
-        return true;
+        return mFeatureProvider.getImeLabelIfOwnerSet() != null;
     }
 
     @Override
diff --git a/src/com/android/settings/enterprise/ManageDeviceAdminPreferenceController.java b/src/com/android/settings/enterprise/ManageDeviceAdminPreferenceController.java
index 55937ec..6317afe 100644
--- a/src/com/android/settings/enterprise/ManageDeviceAdminPreferenceController.java
+++ b/src/com/android/settings/enterprise/ManageDeviceAdminPreferenceController.java
@@ -36,8 +36,10 @@
     public void updateState(Preference preference) {
         final int activeAdmins
                 = mFeatureProvider.getNumberOfActiveDeviceAdminsForCurrentUserAndManagedProfile();
-        preference.setSummary(mContext.getResources().getQuantityString(
-                R.plurals.number_of_device_admins, activeAdmins, activeAdmins));
+        preference.setSummary(activeAdmins == 0
+                ? mContext.getResources().getString(R.string.number_of_device_admins_none)
+                : mContext.getResources().getQuantityString(R.plurals.number_of_device_admins,
+                        activeAdmins, activeAdmins));
     }
 
     @Override
diff --git a/src/com/android/settings/fuelgauge/BatteryHistoryPreference.java b/src/com/android/settings/fuelgauge/BatteryHistoryPreference.java
index bed2dc5..1f6030e 100644
--- a/src/com/android/settings/fuelgauge/BatteryHistoryPreference.java
+++ b/src/com/android/settings/fuelgauge/BatteryHistoryPreference.java
@@ -19,6 +19,7 @@
 import android.content.Context;
 import android.os.Bundle;
 import android.os.SystemClock;
+import android.support.annotation.VisibleForTesting;
 import android.support.v7.preference.Preference;
 import android.support.v7.preference.PreferenceViewHolder;
 import android.util.AttributeSet;
@@ -36,7 +37,8 @@
  */
 public class BatteryHistoryPreference extends Preference {
 
-    private BatteryInfo mBatteryInfo;
+    @VisibleForTesting
+    BatteryInfo mBatteryInfo;
 
     public BatteryHistoryPreference(Context context, AttributeSet attrs) {
         super(context, attrs);
@@ -57,11 +59,8 @@
         if (mBatteryInfo == null) {
             return;
         }
-        view.setDividerAllowedAbove(true);
+
         ((TextView) view.findViewById(R.id.charge)).setText(mBatteryInfo.batteryPercentString);
-        ((TextView) view.findViewById(R.id.estimation)).setText(
-                mBatteryInfo.remainingLabel != null ?
-                        mBatteryInfo.remainingLabel : mBatteryInfo.statusLabel);
         UsageView usageView = (UsageView) view.findViewById(R.id.battery_usage);
         usageView.findViewById(R.id.label_group).setAlpha(.7f);
         mBatteryInfo.bindHistory(usageView);
diff --git a/src/com/android/settings/wifi/WifiSettings.java b/src/com/android/settings/wifi/WifiSettings.java
index dd17a64..ab1e04e 100644
--- a/src/com/android/settings/wifi/WifiSettings.java
+++ b/src/com/android/settings/wifi/WifiSettings.java
@@ -16,6 +16,8 @@
 
 package com.android.settings.wifi;
 
+import static android.os.UserManager.DISALLOW_CONFIG_WIFI;
+
 import android.annotation.NonNull;
 import android.app.Activity;
 import android.app.Dialog;
@@ -70,12 +72,11 @@
 import com.android.settingslib.wifi.AccessPoint.AccessPointListener;
 import com.android.settingslib.wifi.AccessPointPreference;
 import com.android.settingslib.wifi.WifiTracker;
+import com.android.settingslib.wifi.WifiTrackerFactory;
 
 import java.util.ArrayList;
 import java.util.List;
 
-import static android.os.UserManager.DISALLOW_CONFIG_WIFI;
-
 /**
  * Two types of UI are provided here.
  *
@@ -231,8 +232,8 @@
     public void onActivityCreated(Bundle savedInstanceState) {
         super.onActivityCreated(savedInstanceState);
 
-        mWifiTracker =
-                new WifiTracker(getActivity(), this, mBgThread.getLooper(), true, true, false);
+        mWifiTracker = WifiTrackerFactory.create(
+                getActivity(), this, mBgThread.getLooper(), true, true, false);
         mWifiManager = mWifiTracker.getManager();
 
         mConnectListener = new WifiManager.ActionListener() {
@@ -629,71 +630,11 @@
 
         switch (wifiState) {
             case WifiManager.WIFI_STATE_ENABLED:
-                // AccessPoints are sorted by the WifiTracker
-                final List<AccessPoint> accessPoints = mWifiTracker.getAccessPoints();
-
-                boolean hasAvailableAccessPoints = false;
-                mAccessPointsPreferenceCategory.removePreference(mStatusMessagePreference);
-                cacheRemoveAllPrefs(mAccessPointsPreferenceCategory);
-
-                int index = configureConnectedAccessPointPreferenceCategory(accessPoints) ? 1 : 0;
-                boolean fewerNetworksThanLimit =
-                        accessPoints.size() <= index + NETWORKS_TO_INITIALLY_SHOW;
-                int numAccessPointsToShow = mSeeAllNetworks || fewerNetworksThanLimit
-                        ? accessPoints.size() : index + NETWORKS_TO_INITIALLY_SHOW;
-
-                for (; index < numAccessPointsToShow; index++) {
-                    AccessPoint accessPoint = accessPoints.get(index);
-                    // Ignore access points that are out of range.
-                    if (accessPoint.isReachable()) {
-                        String key = accessPoint.getBssid();
-                        if (TextUtils.isEmpty(key)) {
-                            key = accessPoint.getSsidStr();
-                        }
-                        hasAvailableAccessPoints = true;
-                        LongPressAccessPointPreference pref = (LongPressAccessPointPreference)
-                                getCachedPreference(key);
-                        if (pref != null) {
-                            pref.setOrder(index);
-                            continue;
-                        }
-                        LongPressAccessPointPreference
-                                preference = createLongPressActionPointPreference(accessPoint);
-                        preference.setKey(key);
-                        preference.setOrder(index);
-                        if (mOpenSsid != null && mOpenSsid.equals(accessPoint.getSsidStr())
-                                && !accessPoint.isSaved()
-                                && accessPoint.getSecurity() != AccessPoint.SECURITY_NONE) {
-                            onPreferenceTreeClick(preference);
-                            mOpenSsid = null;
-                        }
-                        mAccessPointsPreferenceCategory.addPreference(preference);
-                        accessPoint.setListener(this);
-                        preference.refresh();
-                    }
-                }
-                removeCachedPrefs(mAccessPointsPreferenceCategory);
-                if (!hasAvailableAccessPoints) {
-                    setProgressBarVisible(true);
-                    Preference pref = new Preference(getPrefContext());
-                    pref.setSelectable(false);
-                    pref.setSummary(R.string.wifi_empty_list_wifi_on);
-                    pref.setOrder(index++);
-                    pref.setKey(PREF_KEY_EMPTY_WIFI_LIST);
-                    mAccessPointsPreferenceCategory.addPreference(pref);
-                } else {
-                    setProgressBarVisible(false);
-                }
-                if (mSeeAllNetworks || fewerNetworksThanLimit) {
-                    mAccessPointsPreferenceCategory.removePreference(mSeeAllNetworksPreference);
-                    mAddPreference.setOrder(index);
-                    mAccessPointsPreferenceCategory.addPreference(mAddPreference);
-                } else {
-                    mAccessPointsPreferenceCategory.removePreference(mAddPreference);
-                    mSeeAllNetworksPreference.setOrder(index);
-                    mAccessPointsPreferenceCategory.addPreference(mSeeAllNetworksPreference);
-                }
-                setConfigureWifiSettingsVisibility();
+                setProgressBarVisible(true);
+                // Have the progress bar displayed before starting to modify APs
+                getView().postDelayed(() -> {
+                        updateAccessPointPreferences();
+                    }, 300 /* delay milliseconds */);
                 break;
 
             case WifiManager.WIFI_STATE_ENABLING:
@@ -715,6 +656,79 @@
         }
     }
 
+    private void updateAccessPointPreferences() {
+        // AccessPoints are sorted by the WifiTracker
+        final List<AccessPoint> accessPoints = mWifiTracker.getAccessPoints();
+
+        boolean hasAvailableAccessPoints = false;
+        mAccessPointsPreferenceCategory.removePreference(mStatusMessagePreference);
+        cacheRemoveAllPrefs(mAccessPointsPreferenceCategory);
+
+        int index =
+                configureConnectedAccessPointPreferenceCategory(accessPoints) ? 1 : 0;
+        boolean fewerNetworksThanLimit =
+                accessPoints.size() <= index + NETWORKS_TO_INITIALLY_SHOW;
+        int numAccessPointsToShow = mSeeAllNetworks || fewerNetworksThanLimit
+                ? accessPoints.size() : index + NETWORKS_TO_INITIALLY_SHOW;
+
+        for (; index < numAccessPointsToShow; index++) {
+            AccessPoint accessPoint = accessPoints.get(index);
+            // Ignore access points that are out of range.
+            if (accessPoint.isReachable()) {
+                String key = accessPoint.getBssid();
+                if (TextUtils.isEmpty(key)) {
+                    key = accessPoint.getSsidStr();
+                }
+                hasAvailableAccessPoints = true;
+                LongPressAccessPointPreference pref =
+                        (LongPressAccessPointPreference) getCachedPreference(key);
+                if (pref != null) {
+                    pref.setOrder(index);
+                    continue;
+                }
+                LongPressAccessPointPreference preference =
+                        createLongPressActionPointPreference(accessPoint);
+                preference.setKey(key);
+                preference.setOrder(index);
+                if (mOpenSsid != null && mOpenSsid.equals(accessPoint.getSsidStr())
+                        && !accessPoint.isSaved()
+                        && accessPoint.getSecurity() != AccessPoint.SECURITY_NONE) {
+                    onPreferenceTreeClick(preference);
+                    mOpenSsid = null;
+                }
+                mAccessPointsPreferenceCategory.addPreference(preference);
+                accessPoint.setListener(WifiSettings.this);
+                preference.refresh();
+            }
+        }
+        removeCachedPrefs(mAccessPointsPreferenceCategory);
+        if (mSeeAllNetworks || fewerNetworksThanLimit) {
+            mAccessPointsPreferenceCategory.removePreference(mSeeAllNetworksPreference);
+            mAddPreference.setOrder(index);
+            mAccessPointsPreferenceCategory.addPreference(mAddPreference);
+        } else {
+            mAccessPointsPreferenceCategory.removePreference(mAddPreference);
+            mSeeAllNetworksPreference.setOrder(index);
+            mAccessPointsPreferenceCategory.addPreference(mSeeAllNetworksPreference);
+        }
+        setConfigureWifiSettingsVisibility();
+
+        if (!hasAvailableAccessPoints) {
+            setProgressBarVisible(true);
+            Preference pref = new Preference(getPrefContext());
+            pref.setSelectable(false);
+            pref.setSummary(R.string.wifi_empty_list_wifi_on);
+            pref.setOrder(index++);
+            pref.setKey(PREF_KEY_EMPTY_WIFI_LIST);
+            mAccessPointsPreferenceCategory.addPreference(pref);
+        } else {
+            // Continuing showing progress bar for an additional delay to overlap with animation
+            getView().postDelayed(() -> {
+                    setProgressBarVisible(false);
+                }, 1700 /* delay millis */);
+        }
+    }
+
     @NonNull
     private LongPressAccessPointPreference createLongPressActionPointPreference(
             AccessPoint accessPoint) {
@@ -844,7 +858,8 @@
 
     protected void setProgressBarVisible(boolean visible) {
         if (mProgressHeader != null) {
-            mProgressHeader.setVisibility(visible && !isUiRestricted() ? View.VISIBLE : View.GONE);
+            mProgressHeader.setVisibility(
+                    visible && !isUiRestricted() ? View.VISIBLE : View.INVISIBLE);
         }
     }
 
diff --git a/tests/robotests/assets/grandfather_not_implementing_indexable b/tests/robotests/assets/grandfather_not_implementing_indexable
index d7ea14c..0f65f89 100644
--- a/tests/robotests/assets/grandfather_not_implementing_indexable
+++ b/tests/robotests/assets/grandfather_not_implementing_indexable
@@ -91,3 +91,4 @@
 com.android.settings.qstile.DevelopmentTileConfigActivity$DevelopmentTileConfigFragment
 com.android.settings.applications.ExternalSourcesDetails
 com.android.settings.applications.PictureInPictureSettings
+com.android.settings.applications.PictureInPictureDetails
diff --git a/tests/robotests/src/com/android/settings/TestUtils.java b/tests/robotests/src/com/android/settings/TestUtils.java
new file mode 100644
index 0000000..16d35f3
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/TestUtils.java
@@ -0,0 +1,26 @@
+/*
+ * 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;
+
+/**
+ * Convenience methods and constants for testing.
+ */
+public class TestUtils {
+    public static final long KILOBYTE = 1024L; // TODO: Change to 1000 in O Robolectric.
+    public static final long MEGABYTE = KILOBYTE * KILOBYTE;
+    public static final long GIGABYTE = KILOBYTE * MEGABYTE;
+}
diff --git a/tests/robotests/src/com/android/settings/applications/AppWithAdminGrantedPermissionsCounterTest.java b/tests/robotests/src/com/android/settings/applications/AppWithAdminGrantedPermissionsCounterTest.java
index 3dd3a65..dfef3b8 100644
--- a/tests/robotests/src/com/android/settings/applications/AppWithAdminGrantedPermissionsCounterTest.java
+++ b/tests/robotests/src/com/android/settings/applications/AppWithAdminGrantedPermissionsCounterTest.java
@@ -89,8 +89,7 @@
         MockitoAnnotations.initMocks(this);
     }
 
-    @Test
-    public void testCountInstalledAppsAcrossAllUsers() throws Exception {
+    private void verifyCountInstalledAppsAcrossAllUsers(boolean async) throws Exception {
         // There are two users.
         mUsersToCount = Arrays.asList(
                 new UserInfo(MAIN_USER_ID, "main", UserInfo.FLAG_ADMIN),
@@ -181,10 +180,14 @@
                 .thenReturn(PackageManager.INSTALL_REASON_UNKNOWN);
 
         // Count the number of all apps installed that were granted on or more permissions by the
-        // admin.  Wait for the background task to finish.
-        (new AppWithAdminGrantedPermissionsCounterTestable(PERMISSIONS)).execute();
-        ShadowApplication.runBackgroundTasks();
-
+        // admin.
+        if (async) {
+            (new AppWithAdminGrantedPermissionsCounterTestable(PERMISSIONS)).execute();
+            // Wait for the background task to finish.
+            ShadowApplication.runBackgroundTasks();
+        } else {
+            (new AppWithAdminGrantedPermissionsCounterTestable(PERMISSIONS)).executeInForeground();
+        }
         assertThat(mAppCount).isEqualTo(3);
 
         // Verify that installed packages were retrieved for the users returned by
@@ -194,7 +197,16 @@
                 eq(MANAGED_PROFILE_ID));
         verify(mPackageManager, atLeast(0)).getInstallReason(anyObject(), anyObject());
         verifyNoMoreInteractions(mPackageManager);
+    }
 
+    @Test
+    public void testCountInstalledAppsAcrossAllUsersSync() throws Exception {
+        verifyCountInstalledAppsAcrossAllUsers(false /* async */);
+    }
+
+    @Test
+    public void testCountInstalledAppsAcrossAllUsersAync() throws Exception {
+        verifyCountInstalledAppsAcrossAllUsers(true /* async */);
     }
 
     private class AppWithAdminGrantedPermissionsCounterTestable extends
diff --git a/tests/robotests/src/com/android/settings/applications/ApplicationFeatureProviderImplTest.java b/tests/robotests/src/com/android/settings/applications/ApplicationFeatureProviderImplTest.java
index 3c8d933..a513f71 100644
--- a/tests/robotests/src/com/android/settings/applications/ApplicationFeatureProviderImplTest.java
+++ b/tests/robotests/src/com/android/settings/applications/ApplicationFeatureProviderImplTest.java
@@ -88,7 +88,7 @@
                 mPackageManagerService, mDevicePolicyManager);
     }
 
-    private void testCalculateNumberOfInstalledApps(boolean async) {
+    private void verifyCalculateNumberOfInstalledApps(boolean async) {
         setUpUsersAndInstalledApps();
 
         when(mPackageManager.getInstallReason(APP_1, new UserHandle(MAIN_USER_ID)))
@@ -117,16 +117,16 @@
 
     @Test
     public void testCalculateNumberOfInstalledAppsSync() {
-        testCalculateNumberOfInstalledApps(false /* async */);
+        verifyCalculateNumberOfInstalledApps(false /* async */);
     }
 
     @Test
     public void testCalculateNumberOfInstalledAppsAsync() {
-        testCalculateNumberOfInstalledApps(true /* async */);
+        verifyCalculateNumberOfInstalledApps(true /* async */);
     }
 
-    @Test
-    public void testCalculateNumberOfAppsWithAdminGrantedPermissions() throws Exception {
+    private void verifyCalculateNumberOfAppsWithAdminGrantedPermissions(boolean async)
+            throws Exception {
         setUpUsersAndInstalledApps();
 
         when(mDevicePolicyManager.getPermissionGrantState(null, APP_1, PERMISSION))
@@ -143,16 +143,26 @@
                 .thenReturn(PackageManager.INSTALL_REASON_POLICY);
 
         mAppCount = -1;
-        mProvider.calculateNumberOfAppsWithAdminGrantedPermissions(new String[] {PERMISSION},
-                (num) -> {
-                    mAppCount = num;
-                });
-        ShadowApplication.runBackgroundTasks();
+        mProvider.calculateNumberOfAppsWithAdminGrantedPermissions(new String[] {PERMISSION}, async,
+                (num) -> mAppCount = num);
+        if (async) {
+            ShadowApplication.runBackgroundTasks();
+        }
         assertThat(mAppCount).isEqualTo(2);
 
     }
 
     @Test
+    public void testCalculateNumberOfAppsWithAdminGrantedPermissionsSync() throws Exception {
+        verifyCalculateNumberOfAppsWithAdminGrantedPermissions(false /* async */);
+    }
+
+    @Test
+    public void testCalculateNumberOfAppsWithAdminGrantedPermissionsAsync() throws Exception {
+        verifyCalculateNumberOfAppsWithAdminGrantedPermissions(true /* async */);
+    }
+
+    @Test
     public void testFindPersistentPreferredActivities() throws Exception {
         when(mUserManager.getUserProfiles()).thenReturn(Arrays.asList(new UserHandle(MAIN_USER_ID),
                 new UserHandle(MANAGED_PROFILE_ID)));
diff --git a/tests/robotests/src/com/android/settings/applications/PictureInPictureSettingsTest.java b/tests/robotests/src/com/android/settings/applications/PictureInPictureDetailsTest.java
similarity index 86%
rename from tests/robotests/src/com/android/settings/applications/PictureInPictureSettingsTest.java
rename to tests/robotests/src/com/android/settings/applications/PictureInPictureDetailsTest.java
index 262c9e0..96a10f1 100644
--- a/tests/robotests/src/com/android/settings/applications/PictureInPictureSettingsTest.java
+++ b/tests/robotests/src/com/android/settings/applications/PictureInPictureDetailsTest.java
@@ -17,8 +17,6 @@
 package com.android.settings.applications;
 
 import android.content.Context;
-import android.content.pm.ActivityInfo;
-import android.content.pm.PackageInfo;
 
 import com.android.internal.logging.nano.MetricsProto;
 import com.android.settings.SettingsRobolectricTestRunner;
@@ -34,40 +32,32 @@
 import org.robolectric.annotation.Config;
 import org.robolectric.util.ReflectionHelpers;
 
-import java.lang.reflect.Field;
-
 import static com.google.common.truth.Truth.assertThat;
 import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.argThat;
-import static org.mockito.Matchers.anyObject;
 import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.atLeast;
 import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
 
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
-public class PictureInPictureSettingsTest {
+public class PictureInPictureDetailsTest {
 
     @Mock(answer = Answers.RETURNS_DEEP_STUBS)
     private Context mContext;
 
     private FakeFeatureFactory mFeatureFactory;
-    private PictureInPictureSettings mFragment;
+    private PictureInPictureDetails mFragment;
 
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
         FakeFeatureFactory.setupForTest(mContext);
         mFeatureFactory = (FakeFeatureFactory) FakeFeatureFactory.getFactory(mContext);
-        mFragment = new PictureInPictureSettings();
+        mFragment = new PictureInPictureDetails();
     }
 
     @Test
     public void testIgnoredApp() {
-        for (String ignoredPackage : mFragment.IGNORE_PACKAGE_LIST) {
+        for (String ignoredPackage : PictureInPictureSettings.IGNORE_PACKAGE_LIST) {
             assertThat(checkPackageHasPictureInPictureActivities(ignoredPackage, true))
                             .isFalse();
         }
@@ -94,11 +84,11 @@
     public void logSpecialPermissionChange() {
         mFragment.logSpecialPermissionChange(true, "app");
         verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
-                eq(MetricsProto.MetricsEvent.APP_PICTURE_IN_PICTURE_ON_HIDE_ALLOW), eq("app"));
+                eq(MetricsProto.MetricsEvent.APP_PICTURE_IN_PICTURE_ALLOW), eq("app"));
 
         mFragment.logSpecialPermissionChange(false, "app");
         verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
-                eq(MetricsProto.MetricsEvent.APP_PICTURE_IN_PICTURE_ON_HIDE_DENY), eq("app"));
+                eq(MetricsProto.MetricsEvent.APP_PICTURE_IN_PICTURE_DENY), eq("app"));
     }
 
     private boolean checkPackageHasPictureInPictureActivities(String packageName,
diff --git a/tests/robotests/src/com/android/settings/deviceinfo/StorageItemPreferenceTest.java b/tests/robotests/src/com/android/settings/deviceinfo/StorageItemPreferenceTest.java
new file mode 100644
index 0000000..f9d26c7
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/deviceinfo/StorageItemPreferenceTest.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2016 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.deviceinfo;
+
+import static com.android.settings.TestUtils.KILOBYTE;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.Context;
+import android.support.v7.preference.PreferenceViewHolder;
+import android.view.LayoutInflater;
+import android.widget.ProgressBar;
+
+import com.android.settings.R;
+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.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class StorageItemPreferenceTest {
+    private Context mContext;
+    private StorageItemPreference mPreference;
+
+    @Before
+    public void setUp() throws Exception {
+        mContext = RuntimeEnvironment.application;
+        mPreference = new StorageItemPreference(mContext);
+    }
+
+    @Test
+    public void testBeforeLoad() {
+        assertThat(mPreference.getSummary()).isEqualTo(
+                mContext.getString(R.string.memory_calculating_size));
+    }
+
+    @Test
+    public void testAfterLoad() {
+        mPreference.setStorageSize(KILOBYTE, KILOBYTE * 10);
+        assertThat(((String) mPreference.getSummary())).isEqualTo("1.00KB");
+    }
+
+    @Test
+    public void testProgressBarPercentageSet() {
+        final PreferenceViewHolder holder = new PreferenceViewHolder(
+                LayoutInflater.from(mContext).inflate(R.layout.storage_item, null));
+        final ProgressBar progressBar =
+                (ProgressBar) holder.itemView.findViewById(android.R.id.progress);
+
+        mPreference.onBindViewHolder(holder);
+        mPreference.setStorageSize(KILOBYTE, KILOBYTE * 10);
+
+        assertThat(progressBar.getProgress()).isEqualTo(10);
+    }
+
+}
\ No newline at end of file
diff --git a/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceAlternateTest.java b/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceAlternateTest.java
deleted file mode 100644
index d2fc504..0000000
--- a/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceAlternateTest.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2016 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.deviceinfo.storage;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import android.content.Context;
-
-import com.android.settings.R;
-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.robolectric.RuntimeEnvironment;
-import org.robolectric.annotation.Config;
-
-
-@RunWith(SettingsRobolectricTestRunner.class)
-@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
-public class StorageItemPreferenceAlternateTest {
-    private Context mContext;
-
-    @Before
-    public void setUp() throws Exception {
-        mContext = RuntimeEnvironment.application;
-    }
-
-    @Test
-    public void testBeforeLoad() {
-        StorageItemPreferenceAlternate pref = new StorageItemPreferenceAlternate(mContext);
-        assertThat(((String) pref.getSummary())).isEqualTo(
-                mContext.getString(R.string.memory_calculating_size));
-    }
-
-    @Test
-    public void testAfterLoad() {
-        StorageItemPreferenceAlternate pref = new StorageItemPreferenceAlternate(mContext);
-        pref.setStorageSize(1024L);
-        assertThat(((String) pref.getSummary())).isEqualTo("1.00KB");
-    }
-}
\ No newline at end of file
diff --git a/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java
index 961a6c7..387bc43 100644
--- a/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java
@@ -15,6 +15,8 @@
  */
 package com.android.settings.deviceinfo.storage;
 
+import static com.android.settings.TestUtils.KILOBYTE;
+
 import static com.google.common.truth.Truth.assertThat;
 
 import static org.mockito.Matchers.any;
@@ -43,6 +45,7 @@
 import com.android.settings.TestConfig;
 import com.android.settings.applications.ManageApplications;
 import com.android.settings.core.instrumentation.MetricsFeatureProvider;
+import com.android.settings.deviceinfo.StorageItemPreference;
 import com.android.settings.testutils.FakeFeatureFactory;
 import com.android.settingslib.applications.StorageStatsSource;
 import com.android.settingslib.deviceinfo.StorageVolumeProvider;
@@ -60,11 +63,6 @@
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class StorageItemPreferenceControllerTest {
-    /**
-     *  In O, this will change to 1000 instead of 1024 due to the formatter properly defining a
-     *  kilobyte.
-     */
-    private static long KILOBYTE = 1024L;
     private Context mContext;
     private VolumeInfo mVolume;
     @Mock(answer = Answers.RETURNS_DEEP_STUBS)
@@ -72,7 +70,7 @@
     @Mock
     private StorageVolumeProvider mSvp;
     private StorageItemPreferenceController mController;
-    private StorageItemPreferenceAlternate mPreference;
+    private StorageItemPreference mPreference;
     private FakeFeatureFactory mFakeFeatureFactory;
     private MetricsFeatureProvider mMetricsFeatureProvider;
 
@@ -87,7 +85,7 @@
         // Note: null is passed as the Lifecycle because we are handling it outside of the normal
         //       Settings fragment lifecycle for test purposes.
         mController = new StorageItemPreferenceController(mContext, mFragment, mVolume, mSvp);
-        mPreference = new StorageItemPreferenceAlternate(mContext);
+        mPreference = new StorageItemPreference(mContext);
 
         // Inflate the preference and the widget.
         LayoutInflater inflater = LayoutInflater.from(mContext);
@@ -190,12 +188,12 @@
 
     @Test
     public void testMeasurementCompletedUpdatesPreferences() {
-        StorageItemPreferenceAlternate audio = new StorageItemPreferenceAlternate(mContext);
-        StorageItemPreferenceAlternate image = new StorageItemPreferenceAlternate(mContext);
-        StorageItemPreferenceAlternate games = new StorageItemPreferenceAlternate(mContext);
-        StorageItemPreferenceAlternate apps = new StorageItemPreferenceAlternate(mContext);
-        StorageItemPreferenceAlternate system = new StorageItemPreferenceAlternate(mContext);
-        StorageItemPreferenceAlternate files = new StorageItemPreferenceAlternate(mContext);
+        StorageItemPreference audio = new StorageItemPreference(mContext);
+        StorageItemPreference image = new StorageItemPreference(mContext);
+        StorageItemPreference games = new StorageItemPreference(mContext);
+        StorageItemPreference apps = new StorageItemPreference(mContext);
+        StorageItemPreference system = new StorageItemPreference(mContext);
+        StorageItemPreference files = new StorageItemPreference(mContext);
         PreferenceScreen screen = mock(PreferenceScreen.class);
         when(screen.findPreference(
                 eq(StorageItemPreferenceController.AUDIO_KEY))).thenReturn(audio);
diff --git a/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageSummaryDonutPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageSummaryDonutPreferenceControllerTest.java
index 2c091f2..444a0d1 100644
--- a/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageSummaryDonutPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageSummaryDonutPreferenceControllerTest.java
@@ -52,12 +52,13 @@
 
 import java.io.File;
 
+import static com.android.settings.TestUtils.KILOBYTE;
+import static com.android.settings.TestUtils.MEGABYTE;
+import static com.android.settings.TestUtils.GIGABYTE;
+
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class StorageSummaryDonutPreferenceControllerTest {
-    private static final long KILOBYTE = 1024; // Note: When O comes around, this value changes!
-    private static final long MEGABYTE = KILOBYTE * KILOBYTE;
-    private static final long GIGABYTE = KILOBYTE * MEGABYTE;
     private Context mContext;
     private StorageSummaryDonutPreferenceController mController;
     private StorageSummaryDonutPreference mPreference;
diff --git a/tests/robotests/src/com/android/settings/enterprise/AdminGrantedCameraPermissionPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/AdminGrantedCameraPermissionPreferenceControllerTest.java
index a998fb5..0281ce5 100644
--- a/tests/robotests/src/com/android/settings/enterprise/AdminGrantedCameraPermissionPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/AdminGrantedCameraPermissionPreferenceControllerTest.java
@@ -39,8 +39,8 @@
     }
 
     @Override
-    public void setUp() {
-        super.setUp();
-        mController = new AdminGrantedCameraPermissionPreferenceController(mContext);
+    protected AdminGrantedPermissionsPreferenceControllerBase createController(boolean async) {
+        return new AdminGrantedCameraPermissionPreferenceController(mContext,null /* lifecycle */,
+                async);
     }
 }
diff --git a/tests/robotests/src/com/android/settings/enterprise/AdminGrantedLocationPermissionsPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/AdminGrantedLocationPermissionsPreferenceControllerTest.java
index e7aa358..d556296 100644
--- a/tests/robotests/src/com/android/settings/enterprise/AdminGrantedLocationPermissionsPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/AdminGrantedLocationPermissionsPreferenceControllerTest.java
@@ -40,8 +40,8 @@
     }
 
     @Override
-    public void setUp() {
-        super.setUp();
-        mController = new AdminGrantedLocationPermissionsPreferenceController(mContext);
+    protected AdminGrantedPermissionsPreferenceControllerBase createController(boolean async) {
+        return new AdminGrantedLocationPermissionsPreferenceController(mContext,
+                null /* lifecycle */, async);
     }
 }
diff --git a/tests/robotests/src/com/android/settings/enterprise/AdminGrantedMicrophonePermissionPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/AdminGrantedMicrophonePermissionPreferenceControllerTest.java
index 8c84af2..e2a45ec 100644
--- a/tests/robotests/src/com/android/settings/enterprise/AdminGrantedMicrophonePermissionPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/AdminGrantedMicrophonePermissionPreferenceControllerTest.java
@@ -39,8 +39,8 @@
     }
 
     @Override
-    public void setUp() {
-        super.setUp();
-        mController = new AdminGrantedMicrophonePermissionPreferenceController(mContext);
+    protected AdminGrantedPermissionsPreferenceControllerBase createController(boolean async) {
+        return new AdminGrantedMicrophonePermissionPreferenceController(mContext,
+                null /* lifecycle */, async);
     }
 }
diff --git a/tests/robotests/src/com/android/settings/enterprise/AdminGrantedPermissionsPreferenceControllerBaseTest.java b/tests/robotests/src/com/android/settings/enterprise/AdminGrantedPermissionsPreferenceControllerBaseTest.java
index 0d53fb6..4da1cd2 100644
--- a/tests/robotests/src/com/android/settings/enterprise/AdminGrantedPermissionsPreferenceControllerBaseTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/AdminGrantedPermissionsPreferenceControllerBaseTest.java
@@ -40,17 +40,16 @@
     }
 
     @Override
-    public void setUp() {
-        super.setUp();
-        mController = new AdminGrantedPermissionsPreferenceControllerBaseTestable();
+    protected AdminGrantedPermissionsPreferenceControllerBase createController(boolean async) {
+        return new AdminGrantedPermissionsPreferenceControllerBaseTestable(async);
     }
 
     private class AdminGrantedPermissionsPreferenceControllerBaseTestable extends
             AdminGrantedPermissionsPreferenceControllerBase {
 
-        AdminGrantedPermissionsPreferenceControllerBaseTestable() {
-            super(AdminGrantedPermissionsPreferenceControllerBaseTest.this.mContext, mPermissions,
-                    mPermissionGroup);
+        AdminGrantedPermissionsPreferenceControllerBaseTestable(boolean async) {
+            super(AdminGrantedPermissionsPreferenceControllerBaseTest.this.mContext,
+                    null /* lifecycle */, async, mPermissions, mPermissionGroup);
         }
 
         @Override
diff --git a/tests/robotests/src/com/android/settings/enterprise/AdminGrantedPermissionsPreferenceControllerTestBase.java b/tests/robotests/src/com/android/settings/enterprise/AdminGrantedPermissionsPreferenceControllerTestBase.java
index 5a70b7a..69e6237 100644
--- a/tests/robotests/src/com/android/settings/enterprise/AdminGrantedPermissionsPreferenceControllerTestBase.java
+++ b/tests/robotests/src/com/android/settings/enterprise/AdminGrantedPermissionsPreferenceControllerTestBase.java
@@ -68,39 +68,56 @@
         MockitoAnnotations.initMocks(this);
         FakeFeatureFactory.setupForTest(mContext);
         mFeatureFactory = (FakeFeatureFactory) FakeFeatureFactory.getFactory(mContext);
+        mController = createController(true /* async */);
     }
 
-    private void setNumberOfPackagesWithAdminGrantedPermissions(int number) {
+    private void setNumberOfPackagesWithAdminGrantedPermissions(int number, boolean async) {
         doAnswer(new Answer() {
             public Object answer(InvocationOnMock invocation) {
                 ((ApplicationFeatureProvider.NumberOfAppsCallback)
-                        invocation.getArguments()[1]).onNumberOfAppsResult(number);
+                        invocation.getArguments()[2]).onNumberOfAppsResult(number);
                 return null;
             }}).when(mFeatureFactory.applicationFeatureProvider)
                     .calculateNumberOfAppsWithAdminGrantedPermissions(eq(mPermissions),
-                            anyObject());
+                            eq(async), anyObject());
     }
 
     @Test
     public void testUpdateState() {
         final Preference preference = new Preference(mContext, null, 0, 0);
-        preference.setVisible(false);
+        preference.setVisible(true);
 
-        setNumberOfPackagesWithAdminGrantedPermissions(20);
+        setNumberOfPackagesWithAdminGrantedPermissions(0, true /* async */);
+        mController.updateState(preference);
+        assertThat(preference.isVisible()).isFalse();
+
+        setNumberOfPackagesWithAdminGrantedPermissions(20, true /* async */);
         when(mContext.getResources().getQuantityString(
                 R.plurals.enterprise_privacy_number_packages_actionable,20, 20))
                 .thenReturn("20 packages");
         mController.updateState(preference);
         assertThat(preference.getSummary()).isEqualTo("20 packages");
         assertThat(preference.isVisible()).isTrue();
-
-        setNumberOfPackagesWithAdminGrantedPermissions(0);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isFalse();
     }
 
     @Test
-    public void testIsAvailable() {
+    public void testIsAvailableSync() {
+        final AdminGrantedPermissionsPreferenceControllerBase controller
+                = createController(false /* async */);
+
+        setNumberOfPackagesWithAdminGrantedPermissions(0, false /* async */);
+        assertThat(controller.isAvailable()).isFalse();
+
+        setNumberOfPackagesWithAdminGrantedPermissions(20, false /* async */);
+        assertThat(controller.isAvailable()).isTrue();
+    }
+
+    @Test
+    public void testIsAvailableAsync() {
+        setNumberOfPackagesWithAdminGrantedPermissions(0, true /* async */);
+        assertThat(mController.isAvailable()).isTrue();
+
+        setNumberOfPackagesWithAdminGrantedPermissions(20, true /* async */);
         assertThat(mController.isAvailable()).isTrue();
     }
 
@@ -125,4 +142,7 @@
     public void testGetPreferenceKey() {
         assertThat(mController.getPreferenceKey()).isEqualTo(mKey);
     }
+
+    protected abstract AdminGrantedPermissionsPreferenceControllerBase createController(
+            boolean async);
 }
diff --git a/tests/robotests/src/com/android/settings/enterprise/AlwaysOnVpnManagedProfilePreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/AlwaysOnVpnManagedProfilePreferenceControllerTest.java
index a52e049..8ac10d1 100644
--- a/tests/robotests/src/com/android/settings/enterprise/AlwaysOnVpnManagedProfilePreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/AlwaysOnVpnManagedProfilePreferenceControllerTest.java
@@ -52,27 +52,18 @@
         MockitoAnnotations.initMocks(this);
         FakeFeatureFactory.setupForTest(mContext);
         mFeatureFactory = (FakeFeatureFactory) FakeFeatureFactory.getFactory(mContext);
-        mController = new AlwaysOnVpnManagedProfilePreferenceController(mContext);
-    }
-
-    @Test
-    public void testUpdateState() {
-        final Preference preference = new Preference(mContext, null, 0, 0);
-        preference.setVisible(true);
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isAlwaysOnVpnSetInManagedProfile())
-                .thenReturn(false);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isFalse();
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isAlwaysOnVpnSetInManagedProfile())
-                .thenReturn(true);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isTrue();
+        mController = new AlwaysOnVpnManagedProfilePreferenceController(mContext,
+                null /* lifecycle */);
     }
 
     @Test
     public void testIsAvailable() {
+        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isAlwaysOnVpnSetInManagedProfile())
+                .thenReturn(false);
+        assertThat(mController.isAvailable()).isFalse();
+
+        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isAlwaysOnVpnSetInManagedProfile())
+                .thenReturn(true);
         assertThat(mController.isAvailable()).isTrue();
     }
 
diff --git a/tests/robotests/src/com/android/settings/enterprise/AlwaysOnVpnPrimaryUserPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/AlwaysOnVpnPrimaryUserPreferenceControllerTest.java
index d504b84..12fdb4f 100644
--- a/tests/robotests/src/com/android/settings/enterprise/AlwaysOnVpnPrimaryUserPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/AlwaysOnVpnPrimaryUserPreferenceControllerTest.java
@@ -56,7 +56,8 @@
         MockitoAnnotations.initMocks(this);
         FakeFeatureFactory.setupForTest(mContext);
         mFeatureFactory = (FakeFeatureFactory) FakeFeatureFactory.getFactory(mContext);
-        mController = new AlwaysOnVpnPrimaryUserPreferenceController(mContext);
+        mController = new AlwaysOnVpnPrimaryUserPreferenceController(mContext,
+                null /* lifecycle */);
         when(mContext.getString(R.string.enterprise_privacy_always_on_vpn_device))
                 .thenReturn(VPN_SET_DEVICE);
         when(mContext.getString(R.string.enterprise_privacy_always_on_vpn_personal))
@@ -66,37 +67,27 @@
     @Test
     public void testUpdateState() {
         final Preference preference = new Preference(mContext, null, 0, 0);
-        preference.setVisible(true);
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isInCompMode()).thenReturn(false);
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isAlwaysOnVpnSetInPrimaryUser())
-                .thenReturn(false);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isFalse();
 
         when(mFeatureFactory.enterprisePrivacyFeatureProvider.isAlwaysOnVpnSetInPrimaryUser())
                 .thenReturn(true);
+
+        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isInCompMode()).thenReturn(false);
         mController.updateState(preference);
-        assertThat(preference.isVisible()).isTrue();
         assertThat(preference.getTitle()).isEqualTo(VPN_SET_DEVICE);
 
         when(mFeatureFactory.enterprisePrivacyFeatureProvider.isInCompMode()).thenReturn(true);
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isAlwaysOnVpnSetInPrimaryUser())
-                .thenReturn(false);
         mController.updateState(preference);
-        assertThat(preference.isVisible()).isFalse();
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isAlwaysOnVpnSetInPrimaryUser())
-                .thenReturn(true);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isTrue();
         assertThat(preference.getTitle()).isEqualTo(VPN_SET_PERSONAL);
     }
 
     @Test
     public void testIsAvailable() {
+        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isAlwaysOnVpnSetInPrimaryUser())
+                .thenReturn(false);
+        assertThat(mController.isAvailable()).isFalse();
+
+        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isAlwaysOnVpnSetInPrimaryUser())
+                .thenReturn(true);
         assertThat(mController.isAvailable()).isTrue();
     }
 
diff --git a/tests/robotests/src/com/android/settings/enterprise/CaCertsCurrentUserPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/CaCertsCurrentUserPreferenceControllerTest.java
deleted file mode 100644
index 3cd63bb..0000000
--- a/tests/robotests/src/com/android/settings/enterprise/CaCertsCurrentUserPreferenceControllerTest.java
+++ /dev/null
@@ -1,147 +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.enterprise;
-
-import android.content.Context;
-import android.content.res.Resources;
-import com.android.settings.R;
-import android.support.v7.preference.Preference;
-
-import com.android.settings.SettingsRobolectricTestRunner;
-import com.android.settings.TestConfig;
-import com.android.settings.testutils.FakeFeatureFactory;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Answers;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.robolectric.annotation.Config;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.when;
-
-/**
- * Tests for {@link CaCertsCurrentUserPreferenceController}.
- */
-@RunWith(SettingsRobolectricTestRunner.class)
-@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
-public final class CaCertsCurrentUserPreferenceControllerTest {
-
-    private final String INSTALLED_CERTS_USER_1 = "cert installed";
-    private final String INSTALLED_CERTS_USER_10 = "certs installed";
-    private final String INSTALLED_CERTS_PERSONAL_1 = "cert installed in personal profile";
-    private final String INSTALLED_CERTS_PERSONAL_10 = "certs installed in personal profile";
-    private final String NUMBER_INSTALLED_CERTS_1 = "1 cert";
-    private final String NUMBER_INSTALLED_CERTS_10 = "10 certs";
-
-    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
-    private Context mContext;
-    private FakeFeatureFactory mFeatureFactory;
-
-    private CaCertsCurrentUserPreferenceController mController;
-
-    @Before
-    public void setUp() {
-        MockitoAnnotations.initMocks(this);
-        FakeFeatureFactory.setupForTest(mContext);
-        mFeatureFactory = (FakeFeatureFactory) FakeFeatureFactory.getFactory(mContext);
-        mController = new CaCertsCurrentUserPreferenceController(mContext);
-
-        when(mContext.getResources().getQuantityString(R.plurals.enterprise_privacy_ca_certs_user,
-                1)).thenReturn(INSTALLED_CERTS_USER_1);
-        when(mContext.getResources().getQuantityString(R.plurals.enterprise_privacy_ca_certs_user,
-                10)).thenReturn(INSTALLED_CERTS_USER_10);
-        when(mContext.getResources().getQuantityString(
-                R.plurals.enterprise_privacy_ca_certs_personal, 1))
-                .thenReturn(INSTALLED_CERTS_PERSONAL_1);
-        when(mContext.getResources().getQuantityString(
-                R.plurals.enterprise_privacy_ca_certs_personal, 10))
-                .thenReturn(INSTALLED_CERTS_PERSONAL_10);
-        when(mContext.getResources().getQuantityString(R.plurals.enterprise_privacy_number_ca_certs,
-                1, 1)).thenReturn(NUMBER_INSTALLED_CERTS_1);
-        when(mContext.getResources().getQuantityString(R.plurals.enterprise_privacy_number_ca_certs,
-                10, 10)).thenReturn(NUMBER_INSTALLED_CERTS_10);
-    }
-
-    @Test
-    public void testUpdateState() {
-        final Preference preference = new Preference(mContext, null, 0, 0);
-        preference.setVisible(true);
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isInCompMode()).thenReturn(false);
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider
-                .getNumberOfOwnerInstalledCaCertsInCurrentUser()).thenReturn(0);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isFalse();
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider
-                .getNumberOfOwnerInstalledCaCertsInCurrentUser()).thenReturn(1);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isTrue();
-        assertThat(preference.getTitle()).isEqualTo(INSTALLED_CERTS_USER_1);
-        assertThat(preference.getSummary()).isEqualTo(NUMBER_INSTALLED_CERTS_1);
-
-        preference.setVisible(false);
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider
-                .getNumberOfOwnerInstalledCaCertsInCurrentUser()).thenReturn(10);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isTrue();
-        assertThat(preference.getTitle()).isEqualTo(INSTALLED_CERTS_USER_10);
-        assertThat(preference.getSummary()).isEqualTo(NUMBER_INSTALLED_CERTS_10);
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isInCompMode()).thenReturn(true);
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider
-                .getNumberOfOwnerInstalledCaCertsInCurrentUser()).thenReturn(0);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isFalse();
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider
-                .getNumberOfOwnerInstalledCaCertsInCurrentUser()).thenReturn(1);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isTrue();
-        assertThat(preference.getTitle()).isEqualTo(INSTALLED_CERTS_PERSONAL_1);
-        assertThat(preference.getSummary()).isEqualTo(NUMBER_INSTALLED_CERTS_1);
-
-        preference.setVisible(false);
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider
-                .getNumberOfOwnerInstalledCaCertsInCurrentUser()).thenReturn(10);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isTrue();
-        assertThat(preference.getTitle()).isEqualTo(INSTALLED_CERTS_PERSONAL_10);
-        assertThat(preference.getSummary()).isEqualTo(NUMBER_INSTALLED_CERTS_10);
-    }
-
-    @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("ca_certs_current_user");
-    }
-}
diff --git a/tests/robotests/src/com/android/settings/enterprise/CaCertsManagedProfilePreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/CaCertsManagedProfilePreferenceControllerTest.java
deleted file mode 100644
index c66128b..0000000
--- a/tests/robotests/src/com/android/settings/enterprise/CaCertsManagedProfilePreferenceControllerTest.java
+++ /dev/null
@@ -1,115 +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.enterprise;
-
-import android.content.Context;
-import android.content.res.Resources;
-import com.android.settings.R;
-import android.support.v7.preference.Preference;
-
-import com.android.settings.SettingsRobolectricTestRunner;
-import com.android.settings.TestConfig;
-import com.android.settings.testutils.FakeFeatureFactory;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Answers;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.robolectric.annotation.Config;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.when;
-
-/**
- * Tests for {@link CaCertsManagedProfilePreferenceController}.
- */
-@RunWith(SettingsRobolectricTestRunner.class)
-@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
-public final class CaCertsManagedProfilePreferenceControllerTest {
-
-    private final String INSTALLED_CERTS_1 = "cert installed";
-    private final String INSTALLED_CERTS_10 = "certs installed";
-    private final String NUMBER_INSTALLED_CERTS_1 = "1 cert";
-    private final String NUMBER_INSTALLED_CERTS_10 = "10 certs";
-
-    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
-    private Context mContext;
-    private FakeFeatureFactory mFeatureFactory;
-
-    private CaCertsManagedProfilePreferenceController mController;
-
-    @Before
-    public void setUp() {
-        MockitoAnnotations.initMocks(this);
-        FakeFeatureFactory.setupForTest(mContext);
-        mFeatureFactory = (FakeFeatureFactory) FakeFeatureFactory.getFactory(mContext);
-        mController = new CaCertsManagedProfilePreferenceController(mContext);
-
-        when(mContext.getResources().getQuantityString(R.plurals.enterprise_privacy_ca_certs_work,
-                1)).thenReturn(INSTALLED_CERTS_1);
-        when(mContext.getResources().getQuantityString(R.plurals.enterprise_privacy_ca_certs_work,
-                10)).thenReturn(INSTALLED_CERTS_10);
-        when(mContext.getResources().getQuantityString(R.plurals.enterprise_privacy_number_ca_certs,
-                1, 1)).thenReturn(NUMBER_INSTALLED_CERTS_1);
-        when(mContext.getResources().getQuantityString(R.plurals.enterprise_privacy_number_ca_certs,
-                10, 10)).thenReturn(NUMBER_INSTALLED_CERTS_10);
-    }
-
-    @Test
-    public void testUpdateState() {
-        final Preference preference = new Preference(mContext, null, 0, 0);
-        preference.setVisible(true);
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider
-                .getNumberOfOwnerInstalledCaCertsInManagedProfile()).thenReturn(0);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isFalse();
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider
-                .getNumberOfOwnerInstalledCaCertsInManagedProfile()).thenReturn(1);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isTrue();
-        assertThat(preference.getTitle()).isEqualTo(INSTALLED_CERTS_1);
-        assertThat(preference.getSummary()).isEqualTo(NUMBER_INSTALLED_CERTS_1);
-
-        preference.setVisible(false);
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider
-                .getNumberOfOwnerInstalledCaCertsInManagedProfile()).thenReturn(10);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isTrue();
-        assertThat(preference.getTitle()).isEqualTo(INSTALLED_CERTS_10);
-        assertThat(preference.getSummary()).isEqualTo(NUMBER_INSTALLED_CERTS_10);
-    }
-
-    @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("ca_certs_managed_profile");
-    }
-}
diff --git a/tests/robotests/src/com/android/settings/enterprise/CaCertsPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/CaCertsPreferenceControllerTest.java
new file mode 100644
index 0000000..fef2e0f
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/enterprise/CaCertsPreferenceControllerTest.java
@@ -0,0 +1,93 @@
+/*
+ * 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.res.Resources;
+import com.android.settings.R;
+import android.support.v7.preference.Preference;
+
+import com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.FakeFeatureFactory;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Answers;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.annotation.Config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests for {@link CaCertsPreferenceController}.
+ */
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public final class CaCertsPreferenceControllerTest {
+
+    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
+    private Context mContext;
+    private FakeFeatureFactory mFeatureFactory;
+
+    private CaCertsPreferenceController mController;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        FakeFeatureFactory.setupForTest(mContext);
+        mFeatureFactory = (FakeFeatureFactory) FakeFeatureFactory.getFactory(mContext);
+        mController = new CaCertsPreferenceController(mContext, null /* lifecycle */);
+    }
+
+    @Test
+    public void testUpdateState() {
+        final Preference preference = new Preference(mContext, null, 0, 0);
+
+        when(mContext.getResources().getQuantityString(R.plurals.enterprise_privacy_number_ca_certs,
+                10, 10)).thenReturn("10 certs");
+        when(mFeatureFactory.enterprisePrivacyFeatureProvider
+                .getNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile()).thenReturn(10);
+        mController.updateState(preference);
+        assertThat(preference.getSummary()).isEqualTo("10 certs");
+    }
+
+    @Test
+    public void testIsAvailable() {
+        when(mFeatureFactory.enterprisePrivacyFeatureProvider
+                .getNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile()).thenReturn(0);
+        assertThat(mController.isAvailable()).isFalse();
+
+        when(mFeatureFactory.enterprisePrivacyFeatureProvider
+                .getNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile()).thenReturn(10);
+        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("ca_certs");
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/enterprise/EnterpriseInstalledPackagesPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/EnterpriseInstalledPackagesPreferenceControllerTest.java
index 6ff1703..98d0fa6 100644
--- a/tests/robotests/src/com/android/settings/enterprise/EnterpriseInstalledPackagesPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/EnterpriseInstalledPackagesPreferenceControllerTest.java
@@ -96,7 +96,7 @@
 
     @Test
     public void testIsAvailableSync() {
-        EnterpriseInstalledPackagesPreferenceController controller
+        final EnterpriseInstalledPackagesPreferenceController controller
                 = new EnterpriseInstalledPackagesPreferenceController(mContext,
                         null /* lifecycle */, false /* async */);
 
diff --git a/tests/robotests/src/com/android/settings/enterprise/EnterprisePrivacyFeatureProviderImplTest.java b/tests/robotests/src/com/android/settings/enterprise/EnterprisePrivacyFeatureProviderImplTest.java
index d4eec19..2afcab9 100644
--- a/tests/robotests/src/com/android/settings/enterprise/EnterprisePrivacyFeatureProviderImplTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/EnterprisePrivacyFeatureProviderImplTest.java
@@ -268,39 +268,45 @@
     }
 
     @Test
-    public void testGetNumberOfOwnerInstalledCaCertsInCurrentUser() {
+    public void testGetNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile() {
         final UserHandle userHandle = new UserHandle(UserHandle.USER_SYSTEM);
-
-        when(mDevicePolicyManager.getOwnerInstalledCaCerts(userHandle))
-                .thenReturn(null);
-        assertThat(mProvider.getNumberOfOwnerInstalledCaCertsInCurrentUser()).isEqualTo(0);
-        when(mDevicePolicyManager.getOwnerInstalledCaCerts(userHandle))
-                .thenReturn(new ArrayList<String>());
-        assertThat(mProvider.getNumberOfOwnerInstalledCaCertsInCurrentUser()).isEqualTo(0);
-        when(mDevicePolicyManager.getOwnerInstalledCaCerts(userHandle))
-                .thenReturn(Arrays.asList(new String[] {"ca1", "ca2"}));
-        assertThat(mProvider.getNumberOfOwnerInstalledCaCertsInCurrentUser()).isEqualTo(2);
-    }
-
-    @Test
-    public void testGetNumberOfOwnerInstalledCaCertsInManagedProfile() {
-        final UserHandle userHandle = new UserHandle(MANAGED_PROFILE_USER_ID);
+        final UserHandle managedProfileUserHandle = new UserHandle(MANAGED_PROFILE_USER_ID);
         final UserInfo managedProfile =
                 new UserInfo(MANAGED_PROFILE_USER_ID, "", "", UserInfo.FLAG_MANAGED_PROFILE);
 
-        mProfiles.add(managedProfile);
+        when(mDevicePolicyManager.getOwnerInstalledCaCerts(managedProfileUserHandle))
+                .thenReturn(Arrays.asList(new String[] {"ca1", "ca2"}));
+
         when(mDevicePolicyManager.getOwnerInstalledCaCerts(userHandle))
                 .thenReturn(null);
-        assertThat(mProvider.getNumberOfOwnerInstalledCaCertsInManagedProfile()).isEqualTo(0);
+        assertThat(mProvider.getNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile())
+                .isEqualTo(0);
         when(mDevicePolicyManager.getOwnerInstalledCaCerts(userHandle))
                 .thenReturn(new ArrayList<String>());
-        assertThat(mProvider.getNumberOfOwnerInstalledCaCertsInManagedProfile()).isEqualTo(0);
+        assertThat(mProvider.getNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile())
+                .isEqualTo(0);
         when(mDevicePolicyManager.getOwnerInstalledCaCerts(userHandle))
                 .thenReturn(Arrays.asList(new String[] {"ca1", "ca2"}));
-        assertThat(mProvider.getNumberOfOwnerInstalledCaCertsInManagedProfile()).isEqualTo(2);
+        assertThat(mProvider.getNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile())
+                .isEqualTo(2);
+
+        mProfiles.add(managedProfile);
+        when(mDevicePolicyManager.getOwnerInstalledCaCerts(managedProfileUserHandle))
+                .thenReturn(null);
+        assertThat(mProvider.getNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile())
+                .isEqualTo(2);
+        when(mDevicePolicyManager.getOwnerInstalledCaCerts(managedProfileUserHandle))
+                .thenReturn(new ArrayList<String>());
+        assertThat(mProvider.getNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile())
+                .isEqualTo(2);
+        when(mDevicePolicyManager.getOwnerInstalledCaCerts(managedProfileUserHandle))
+                .thenReturn(Arrays.asList(new String[] {"ca1", "ca2"}));
+        assertThat(mProvider.getNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile())
+                .isEqualTo(4);
 
         mProfiles.remove(managedProfile);
-        assertThat(mProvider.getNumberOfOwnerInstalledCaCertsInManagedProfile()).isEqualTo(0);
+        assertThat(mProvider.getNumberOfOwnerInstalledCaCertsForCurrentUserAndManagedProfile())
+                .isEqualTo(2);
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/enterprise/EnterprisePrivacySettingsTest.java b/tests/robotests/src/com/android/settings/enterprise/EnterprisePrivacySettingsTest.java
index 46d6b6c..8a11779 100644
--- a/tests/robotests/src/com/android/settings/enterprise/EnterprisePrivacySettingsTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/EnterprisePrivacySettingsTest.java
@@ -117,7 +117,7 @@
 
     private void verifyPreferenceControllers(List<PreferenceController> controllers) {
         assertThat(controllers).isNotNull();
-        assertThat(controllers.size()).isEqualTo(17);
+        assertThat(controllers.size()).isEqualTo(16);
         assertThat(controllers.get(0)).isInstanceOf(InstalledPackagesPreferenceController.class);
         assertThat(controllers.get(1)).isInstanceOf(NetworkLogsPreferenceController.class);
         assertThat(controllers.get(2)).isInstanceOf(BugReportsPreferenceController.class);
@@ -137,13 +137,11 @@
         assertThat(controllers.get(10)).isInstanceOf(
                 AlwaysOnVpnManagedProfilePreferenceController.class);
         assertThat(controllers.get(11)).isInstanceOf(GlobalHttpProxyPreferenceController.class);
-        assertThat(controllers.get(12)).isInstanceOf(CaCertsCurrentUserPreferenceController.class);
+        assertThat(controllers.get(12)).isInstanceOf(CaCertsPreferenceController.class);
         assertThat(controllers.get(13)).isInstanceOf(
-                CaCertsManagedProfilePreferenceController.class);
-        assertThat(controllers.get(14)).isInstanceOf(
                 FailedPasswordWipePrimaryUserPreferenceController.class);
-        assertThat(controllers.get(15)).isInstanceOf(
+        assertThat(controllers.get(14)).isInstanceOf(
                 FailedPasswordWipeManagedProfilePreferenceController.class);
-        assertThat(controllers.get(16)).isInstanceOf(ImePreferenceController.class);
+        assertThat(controllers.get(15)).isInstanceOf(ImePreferenceController.class);
     }
 }
diff --git a/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipeManagedProfilePreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipeManagedProfilePreferenceControllerTest.java
index c9981f9..99c68f8 100644
--- a/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipeManagedProfilePreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipeManagedProfilePreferenceControllerTest.java
@@ -43,7 +43,8 @@
     @Override
     public void setUp() {
         super.setUp();
-        mController = new FailedPasswordWipeManagedProfilePreferenceController(mContext);
+        mController = new FailedPasswordWipeManagedProfilePreferenceController(mContext,
+                null /* lifecycle */);
     }
 
     @Override
diff --git a/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipePreferenceControllerBaseTest.java b/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipePreferenceControllerBaseTest.java
index 1c7b448..74c3de5 100644
--- a/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipePreferenceControllerBaseTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipePreferenceControllerBaseTest.java
@@ -50,7 +50,8 @@
     private class FailedPasswordWipePreferenceControllerBaseTestable extends
             FailedPasswordWipePreferenceControllerBase {
         FailedPasswordWipePreferenceControllerBaseTestable() {
-            super(FailedPasswordWipePreferenceControllerBaseTest.this.mContext);
+            super(FailedPasswordWipePreferenceControllerBaseTest.this.mContext,
+                    null /* lifecycle */);
         }
 
         @Override
diff --git a/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipePreferenceControllerTestBase.java b/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipePreferenceControllerTestBase.java
index aa189e2..c14b71e 100644
--- a/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipePreferenceControllerTestBase.java
+++ b/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipePreferenceControllerTestBase.java
@@ -61,7 +61,6 @@
     @Test
     public void testUpdateState() {
         final Preference preference = new Preference(mContext, null, 0, 0);
-        preference.setVisible(false);
 
         setMaximumFailedPasswordsBeforeWipe(10);
         when(mContext.getResources().getQuantityString(
@@ -69,14 +68,14 @@
                 .thenReturn("10 attempts");
         mController.updateState(preference);
         assertThat(preference.getSummary()).isEqualTo("10 attempts");
-
-        setMaximumFailedPasswordsBeforeWipe(0);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isFalse();
     }
 
     @Test
     public void testIsAvailable() {
+        setMaximumFailedPasswordsBeforeWipe(0);
+        assertThat(mController.isAvailable()).isFalse();
+
+        setMaximumFailedPasswordsBeforeWipe(10);
         assertThat(mController.isAvailable()).isTrue();
     }
 
diff --git a/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipePrimaryUserPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipePrimaryUserPreferenceControllerTest.java
index 65c9828..d74b9b8 100644
--- a/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipePrimaryUserPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/FailedPasswordWipePrimaryUserPreferenceControllerTest.java
@@ -43,7 +43,8 @@
     @Override
     public void setUp() {
         super.setUp();
-        mController = new FailedPasswordWipePrimaryUserPreferenceController(mContext);
+        mController = new FailedPasswordWipePrimaryUserPreferenceController(mContext,
+                null /* lifecycle */);
     }
 
     @Override
diff --git a/tests/robotests/src/com/android/settings/enterprise/GlobalHttpProxyPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/GlobalHttpProxyPreferenceControllerTest.java
index d505bad..a0bc9ee 100644
--- a/tests/robotests/src/com/android/settings/enterprise/GlobalHttpProxyPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/GlobalHttpProxyPreferenceControllerTest.java
@@ -51,27 +51,17 @@
         MockitoAnnotations.initMocks(this);
         FakeFeatureFactory.setupForTest(mContext);
         mFeatureFactory = (FakeFeatureFactory) FakeFeatureFactory.getFactory(mContext);
-        mController = new GlobalHttpProxyPreferenceController(mContext);
-    }
-
-    @Test
-    public void testUpdateState() {
-        final Preference preference = new Preference(mContext, null, 0, 0);
-        preference.setVisible(true);
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isGlobalHttpProxySet())
-                .thenReturn(false);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isFalse();
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isGlobalHttpProxySet())
-                .thenReturn(true);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isTrue();
+        mController = new GlobalHttpProxyPreferenceController(mContext, null /* lifecycle */);
     }
 
     @Test
     public void testIsAvailable() {
+        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isGlobalHttpProxySet())
+                .thenReturn(false);
+        assertThat(mController.isAvailable()).isFalse();
+
+        when(mFeatureFactory.enterprisePrivacyFeatureProvider.isGlobalHttpProxySet())
+                .thenReturn(true);
         assertThat(mController.isAvailable()).isTrue();
     }
 
diff --git a/tests/robotests/src/com/android/settings/enterprise/ImePreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/ImePreferenceControllerTest.java
index 547746c..05d0535 100644
--- a/tests/robotests/src/com/android/settings/enterprise/ImePreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/ImePreferenceControllerTest.java
@@ -57,7 +57,7 @@
         MockitoAnnotations.initMocks(this);
         FakeFeatureFactory.setupForTest(mContext);
         mFeatureFactory = (FakeFeatureFactory) FakeFeatureFactory.getFactory(mContext);
-        mController = new ImePreferenceController(mContext);
+        mController = new ImePreferenceController(mContext, null /* lifecycle */);
         when(mContext.getResources().getString(R.string.enterprise_privacy_input_method_name,
                 DEFAULT_IME_LABEL)).thenReturn(DEFAULT_IME_TEXT);
     }
@@ -65,22 +65,21 @@
     @Test
     public void testUpdateState() {
         final Preference preference = new Preference(mContext, null, 0, 0);
-        preference.setVisible(true);
-
-        when(mFeatureFactory.enterprisePrivacyFeatureProvider.getImeLabelIfOwnerSet())
-            .thenReturn(null);
-        mController.updateState(preference);
-        assertThat(preference.isVisible()).isFalse();
 
         when(mFeatureFactory.enterprisePrivacyFeatureProvider.getImeLabelIfOwnerSet())
             .thenReturn(DEFAULT_IME_LABEL);
         mController.updateState(preference);
-        assertThat(preference.isVisible()).isTrue();
         assertThat(preference.getSummary()).isEqualTo(DEFAULT_IME_TEXT);
     }
 
     @Test
     public void testIsAvailable() {
+        when(mFeatureFactory.enterprisePrivacyFeatureProvider.getImeLabelIfOwnerSet())
+            .thenReturn(null);
+        assertThat(mController.isAvailable()).isFalse();
+
+        when(mFeatureFactory.enterprisePrivacyFeatureProvider.getImeLabelIfOwnerSet())
+            .thenReturn(DEFAULT_IME_LABEL);
         assertThat(mController.isAvailable()).isTrue();
     }
 
diff --git a/tests/robotests/src/com/android/settings/enterprise/ManageDeviceAdminPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/ManageDeviceAdminPreferenceControllerTest.java
index 5cb6377..d3f5e97 100644
--- a/tests/robotests/src/com/android/settings/enterprise/ManageDeviceAdminPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/ManageDeviceAdminPreferenceControllerTest.java
@@ -62,6 +62,13 @@
         final Preference preference = new Preference(mContext, null, 0, 0);
 
         when(mFeatureFactory.enterprisePrivacyFeatureProvider
+                .getNumberOfActiveDeviceAdminsForCurrentUserAndManagedProfile()).thenReturn(0);
+        when(mContext.getResources().getString(R.string.number_of_device_admins_none))
+                .thenReturn("no apps");
+        mController.updateState(preference);
+        assertThat(preference.getSummary()).isEqualTo("no apps");
+
+        when(mFeatureFactory.enterprisePrivacyFeatureProvider
                 .getNumberOfActiveDeviceAdminsForCurrentUserAndManagedProfile()).thenReturn(5);
         when(mContext.getResources().getQuantityString(R.plurals.number_of_device_admins, 5, 5))
                 .thenReturn("5 active apps");
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/BatteryHistoryPreferenceTest.java b/tests/robotests/src/com/android/settings/fuelgauge/BatteryHistoryPreferenceTest.java
new file mode 100644
index 0000000..471f9ea
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/fuelgauge/BatteryHistoryPreferenceTest.java
@@ -0,0 +1,90 @@
+/*
+ * 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.fuelgauge;
+
+import android.content.Context;
+import android.os.PowerManager;
+import android.support.v7.preference.PreferenceViewHolder;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.TextView;
+
+import com.android.settings.R;
+import com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.TestConfig;
+import com.android.settingslib.BatteryInfo;
+import com.android.settingslib.graph.UsageView;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+import org.robolectric.util.ReflectionHelpers;
+
+import static org.mockito.AdditionalMatchers.not;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class BatteryHistoryPreferenceTest {
+    @Mock
+    private PreferenceViewHolder mViewHolder;
+    @Mock
+    private BatteryInfo mBatteryInfo;
+    @Mock
+    private TextView mTextView;
+    @Mock
+    private View mItemView;
+    @Mock
+    private UsageView mUsageView;
+    @Mock
+    private View mLabelView;
+    private BatteryHistoryPreference mBatteryHistoryPreference;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        final Context context = RuntimeEnvironment.application;
+        final View itemView = LayoutInflater.from(context).inflate(R.layout.battery_usage_graph,
+                null);
+
+        mBatteryHistoryPreference = new BatteryHistoryPreference(context, null);
+        mBatteryHistoryPreference.mBatteryInfo = mBatteryInfo;
+        mViewHolder = spy(new PreferenceViewHolder(itemView));
+        when(mViewHolder.findViewById(R.id.battery_usage)).thenReturn(mUsageView);
+        when(mViewHolder.findViewById(R.id.charge)).thenReturn(mTextView);
+        when(mUsageView.findViewById(anyInt())).thenReturn(mLabelView);
+    }
+
+    @Test
+    public void testOnBindViewHolder_updateBatteryUsage() {
+        mBatteryHistoryPreference.onBindViewHolder(mViewHolder);
+
+        verify(mViewHolder).findViewById(R.id.battery_usage);
+        verify(mTextView).setText(anyString());
+        verify(mBatteryInfo).bindHistory(mUsageView);
+    }
+}