Merge "Send ACTION_KEYCHAIN_CHANGED when installing a cert" into oc-dev
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index da88f76..c7610f6 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -440,13 +440,6 @@
             </intent-filter>
         </activity>
 
-        <receiver
-            android:name=".HotspotOffReceiver" >
-            <intent-filter>
-                <action android:name="android.net.wifi.WIFI_AP_STATE_CHANGED" />
-            </intent-filter>
-        </receiver>
-
         <activity android:name="Settings$TetherSettingsActivity"
                 android:label="@string/tether_settings_title_all"
                 android:icon="@drawable/ic_settings_wireless"
@@ -902,23 +895,13 @@
                 android:icon="@drawable/ic_settings_night_display"
                 android:taskAffinity="">
             <intent-filter android:priority="1">
-                <action android:name="android.intent.action.MAIN" />
-                <category android:name="com.android.settings.suggested.category.SETTINGS_ONLY" />
-            </intent-filter>
-            <intent-filter android:priority="1">
                 <action android:name="android.settings.NIGHT_DISPLAY_SETTINGS" />
                 <category android:name="android.intent.category.DEFAULT" />
             </intent-filter>
-            <meta-data android:name="com.android.settings.PRIMARY_PROFILE_CONTROLLED"
-                android:value="true" />
             <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
                 android:value="com.android.settings.display.NightDisplaySettings" />
-            <meta-data android:name="com.android.settings.dismiss"
-                android:value="30" />
-            <meta-data android:name="com.android.settings.title"
-                android:resource="@string/night_display_suggestion_title" />
-            <meta-data android:name="com.android.settings.summary"
-                android:resource="@string/night_display_suggestion_summary" />
+            <meta-data android:name="com.android.settings.PRIMARY_PROFILE_CONTROLLED"
+                android:value="true" />
         </activity>
 
         <activity android:name="Settings$DeviceInfoSettingsActivity"
@@ -2813,7 +2796,7 @@
         </provider>
 
         <activity android:name="Settings$OverlaySettingsActivity"
-                android:label="@string/draw_overlay_title"
+                android:label="@string/draw_overlay"
                 android:taskAffinity="">
             <intent-filter android:priority="1">
                 <action android:name="android.settings.action.MANAGE_OVERLAY_PERMISSION" />
@@ -2824,7 +2807,7 @@
         </activity>
 
         <activity android:name="Settings$AppDrawOverlaySettingsActivity"
-                android:label="@string/draw_overlay_title"
+                android:label="@string/draw_overlay"
                 android:taskAffinity="">
             <intent-filter android:priority="1">
                 <action android:name="android.settings.action.MANAGE_OVERLAY_PERMISSION" />
@@ -2863,7 +2846,7 @@
                 android:label="@string/install_other_apps"
                 android:taskAffinity="">
             <intent-filter android:priority="1">
-                <action android:name="android.settings.action.MANAGE_EXTERNAL_SOURCES" />
+                <action android:name="android.settings.action.MANAGE_UNKNOWN_APP_SOURCES" />
                 <category android:name="android.intent.category.DEFAULT" />
             </intent-filter>
             <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
@@ -2874,7 +2857,7 @@
                   android:label="@string/install_other_apps"
                   android:taskAffinity="">
             <intent-filter android:priority="1">
-                <action android:name="android.settings.action.MANAGE_EXTERNAL_SOURCES" />
+                <action android:name="android.settings.action.MANAGE_UNKNOWN_APP_SOURCES" />
                 <category android:name="android.intent.category.DEFAULT" />
                 <data android:scheme="package" />
             </intent-filter>
diff --git a/res/layout/app_details.xml b/res/layout/app_details.xml
index 4aa1496..5ffeec5 100644
--- a/res/layout/app_details.xml
+++ b/res/layout/app_details.xml
@@ -26,17 +26,23 @@
     android:paddingStart="?android:attr/listPreferredItemPaddingStart"
     android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
     android:paddingTop="24dp"
-    android:paddingBottom="24dp" >
+    android:paddingBottom="24dp"
+    android:clipChildren="false"
+    android:clipToPadding="false">
 
     <!-- App snippet with buttons -->
     <RelativeLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
-        android:paddingStart="8dp">
+        android:paddingStart="8dp"
+        android:clipChildren="false"
+        android:clipToPadding="false">
 
         <FrameLayout android:id="@+id/app_icon_frame"
                      android:layout_width="80dp"
-                     android:layout_height="80dp">
+                     android:layout_height="80dp"
+                     android:clipChildren="false"
+                     android:clipToPadding="false">
             <ImageView
                 android:id="@+id/app_detail_icon"
                 android:layout_width="match_parent"
diff --git a/res/layout/preference_bluetooth.xml b/res/layout/preference_bluetooth.xml
deleted file mode 100644
index c339e67..0000000
--- a/res/layout/preference_bluetooth.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2006 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:gravity="center_vertical">
-
-    <!-- Details button -->
-    <ImageView
-        android:id="@+id/deviceDetails"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center_vertical"
-        android:padding="8dip"
-        android:background="?android:attr/selectableItemBackground"
-        android:src="@drawable/ic_settings"
-        android:contentDescription="@string/bluetooth_device_details" />
-
-</LinearLayout>
diff --git a/res/layout/preference_progress_category.xml b/res/layout/preference_progress_category.xml
index 1380698..9f5a8b4 100644
--- a/res/layout/preference_progress_category.xml
+++ b/res/layout/preference_progress_category.xml
@@ -35,7 +35,6 @@
             android:id="@android:id/icon"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:tint="?android:attr/textColorPrimary"
             android:maxWidth="18dp"
             android:maxHeight="18dp"/>
     </LinearLayout>
@@ -47,7 +46,8 @@
         android:layout_height="wrap_content"
         android:layout_weight="1"
         android:layout_gravity="start|center"
-        android:textAppearance="@android:style/TextAppearance.Material.Body2"/>
+        android:textAppearance="@android:style/TextAppearance.Material.Body2"
+        android:textColor="?android:attr/colorAccent"/>
 
     <ProgressBar
         android:id="@+id/scanning_progress"
diff --git a/res/layout/preference_widget_summary.xml b/res/layout/preference_widget_summary.xml
index aa4c76b..2d7ed1d 100644
--- a/res/layout/preference_widget_summary.xml
+++ b/res/layout/preference_widget_summary.xml
@@ -18,5 +18,6 @@
     android:id="@+id/widget_summary"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
+    android:textAlignment="viewEnd"
     android:textAppearance="?android:attr/textAppearanceSmall"
     android:textColor="?android:attr/textColorSecondary" />
diff --git a/res/layout/vpn_dialog.xml b/res/layout/vpn_dialog.xml
index 7731e6d..47be368 100644
--- a/res/layout/vpn_dialog.xml
+++ b/res/layout/vpn_dialog.xml
@@ -28,16 +28,22 @@
                 android:orientation="vertical"
                 android:visibility="gone">
 
-            <TextView style="@style/vpn_label" android:text="@string/vpn_name"/>
+            <TextView style="@style/vpn_label"
+                    android:text="@string/vpn_name"
+                    android:labelFor="@+id/name"/>
             <EditText style="@style/vpn_value" android:id="@+id/name"
                     android:inputType="textCapWords"/>
 
-            <TextView style="@style/vpn_label" android:text="@string/vpn_type"/>
+            <TextView style="@style/vpn_label"
+                    android:text="@string/vpn_type"
+                    android:labelFor="@+id/type"/>
             <Spinner style="@style/vpn_value" android:id="@+id/type"
                     android:prompt="@string/vpn_type"
                     android:entries="@array/vpn_types"/>
 
-            <TextView style="@style/vpn_label" android:text="@string/vpn_server"/>
+            <TextView style="@style/vpn_label"
+                    android:text="@string/vpn_server"
+                    android:labelFor="@+id/server"/>
             <EditText style="@style/vpn_value" android:id="@+id/server"/>
 
             <CheckBox style="@style/vpn_value" android:id="@+id/mppe"
@@ -50,7 +56,9 @@
                     android:layout_height="wrap_content"
                     android:orientation="vertical"
                     android:visibility="gone">
-                <TextView style="@style/vpn_label" android:text="@string/vpn_l2tp_secret"/>
+                <TextView style="@style/vpn_label"
+                        android:text="@string/vpn_l2tp_secret"
+                        android:labelFor="@+id/l2tp_secret"/>
                 <EditText style="@style/vpn_value" android:id="@+id/l2tp_secret"
                         android:password="true"
                         android:hint="@string/vpn_not_used"/>
@@ -61,11 +69,15 @@
                     android:layout_height="wrap_content"
                     android:orientation="vertical"
                     android:visibility="gone">
-                <TextView style="@style/vpn_label" android:text="@string/vpn_ipsec_identifier"/>
+                <TextView style="@style/vpn_label"
+                        android:text="@string/vpn_ipsec_identifier"
+                        android:labelFor="@+id/ipsec_identifier"/>
                 <EditText style="@style/vpn_value" android:id="@+id/ipsec_identifier"
                         android:hint="@string/vpn_not_used"/>
 
-                <TextView style="@style/vpn_label" android:text="@string/vpn_ipsec_secret"/>
+                <TextView style="@style/vpn_label"
+                        android:text="@string/vpn_ipsec_secret"
+                        android:labelFor="@+id/ipsec_secret"/>
                 <EditText style="@style/vpn_value" android:id="@+id/ipsec_secret"
                         android:password="true"/>
             </LinearLayout>
@@ -75,7 +87,9 @@
                     android:layout_height="wrap_content"
                     android:orientation="vertical"
                     android:visibility="gone">
-                <TextView style="@style/vpn_label" android:text="@string/vpn_ipsec_user_cert"/>
+                <TextView style="@style/vpn_label"
+                        android:text="@string/vpn_ipsec_user_cert"
+                        android:labelFor="@+id/ipsec_user_cert"/>
                 <Spinner style="@style/vpn_value" android:id="@+id/ipsec_user_cert"
                         android:prompt="@string/vpn_ipsec_user_cert" />
             </LinearLayout>
@@ -85,10 +99,15 @@
                     android:layout_height="wrap_content"
                     android:orientation="vertical"
                     android:visibility="gone">
-                <TextView style="@style/vpn_label" android:text="@string/vpn_ipsec_ca_cert"/>
+                <TextView style="@style/vpn_label"
+                        android:text="@string/vpn_ipsec_ca_cert"
+                        android:labelFor="@+id/ipsec_ca_cert"/>
                 <Spinner style="@style/vpn_value" android:id="@+id/ipsec_ca_cert"
                         android:prompt="@string/vpn_ipsec_ca_cert" />
-                <TextView style="@style/vpn_label" android:text="@string/vpn_ipsec_server_cert"/>
+
+                <TextView style="@style/vpn_label"
+                        android:text="@string/vpn_ipsec_server_cert"
+                        android:labelFor="@+id/ipsec_server_cert"/>
                 <Spinner style="@style/vpn_value" android:id="@+id/ipsec_server_cert"
                         android:prompt="@string/vpn_ipsec_server_cert" />
             </LinearLayout>
@@ -103,15 +122,21 @@
                 android:layout_height="wrap_content"
                 android:orientation="vertical"
                 android:visibility="gone">
-            <TextView style="@style/vpn_label" android:text="@string/vpn_search_domains"/>
+            <TextView style="@style/vpn_label"
+                    android:text="@string/vpn_search_domains"
+                    android:labelFor="@+id/search_domains"/>
             <EditText style="@style/vpn_value" android:id="@+id/search_domains"
                     android:hint="@string/vpn_not_used"/>
 
-            <TextView style="@style/vpn_label" android:text="@string/vpn_dns_servers"/>
+            <TextView style="@style/vpn_label"
+                    android:text="@string/vpn_dns_servers"
+                    android:labelFor="@+id/dns_servers"/>
             <EditText style="@style/vpn_value" android:id="@+id/dns_servers"
                     android:hint="@string/vpn_not_used"/>
 
-            <TextView style="@style/vpn_label" android:text="@string/vpn_routes"/>
+            <TextView style="@style/vpn_label"
+                    android:text="@string/vpn_routes"
+                    android:labelFor="@+id/routes"/>
             <EditText style="@style/vpn_value" android:id="@+id/routes"
                     android:hint="@string/vpn_not_used"/>
         </LinearLayout>
@@ -122,10 +147,14 @@
                 android:orientation="vertical"
                 android:animateLayoutChanges="true">
 
-            <TextView style="@style/vpn_label" android:text="@string/vpn_username"/>
+            <TextView style="@style/vpn_label"
+                    android:text="@string/vpn_username"
+                    android:labelFor="@+id/username"/>
             <EditText style="@style/vpn_value" android:id="@+id/username"/>
 
-            <TextView style="@style/vpn_label" android:text="@string/vpn_password"/>
+            <TextView style="@style/vpn_label"
+                    android:text="@string/vpn_password"
+                    android:labelFor="@+id/password"/>
             <EditText style="@style/vpn_value" android:id="@+id/password"
                     android:password="true"/>
 
diff --git a/res/values/arrays.xml b/res/values/arrays.xml
index 8980568..873576c 100644
--- a/res/values/arrays.xml
+++ b/res/values/arrays.xml
@@ -388,6 +388,21 @@
         <item>GTC</item>
     </string-array>
 
+    <!-- Type of EAP method when EAP SIM, AKA, AKA' are supported -->
+    <string-array name="wifi_peap_phase2_entries_with_sim_auth">
+        <item>None</item>
+        <!-- Do not translate. -->
+        <item>MSCHAPV2</item>
+        <!-- Do not translate. -->
+        <item>GTC</item>
+        <!-- Do not translate. -->
+        <item>SIM</item>
+        <!-- Do not translate. -->
+        <item>AKA</item>
+        <!-- Do not translate. -->
+        <item>AKA\'</item>
+    </string-array>
+
     <!-- Phase 2 options for rest of EAP methods -->
     <string-array name="wifi_phase2_entries">
         <item>None</item>
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index 5efaf1e..09f7cda 100755
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -240,6 +240,8 @@
     <dimen name="mdm_app_name_padding_left">16dp</dimen>
     <dimen name="mdm_app_icon_width_height">56dp</dimen>
 
+    <!-- Launcher Icons -->
+    <dimen name="launcher_icon_elevation">6dp</dimen>
     <dimen name="shortcut_size_maskable">120dp</dimen>
     <dimen name="shortcut_size">40dp</dimen>
     <dimen name="shortcut_icon_size">16dp</dimen>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index f6b36b4..d5a4189 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -743,7 +743,7 @@
     <!-- Main Settings screen setting option title for the item to take you to the accounts screen [CHAR LIMIT=22] -->
     <string name="account_settings_title">Accounts</string>
     <!-- Main Settings screen setting option title for the item to take you to the security screen -->
-    <string name="security_settings_title">Security &amp; screen lock</string>
+    <string name="security_settings_title">Security &amp; Location</string>
     <!-- Security Settings screen setting option title for the item to take you to the encryption and credential screen -->
     <string name="encryption_and_credential_settings_title">Encryption &amp; credentials</string>
     <!-- Security Settings screen Encryption and crendential summary -->
@@ -762,9 +762,9 @@
     <!-- In the security screen, the header title for security statuses -->
     <string name="security_status_title">Security status</string>
     <!-- Summary for Security settings, explaining a few important settings under it [CHAR LIMIT=NONE]-->
-    <string name="security_dashboard_summary">Location, fingerprint</string>
+    <string name="security_dashboard_summary">Screen lock, fingerprint</string>
     <!-- Summary for Security settings when fingerprint is not supported [CHAR LIMIT=NONE]-->
-    <string name="security_dashboard_summary_no_fingerprint">Location</string>
+    <string name="security_dashboard_summary_no_fingerprint">Screen lock</string>
     <!-- Fingerprint enrollment and settings --><skip />
     <!-- Title shown for menu item that launches fingerprint settings or enrollment [CHAR LIMIT=22] -->
     <string name="security_settings_fingerprint_preference_title">Fingerprint</string>
@@ -1886,11 +1886,11 @@
 
     <!-- Wifi Network Details -->
     <!-- Wifi details preference title to display router IP subnet mask -->
-    <string name="wifi_details_subnet_mask">Subnet Mask</string>
+    <string name="wifi_details_subnet_mask">Subnet mask</string>
     <!-- Wifi details preference title to display router DNS info -->
     <string name="wifi_details_dns">DNS</string>
     <!-- Wifi details preference category title for IPv6 information -->
-    <string name="wifi_details_ipv6_address_header">IPv6 Addresses</string>
+    <string name="wifi_details_ipv6_address_header">IPv6 addresses</string>
 
     <!-- Wifi saved access points.  Used as a label under the shortcut icon that goes to Wifi saved access points. [CHAR LIMIT=20] -->
     <string name="wifi_saved_access_points_label">Saved networks</string>
@@ -2365,6 +2365,8 @@
     <string name="screensaver_settings_disabled_prompt">To control what happens when the phone is docked and/or sleeping, turn screen saver on.</string>
     <!-- Dream settings screen, action label, when to dream -->
     <string name="screensaver_settings_when_to_dream">When to start</string>
+    <!-- Dream settings screen, action label, current selected screen saver -->
+    <string name="screensaver_settings_current">Current screen saver</string>
     <!-- Dream settings screen, button label to start dreaming -->
     <string name="screensaver_settings_dream_start">Start now</string>
     <!-- Dream settings screen, button label for settings for a specific screensaver -->
@@ -3065,7 +3067,7 @@
     <string name="tether_settings_title_bluetooth">Bluetooth tethering</string>
     <!-- Tethering controls, item title to go into the tethering settings when USB and Bluetooth tethering are available [CHAR LIMIT=25]-->
     <string name="tether_settings_title_usb_bluetooth">Tethering</string>
-    <!-- Tethering controls, item title to go into the tethering settings when USB, Bluetooth and Wifi tethering are available [CHAR LIMIT=50]-->
+    <!-- Tethering controls, item title to go into the tethering settings when USB, Bluetooth and Wifi tethering are available [CHAR LIMIT=60]-->
     <string name="tether_settings_title_all">Hotspot &amp; tethering</string>
     <!-- Tethering setting summary when both Wi-Fi hotspot and tether are turned on [CHAR LIMIT=NONE]-->
     <string name="tether_settings_summary_hotspot_on_tether_on">Hotspot on, tethering</string>
@@ -3861,7 +3863,7 @@
     <string name="language_settings">Languages&#160;&amp; input</string>
     <!-- Title of Languages & input settings screen -->
     <string name="language_keyboard_settings_title">Languages&#160;&amp; input</string>
-    <!-- Title of preference category that lists all settings about helping user input such as spell checker [CHAR LIMIT=60]-->
+    <!-- Title of preference category that lists all settings about helping user text input such as spell checker [CHAR LIMIT=60]-->
     <string name="input_assistance">Input assistance</string>
     <!-- On Languages & input settings screen, heading. Inside the "Languages & input settings" screen, this is the header for settings that relate to keyboard (enable/disable each keyboard, settings for each keyboard). -->
     <string name="keyboard_settings_category">Keyboard &amp; input methods</string>
@@ -6424,10 +6426,10 @@
     <!--  Do not disturb: Title for the zen mode automation listing. [CHAR LIMIT=30] -->
     <string name="zen_mode_automation_settings_title">Automatic rules</string>
 
-    <!--  Do not disturb: Title for the zen mode automation option Suggestion. [CHAR LIMIT=30] -->
+    <!--  Do not disturb: Title for the zen mode automation option Suggestion. [CHAR LIMIT=50] -->
     <string name="zen_mode_automation_suggestion_title">Set Do Not Disturb rules</string>
 
-    <!--  Do not disturb: Summary for the zen mode automation option Suggestion. [CHAR LIMIT=30] -->
+    <!--  Do not disturb: Summary for the zen mode automation option Suggestion. [CHAR LIMIT=NONE] -->
     <string name="zen_mode_automation_suggestion_summary">Limit sounds &amp; vibrations at certain times</string>
 
     <!--  Do not disturb: Zen mode option: Important interruptions [CHAR LIMIT=60] -->
@@ -7613,8 +7615,6 @@
     <string name="accessibility_lock_screen_progress"><xliff:g id="count" example="1">%1$d</xliff:g> of <xliff:g id="count" example="1">%2$d</xliff:g> characters used</string>
 
     <!-- System Alert Window settings -->
-    <!-- Title of display overlay preference item [CHAR LIMIT=55] -->
-    <string name="draw_overlay_title">Apps that can display over other apps</string>
     <!-- Title of display overlay screen [CHAR LIMIT=30] -->
     <string name="draw_overlay">Display over other apps</string>
     <!-- Settings title in main settings screen for SYSTEM_ALERT_WINDOW [CHAR LIMIT=45] -->
@@ -7871,12 +7871,6 @@
     <!-- Summary of condition that work mode is off [CHAR LIMIT=NONE] -->
     <string name="condition_work_summary">Apps, background sync, and other features related to your work profile are turned off.</string>
 
-    <!--  Night display: Title for the night display option Suggestion (renamed "Night Light" with title caps). [CHAR LIMIT=NONE] -->
-    <string name="night_display_suggestion_title">Set Night Light schedule</string>
-
-    <!--  Night display: Summary for the night display option Suggestion (renamed "Night Light" with title caps). [CHAR LIMIT=30] -->
-    <string name="night_display_suggestion_summary">Tint screen amber to help you fall asleep</string>
-
     <!-- Title of condition that night display is on (renamed "Night Light" with title caps). [CHAR LIMIT=30] -->
     <string name="condition_night_display_title">Night Light is on</string>
 
@@ -8390,7 +8384,7 @@
     <!-- Summary text for ambient display (device) [CHAR LIMIT=160]-->
     <string name="ambient_display_pickup_summary" product="device">To quickly check your notifications, pick up your device.</string>
 
-    <!-- Title text for fingerprint swipe for notifications [CHAR LIMIT=80]-->
+    <!-- Title text for swiping downwards on fingerprint sensor for notifications [CHAR LIMIT=80]-->
     <string name="fingerprint_swipe_for_notifications_title">Swipe fingerprint for notifications</string>
 
     <!-- Summary text for fingerprint swipe for notifications (phone) [CHAR LIMIT=160]-->
@@ -8425,14 +8419,16 @@
     <string name="automatic_storage_manager_freed_bytes"><xliff:g id="size" example="3.25MB">%1$s</xliff:g> total made available\n\nLast ran on <xliff:g id="date" example="Jan 12">%2$s</xliff:g></string>
 
     <!-- Title text for enabling web actions. [CHAR_LIMIT=60] -->
-    <string name="web_action_enable_title">Open links in apps</string>
+    <string name="web_action_enable_title">Instant apps</string>
 
     <!-- Summary text for enabling web actions. [CHAR_LIMIT=250] -->
-    <string name="web_action_enable_summary">Open links in supported apps, even if the
-      apps aren’t installed on your device</string>
+    <string name="web_action_enable_summary">Open links in apps, even if they’re not installed</string>
 
     <!-- Section title for the Web Action preference [CHAR LIMIT=60] -->
-    <string name="web_action_section_title">Apps not installed</string>
+    <string name="web_action_section_title">Instant apps</string>
+
+    <!-- Preference label for an tappable preference that will open the account chooser for instant apps. [CHAR LIMIT=60] -->
+    <string name="instant_apps_account">Instant apps account</string>
 
     <!-- Section title for the Domain URL app preference list [CHAR LIMIT=60]-->
     <string name="domain_url_section_title">Installed apps</string>
diff --git a/res/xml/empty_settings.xml b/res/xml/empty_settings.xml
new file mode 100644
index 0000000..d63f7d6
--- /dev/null
+++ b/res/xml/empty_settings.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  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.
+  -->
+
+<PreferenceScreen />
diff --git a/res/xml/installed_app_details_ia.xml b/res/xml/installed_app_details_ia.xml
index 50d183d..b092753 100644
--- a/res/xml/installed_app_details_ia.xml
+++ b/res/xml/installed_app_details_ia.xml
@@ -43,31 +43,37 @@
     <Preference
         android:key="permission_settings"
         android:title="@string/permissions_label"
+        android:summary="@string/summary_placeholder"
         android:selectable="true"/>
 
     <Preference
         android:key="storage_settings"
         android:title="@string/storage_settings"
+        android:summary="@string/summary_placeholder"
         android:selectable="true"/>
 
     <Preference
         android:key="data_settings"
         android:title="@string/data_usage_summary_title"
+        android:summary="@string/summary_placeholder"
         android:selectable="true"/>
 
     <Preference
         android:key="battery"
         android:title="@string/power_usage_summary_title"
+        android:summary="@string/summary_placeholder"
         android:selectable="true"/>
 
     <Preference
         android:key="preferred_settings"
         android:title="@string/launch_by_default"
+        android:summary="@string/summary_placeholder"
         android:selectable="true"/>
 
     <Preference
         android:key="memory"
         android:title="@string/memory_settings_title"
+        android:summary="@string/summary_placeholder"
         android:enabled="false"
         android:selectable="true"/>
 
diff --git a/res/xml/tts_sliders.xml b/res/xml/tts_sliders.xml
deleted file mode 100644
index 3c767b0..0000000
--- a/res/xml/tts_sliders.xml
+++ /dev/null
@@ -1,46 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2009 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.
--->
-
-<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
-        android:title="@string/tts_settings_title">
-
-        <!-- The max value for seek bars here should be kept in sync
-             with the max value specified in TextToSpeechSettings class. -->
-        <com.android.settings.SeekBarPreference
-            android:key="tts_default_rate"
-            android:title="@string/tts_default_rate_title"
-            android:summary="@string/tts_default_rate_summary"
-            android:defaultValue="50"
-            android:max="600"/>
-
-        <com.android.settings.SeekBarPreference
-            android:key="tts_default_pitch"
-            android:title="@string/tts_default_pitch_title"
-            android:summary="@string/tts_default_pitch_summary"
-            android:defaultValue="100"
-            android:max="400"/>
-
-        <Preference android:key="reset_speech_rate"
-            android:persistent="false"
-            android:title="@string/tts_reset_speech_rate_title"
-            android:summary="@string/tts_reset_speech_rate_summary" />
-
-        <Preference android:key="reset_speech_pitch"
-            android:persistent="false"
-            android:title="@string/tts_reset_speech_pitch_title"
-            android:summary="@string/tts_reset_speech_pitch_summary" />
-
-</PreferenceScreen>
diff --git a/res/xml/wifi_network_details_fragment.xml b/res/xml/wifi_network_details_fragment.xml
index 09bcf86..5b20d59 100644
--- a/res/xml/wifi_network_details_fragment.xml
+++ b/res/xml/wifi_network_details_fragment.xml
@@ -55,11 +55,15 @@
             android:key="ip_details_category"
             android:title="@string/wifi_setup_detail">
         <com.android.settings.wifi.WifiDetailPreference
+            android:key="mac_address"
+            android:title="@string/wifi_advanced_mac_address_title"
+            android:selectable="false"/>
+        <com.android.settings.wifi.WifiDetailPreference
                 android:key="ip_address"
                 android:title="@string/wifi_ip_address"
                 android:selectable="false"/>
         <com.android.settings.wifi.WifiDetailPreference
-                android:key="router"
+                android:key="gateway"
                 android:title="@string/wifi_gateway"
                 android:selectable="false"/>
         <com.android.settings.wifi.WifiDetailPreference
diff --git a/src/com/android/settings/ApnSettings.java b/src/com/android/settings/ApnSettings.java
index 5e31a02..b460050 100755
--- a/src/com/android/settings/ApnSettings.java
+++ b/src/com/android/settings/ApnSettings.java
@@ -184,8 +184,7 @@
         mUnavailable = isUiRestricted();
         setHasOptionsMenu(!mUnavailable);
         if (mUnavailable) {
-            setPreferenceScreen(new PreferenceScreen(getPrefContext(), null));
-            getPreferenceScreen().removeAll();
+            addPreferencesFromResource(R.xml.empty_settings);
             return;
         }
 
diff --git a/src/com/android/settings/HotspotOffReceiver.java b/src/com/android/settings/HotspotOffReceiver.java
index 3db0ee9..4083082 100644
--- a/src/com/android/settings/HotspotOffReceiver.java
+++ b/src/com/android/settings/HotspotOffReceiver.java
@@ -4,12 +4,11 @@
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.net.ConnectivityManager;
 import android.net.wifi.WifiManager;
 import android.util.Log;
 
-import com.android.settingslib.TetherUtil;
-
 /**
  * This receiver catches when quick settings turns off the hotspot, so we can
  * cancel the alarm in that case.  All other cancels are handled in tethersettings.
@@ -19,6 +18,13 @@
     private static final String TAG = "HotspotOffReceiver";
     private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
 
+    private Context mContext;
+    private boolean mRegistered;
+
+    public HotspotOffReceiver(Context context) {
+        mContext = context;
+    }
+
     @Override
     public void onReceive(Context context, Intent intent) {
         if (WifiManager.WIFI_AP_STATE_CHANGED_ACTION.equals(intent.getAction())) {
@@ -31,4 +37,19 @@
             }
         }
     }
+
+    public void register() {
+        if (!mRegistered) {
+            mContext.registerReceiver(this,
+                new IntentFilter(WifiManager.WIFI_AP_STATE_CHANGED_ACTION));
+            mRegistered = true;
+        }
+    }
+
+    public void unregister() {
+        if (mRegistered) {
+            mContext.unregisterReceiver(this);
+            mRegistered = false;
+        }
+    }
 }
diff --git a/src/com/android/settings/TetherService.java b/src/com/android/settings/TetherService.java
index 610d320..fce3f27 100644
--- a/src/com/android/settings/TetherService.java
+++ b/src/com/android/settings/TetherService.java
@@ -41,7 +41,6 @@
 import android.util.Log;
 
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.settingslib.TetherUtil;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -69,6 +68,7 @@
     private UsageStatsManagerWrapper mUsageManagerWrapper;
     private ArrayList<Integer> mCurrentTethers;
     private ArrayMap<Integer, List<ResultReceiver>> mPendingCallbacks;
+    private HotspotOffReceiver mHotspotReceiver;
 
     @Override
     public IBinder onBind(Intent intent) {
@@ -94,6 +94,7 @@
         if (mUsageManagerWrapper == null) {
             mUsageManagerWrapper = new UsageStatsManagerWrapper(this);
         }
+        mHotspotReceiver = new HotspotOffReceiver(this);
     }
 
     @Override
@@ -181,6 +182,11 @@
         }
     }
 
+    @VisibleForTesting
+    void setHotspotOffReceiver(HotspotOffReceiver receiver) {
+        mHotspotReceiver = receiver;
+    }
+
     private ArrayList<Integer> stringToTethers(String tethersStr) {
         ArrayList<Integer> ret = new ArrayList<Integer>();
         if (TextUtils.isEmpty(tethersStr)) return ret;
@@ -276,7 +282,8 @@
         }
     }
 
-    private void scheduleAlarm() {
+    @VisibleForTesting
+    void scheduleAlarm() {
         Intent intent = new Intent(this, TetherService.class);
         intent.putExtra(ConnectivityManager.EXTRA_RUN_PROVISION, true);
 
@@ -289,6 +296,7 @@
         if (DEBUG) Log.d(TAG, "Scheduling alarm at interval " + periodMs);
         alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, firstTime, periodMs,
                 pendingIntent);
+        mHotspotReceiver.register();
     }
 
     /**
@@ -302,7 +310,8 @@
         context.startService(intent);
     }
 
-    private void cancelAlarmIfNecessary() {
+    @VisibleForTesting
+    void cancelAlarmIfNecessary() {
         if (mCurrentTethers.size() != 0) {
             if (DEBUG) Log.d(TAG, "Tethering still active, not cancelling alarm");
             return;
@@ -312,6 +321,7 @@
         AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
         alarmManager.cancel(pendingIntent);
         if (DEBUG) Log.d(TAG, "Tethering no longer active, canceling recheck");
+        mHotspotReceiver.unregister();
     }
 
     private void fireCallbacksForType(int type, int result) {
diff --git a/src/com/android/settings/Utils.java b/src/com/android/settings/Utils.java
index 4c8fb2d..d04ae8d 100644
--- a/src/com/android/settings/Utils.java
+++ b/src/com/android/settings/Utils.java
@@ -73,7 +73,6 @@
 import android.provider.ContactsContract.Profile;
 import android.provider.ContactsContract.RawContacts;
 import android.provider.Settings;
-import android.service.persistentdata.PersistentDataBlockManager;
 import android.support.annotation.StringRes;
 import android.support.v7.preference.Preference;
 import android.support.v7.preference.PreferenceGroup;
diff --git a/src/com/android/settings/applications/AppHeaderController.java b/src/com/android/settings/applications/AppHeaderController.java
index b138ede..9e41679 100644
--- a/src/com/android/settings/applications/AppHeaderController.java
+++ b/src/com/android/settings/applications/AppHeaderController.java
@@ -24,6 +24,8 @@
 import android.content.pm.PackageInfo;
 import android.content.pm.ResolveInfo;
 import android.content.res.Resources;
+import android.graphics.Outline;
+import android.graphics.drawable.AdaptiveIconDrawable;
 import android.graphics.drawable.Drawable;
 import android.os.UserHandle;
 import android.support.annotation.IntDef;
@@ -31,6 +33,7 @@
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
+import android.view.ViewOutlineProvider;
 import android.widget.ImageButton;
 import android.widget.ImageView;
 import android.widget.TextView;
@@ -61,12 +64,23 @@
 
     public static final String PREF_KEY_APP_HEADER = "pref_app_header";
 
+    public static final ViewOutlineProvider OUTLINE_PROVIDER = new ViewOutlineProvider() {
+        @Override
+        public void getOutline(View view, Outline outline) {
+            Drawable background = ((ImageView)view).getDrawable();
+            if (background != null) {
+                background.getOutline(outline);
+            }
+        }
+    };
+
     private static final String TAG = "AppDetailFeature";
 
     private final Context mContext;
     private final Fragment mFragment;
     private final int mMetricsCategory;
     private final View mAppHeader;
+    private final int mIconElevation;
 
     private Drawable mIcon;
     private CharSequence mLabel;
@@ -93,6 +107,8 @@
             mAppHeader = LayoutInflater.from(fragment.getContext())
                     .inflate(R.layout.app_details, null /* root */);
         }
+        mIconElevation = mContext.getResources()
+            .getDimensionPixelSize(R.dimen.launcher_icon_elevation);
     }
 
     public AppHeaderController setIcon(Drawable icon) {
@@ -212,6 +228,13 @@
         ImageView iconView = (ImageView) mAppHeader.findViewById(R.id.app_detail_icon);
         if (iconView != null) {
             iconView.setImageDrawable(mIcon);
+            if (mIcon instanceof AdaptiveIconDrawable) {
+                iconView.setElevation(mIconElevation);
+                iconView.setOutlineProvider(OUTLINE_PROVIDER);
+            } else {
+                iconView.setElevation(0);
+                iconView.setOutlineProvider(null);
+            }
             ImageView badgeView = mAppHeader.findViewById(R.id.app_icon_instant_apps_badge);
             if (badgeView != null) {
                 badgeView.setVisibility(mIsInstantApp ? View.VISIBLE : View.GONE);
diff --git a/src/com/android/settings/applications/AppStorageSettings.java b/src/com/android/settings/applications/AppStorageSettings.java
index d5d72bc..8d41558 100644
--- a/src/com/android/settings/applications/AppStorageSettings.java
+++ b/src/com/android/settings/applications/AppStorageSettings.java
@@ -101,6 +101,8 @@
     private static final String KEY_URI_CATEGORY = "uri_category";
     private static final String KEY_CLEAR_URI = "clear_uri_button";
 
+    private static final String KEY_CACHE_CLEARED = "cache_cleared";
+
     // Views related to cache info
     private Preference mCacheSize;
     private Button mClearDataButton;
@@ -115,6 +117,7 @@
     private PreferenceCategory mUri;
 
     private boolean mCanClearData = true;
+    private boolean mCacheCleared;
 
     private AppStorageStats mLastResult;
     private AppStorageSizesController mSizeController;
@@ -133,6 +136,9 @@
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
+        if (savedInstanceState != null) {
+            mCacheCleared = savedInstanceState.getBoolean(KEY_CACHE_CLEARED, false);
+        }
 
         addPreferencesFromResource(R.xml.app_storage_settings);
         setupViews();
@@ -145,6 +151,12 @@
         updateSize();
     }
 
+    @Override
+    public void onSaveInstanceState(Bundle outState) {
+        super.onSaveInstanceState(outState);
+        outState.putBoolean(KEY_CACHE_CLEARED, mCacheCleared);
+    }
+
     private void setupViews() {
         mComputingStr = getActivity().getText(R.string.computing_size);
         mInvalidSizeStr = getActivity().getText(R.string.invalid_size_value);
@@ -523,6 +535,10 @@
     }
 
     private void updateUiWithSize(AppStorageStats result) {
+        if (mCacheCleared) {
+            mSizeController.setCacheCleared(true);
+        }
+
         mSizeController.updateUi(getContext());
 
         if (result == null) {
@@ -539,7 +555,7 @@
                 mClearDataButton.setEnabled(true);
                 mClearDataButton.setOnClickListener(this);
             }
-            if (cacheSize <= 0) {
+            if (cacheSize <= 0 || mCacheCleared) {
                 mClearCacheButton.setEnabled(false);
             } else {
                 mClearCacheButton.setEnabled(true);
@@ -562,6 +578,7 @@
                     processClearMsg(msg);
                     break;
                 case MSG_CLEAR_CACHE:
+                    mCacheCleared = true;
                     // Refresh size info
                     updateSize();
                     break;
diff --git a/src/com/android/settings/applications/AppStorageSizesController.java b/src/com/android/settings/applications/AppStorageSizesController.java
index bc8f680..94935bd 100644
--- a/src/com/android/settings/applications/AppStorageSizesController.java
+++ b/src/com/android/settings/applications/AppStorageSizesController.java
@@ -39,6 +39,7 @@
     @Nullable
     private StorageStatsSource.AppStorageStats mLastResult;
     private boolean mLastResultFailed;
+    private boolean mCachedCleared;
     private long mLastCodeSize = -1;
     private long mLastDataSize = -1;
     private long mLastCacheSize = -1;
@@ -77,7 +78,7 @@
                 mLastDataSize = dataSize;
                 mDataSize.setSummary(getSizeStr(context, dataSize));
             }
-            long cacheSize = mLastResult.getCacheBytes();
+            long cacheSize = mCachedCleared ? 0 : mLastResult.getCacheBytes();
             if (mLastCacheSize != cacheSize) {
                 mLastCacheSize = cacheSize;
                 mCacheSize.setSummary(getSizeStr(context, cacheSize));
@@ -100,6 +101,15 @@
         mLastResultFailed = result == null;
     }
 
+    /**
+     * Sets if we have cleared the cache and should zero the cache bytes.
+     * When the cache is cleared, the cache directories are recreated. These directories have
+     * some size, but are empty. We zero this out to best match user expectations.
+     */
+    public void setCacheCleared(boolean isCleared) {
+        mCachedCleared = isCleared;
+    }
+
     private String getSizeStr(Context context, long size) {
         return Formatter.formatFileSize(context, size);
     }
diff --git a/src/com/android/settings/applications/ManageApplications.java b/src/com/android/settings/applications/ManageApplications.java
index 229e294..0c28461 100644
--- a/src/com/android/settings/applications/ManageApplications.java
+++ b/src/com/android/settings/applications/ManageApplications.java
@@ -23,6 +23,7 @@
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageItemInfo;
 import android.content.pm.PackageManager;
+import android.graphics.drawable.AdaptiveIconDrawable;
 import android.icu.text.AlphabeticIndex;
 import android.os.Bundle;
 import android.os.Environment;
@@ -34,6 +35,7 @@
 import android.support.annotation.VisibleForTesting;
 import android.text.TextUtils;
 import android.util.ArraySet;
+import android.util.LauncherIcons;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.Menu;
@@ -90,7 +92,6 @@
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Comparator;
-import java.util.List;
 import java.util.Locale;
 import java.util.Set;
 
@@ -812,6 +813,8 @@
         private final AppStateBaseBridge mExtraInfoBridge;
         private final Handler mBgHandler;
         private final Handler mFgHandler;
+        private final LauncherIcons mLauncherIcons;
+
         private int mFilterMode;
         private ArrayList<ApplicationsState.AppEntry> mBaseEntries;
         private ArrayList<ApplicationsState.AppEntry> mEntries;
@@ -866,6 +869,7 @@
             mContext = manageApplications.getActivity();
             mPm = mContext.getPackageManager();
             mFilterMode = filterMode;
+            mLauncherIcons = new LauncherIcons(mContext);
             if (mManageApplications.mListType == LIST_TYPE_NOTIFICATION) {
                 mExtraInfoBridge = new AppStateNotificationBridge(mContext, mState, this,
                         manageApplications.mNotifBackend);
@@ -1300,6 +1304,9 @@
                     }
                     mState.ensureIcon(entry);
                     if (entry.icon != null) {
+                        if (entry.icon instanceof AdaptiveIconDrawable) {
+                            entry.icon = mLauncherIcons.wrapIconDrawableWithShadow(entry.icon);
+                        }
                         holder.appIcon.setImageDrawable(entry.icon);
                     }
                     updateSummary(holder);
diff --git a/src/com/android/settings/applications/ManageDomainUrls.java b/src/com/android/settings/applications/ManageDomainUrls.java
index b09a089..bdc9932 100644
--- a/src/com/android/settings/applications/ManageDomainUrls.java
+++ b/src/com/android/settings/applications/ManageDomainUrls.java
@@ -15,7 +15,9 @@
 package com.android.settings.applications;
 
 import android.app.Application;
+import android.content.ComponentName;
 import android.content.Context;
+import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.os.Bundle;
 import android.os.UserHandle;
@@ -55,6 +57,7 @@
     private ApplicationsState.Session mSession;
     private PreferenceGroup mDomainAppList;
     private SwitchPreference mWebAction;
+    private Preference mInstantAppAccountPreference;
 
     @Override
     public void onCreate(Bundle icicle) {
@@ -126,6 +129,26 @@
                 mWebAction.setOnPreferenceChangeListener(this);
                 webActionCategory.addPreference(mWebAction);
 
+                // Determine whether we should show the instant apps account chooser setting
+                ComponentName instantAppSettingsComponent = getActivity().getPackageManager()
+                        .getInstantAppResolverSettingsComponent();
+                Intent instantAppSettingsIntent = null;
+                if (instantAppSettingsComponent != null) {
+                    instantAppSettingsIntent =
+                            new Intent().setComponent(instantAppSettingsComponent);
+                }
+                if (instantAppSettingsIntent != null) {
+                    final Intent launchIntent = instantAppSettingsIntent;
+                    // TODO: Make this button actually launch the account chooser.
+                    mInstantAppAccountPreference = new Preference(getPrefContext());
+                    mInstantAppAccountPreference.setTitle(R.string.instant_apps_account);
+                    mInstantAppAccountPreference.setOnPreferenceClickListener(pref -> {
+                        startActivity(launchIntent);
+                        return true;
+                    });
+                    webActionCategory.addPreference(mInstantAppAccountPreference);
+                }
+
                 // list to manage link handling per app
                 mDomainAppList = new PreferenceCategory(getPrefContext());
                 mDomainAppList.setTitle(R.string.domain_url_section_title);
@@ -138,9 +161,11 @@
     @Override
     public boolean onPreferenceChange(Preference preference, Object newValue) {
         if (preference == mWebAction) {
-            final int enabled = (boolean) newValue ? 1 : 0;
+            boolean checked = (boolean) newValue;
             Settings.Secure.putInt(
-                    getContentResolver(), Settings.Secure.WEB_ACTION_ENABLED, enabled);
+                    getContentResolver(),
+                    Settings.Secure.WEB_ACTION_ENABLED, checked ? 1 : 0);
+            mWebAction.setChecked(checked);
             return true;
         }
         return false;
diff --git a/src/com/android/settings/applications/RunningProcessesView.java b/src/com/android/settings/applications/RunningProcessesView.java
index dcb6f9e..b365435 100644
--- a/src/com/android/settings/applications/RunningProcessesView.java
+++ b/src/com/android/settings/applications/RunningProcessesView.java
@@ -411,7 +411,7 @@
             args.putBoolean(RunningServiceDetails.KEY_BACKGROUND, mAdapter.mShowBackground);
 
             SettingsActivity sa = (SettingsActivity) mOwner.getActivity();
-            sa.startPreferencePanel(null, RunningServiceDetails.class.getName(), args,
+            sa.startPreferencePanel(mOwner, RunningServiceDetails.class.getName(), args,
                     R.string.runningservicedetails_settings_title, null, null, 0);
         }
     }
diff --git a/src/com/android/settings/applications/RunningServiceDetails.java b/src/com/android/settings/applications/RunningServiceDetails.java
index 9a173bc..84c2ee5 100644
--- a/src/com/android/settings/applications/RunningServiceDetails.java
+++ b/src/com/android/settings/applications/RunningServiceDetails.java
@@ -33,9 +33,9 @@
 import android.widget.TextView;
 
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.settings.core.InstrumentedPreferenceFragment;
 import com.android.settings.R;
 import com.android.settings.Utils;
+import com.android.settings.core.InstrumentedPreferenceFragment;
 import com.android.settings.core.instrumentation.InstrumentedDialogFragment;
 
 import java.io.File;
@@ -493,19 +493,20 @@
             }
         });
     }
-    
+
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        
+        setHasOptionsMenu(true);
         mUid = getArguments().getInt(KEY_UID, -1);
         mUserId = getArguments().getInt(KEY_USER_ID, 0);
         mProcessName = getArguments().getString(KEY_PROCESS, null);
         mShowBackground = getArguments().getBoolean(KEY_BACKGROUND, false);
-        
-        mAm = (ActivityManager)getActivity().getSystemService(Context.ACTIVITY_SERVICE);
-        mInflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-        
+
+        mAm = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
+        mInflater = (LayoutInflater) getActivity().getSystemService(
+                Context.LAYOUT_INFLATER_SERVICE);
+
         mState = RunningState.getInstance(getActivity());
     }
     
diff --git a/src/com/android/settings/applications/UserManagerWrapper.java b/src/com/android/settings/applications/UserManagerWrapper.java
index daefb84..5b4ed2a 100644
--- a/src/com/android/settings/applications/UserManagerWrapper.java
+++ b/src/com/android/settings/applications/UserManagerWrapper.java
@@ -17,6 +17,7 @@
 package com.android.settings.applications;
 
 import android.content.pm.UserInfo;
+
 import java.util.List;
 
 /**
diff --git a/src/com/android/settings/bluetooth/BluetoothDevicePreference.java b/src/com/android/settings/bluetooth/BluetoothDevicePreference.java
index 5bddffa..7be6dd7 100644
--- a/src/com/android/settings/bluetooth/BluetoothDevicePreference.java
+++ b/src/com/android/settings/bluetooth/BluetoothDevicePreference.java
@@ -30,14 +30,13 @@
 import android.util.Log;
 import android.util.Pair;
 import android.util.TypedValue;
-import android.view.View;
-import android.view.View.OnClickListener;
 import android.widget.ImageView;
 
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.settings.R;
 import com.android.settings.core.instrumentation.MetricsFeatureProvider;
 import com.android.settings.overlay.FeatureFactory;
+import com.android.settings.widget.GearPreference;
 import com.android.settingslib.bluetooth.CachedBluetoothDevice;
 import com.android.settingslib.bluetooth.HidProfile;
 import com.android.settingslib.bluetooth.LocalBluetoothProfile;
@@ -50,15 +49,14 @@
  * BluetoothDevicePreference is the preference type used to display each remote
  * Bluetooth device in the Bluetooth Settings screen.
  */
-public final class BluetoothDevicePreference extends Preference implements
-        CachedBluetoothDevice.Callback, OnClickListener {
-    private static final String TAG = "BluetoothDevicePreference";
+public final class BluetoothDevicePreference extends GearPreference implements
+        CachedBluetoothDevice.Callback {
+    private static final String TAG = "BluetoothDevicePref";
 
     private static int sDimAlpha = Integer.MIN_VALUE;
 
     private final CachedBluetoothDevice mCachedDevice;
-
-    private OnClickListener mOnSettingsClickListener;
+    private final UserManager mUserManager;
 
     private AlertDialog mDisconnectDialog;
 
@@ -76,7 +74,8 @@
     public final String BLUETOOTH = r.getString(R.string.bluetooth_talkback_bluetooth);
 
     public BluetoothDevicePreference(Context context, CachedBluetoothDevice cachedDevice) {
-        super(context);
+        super(context, null);
+        mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
 
         if (sDimAlpha == Integer.MIN_VALUE) {
             TypedValue outValue = new TypedValue();
@@ -85,14 +84,6 @@
         }
 
         mCachedDevice = cachedDevice;
-
-        if (cachedDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
-            UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
-            if (!um.hasUserRestriction(DISALLOW_CONFIG_BLUETOOTH)) {
-                setWidgetLayoutResource(R.layout.preference_bluetooth);
-            }
-        }
-
         mCachedDevice.registerCallback(this);
 
         onDeviceAttributesChanged();
@@ -102,12 +93,20 @@
         notifyChanged();
     }
 
-    CachedBluetoothDevice getCachedDevice() {
-        return mCachedDevice;
+    @Override
+    protected boolean shouldHideSecondTarget() {
+        return mCachedDevice == null
+                || mCachedDevice.getBondState() != BluetoothDevice.BOND_BONDED
+                || mUserManager.hasUserRestriction(DISALLOW_CONFIG_BLUETOOTH);
     }
 
-    public void setOnSettingsClickListener(OnClickListener listener) {
-        mOnSettingsClickListener = listener;
+    @Override
+    protected int getSecondTargetResId() {
+        return R.layout.preference_widget_gear;
+    }
+
+    CachedBluetoothDevice getCachedDevice() {
+        return mCachedDevice;
     }
 
     @Override
@@ -120,6 +119,10 @@
         }
     }
 
+    public CachedBluetoothDevice getBluetoothDevice() {
+        return mCachedDevice;
+    }
+
     public void onDeviceAttributesChanged() {
         /*
          * The preference framework takes care of making sure the value has
@@ -157,11 +160,10 @@
         }
 
         if (mCachedDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
-            ImageView deviceDetails = (ImageView) view.findViewById(R.id.deviceDetails);
+            ImageView deviceDetails = (ImageView) view.findViewById(R.id.settings_button);
 
             if (deviceDetails != null) {
                 deviceDetails.setOnClickListener(this);
-                deviceDetails.setTag(mCachedDevice);
             }
         }
         final ImageView imageView = (ImageView) view.findViewById(android.R.id.icon);
@@ -171,13 +173,6 @@
         super.onBindViewHolder(view);
     }
 
-    public void onClick(View v) {
-        // Should never be null by construction
-        if (mOnSettingsClickListener != null) {
-            mOnSettingsClickListener.onClick(v);
-        }
-    }
-
     @Override
     public boolean equals(Object o) {
         if ((o == null) || !(o instanceof BluetoothDevicePreference)) {
@@ -207,19 +202,19 @@
         int bondState = mCachedDevice.getBondState();
 
         final MetricsFeatureProvider metricsFeatureProvider =
-            FeatureFactory.getFactory(getContext()).getMetricsFeatureProvider();
+                FeatureFactory.getFactory(getContext()).getMetricsFeatureProvider();
 
         if (mCachedDevice.isConnected()) {
             metricsFeatureProvider.action(getContext(),
-                MetricsEvent.ACTION_SETTINGS_BLUETOOTH_DISCONNECT);
+                    MetricsEvent.ACTION_SETTINGS_BLUETOOTH_DISCONNECT);
             askDisconnect();
         } else if (bondState == BluetoothDevice.BOND_BONDED) {
             metricsFeatureProvider.action(getContext(),
-                MetricsEvent.ACTION_SETTINGS_BLUETOOTH_CONNECT);
+                    MetricsEvent.ACTION_SETTINGS_BLUETOOTH_CONNECT);
             mCachedDevice.connect(true);
         } else if (bondState == BluetoothDevice.BOND_NONE) {
             metricsFeatureProvider.action(getContext(),
-                MetricsEvent.ACTION_SETTINGS_BLUETOOTH_PAIR);
+                    MetricsEvent.ACTION_SETTINGS_BLUETOOTH_PAIR);
             pair();
         }
     }
@@ -283,10 +278,10 @@
             }
         }
         if (btClass != null) {
-          if (btClass.doesClassMatch(BluetoothClass.PROFILE_HEADSET)) {
+            if (btClass.doesClassMatch(BluetoothClass.PROFILE_HEADSET)) {
                 return new Pair<Integer, String>(R.drawable.ic_bt_headset_hfp, HEADSET);
             }
-          if (btClass.doesClassMatch(BluetoothClass.PROFILE_A2DP)) {
+            if (btClass.doesClassMatch(BluetoothClass.PROFILE_A2DP)) {
                 return new Pair<Integer, String>(R.drawable.ic_bt_headphones_a2dp, HEADPHONE);
             }
         }
diff --git a/src/com/android/settings/bluetooth/BluetoothSettings.java b/src/com/android/settings/bluetooth/BluetoothSettings.java
index 5679f90..317a350 100644
--- a/src/com/android/settings/bluetooth/BluetoothSettings.java
+++ b/src/com/android/settings/bluetooth/BluetoothSettings.java
@@ -45,13 +45,14 @@
 import com.android.settings.LinkifyUtils;
 import com.android.settings.R;
 import com.android.settings.SettingsActivity;
-import com.android.settings.widget.SummaryUpdater.OnSummaryChangeListener;
 import com.android.settings.dashboard.SummaryLoader;
 import com.android.settings.location.ScanningSettings;
 import com.android.settings.search.BaseSearchIndexProvider;
 import com.android.settings.search.Indexable;
 import com.android.settings.search.SearchIndexableRaw;
 import com.android.settings.widget.FooterPreference;
+import com.android.settings.widget.GearPreference;
+import com.android.settings.widget.SummaryUpdater.OnSummaryChangeListener;
 import com.android.settings.widget.SwitchBar;
 import com.android.settings.widget.SwitchBarController;
 import com.android.settingslib.bluetooth.BluetoothDeviceFilter;
@@ -476,24 +477,25 @@
         }
     }
 
-    private final View.OnClickListener mDeviceProfilesListener = new View.OnClickListener() {
-        @Override
-        public void onClick(View v) {
-            // User clicked on advanced options icon for a device in the list
-            if (!(v.getTag() instanceof CachedBluetoothDevice)) {
-                Log.w(TAG, "onClick() called for other View: " + v);
-                return;
-            }
-
-            final CachedBluetoothDevice device = (CachedBluetoothDevice) v.getTag();
-            Bundle args = new Bundle();
-            args.putString(DeviceProfilesSettings.ARG_DEVICE_ADDRESS,
-                    device.getDevice().getAddress());
-            DeviceProfilesSettings profileSettings = new DeviceProfilesSettings();
-            profileSettings.setArguments(args);
-            profileSettings.show(getFragmentManager(),
-                    DeviceProfilesSettings.class.getSimpleName());
+    private final GearPreference.OnGearClickListener mDeviceProfilesListener = pref -> {
+        // User clicked on advanced options icon for a device in the list
+        if (!(pref instanceof BluetoothDevicePreference)) {
+            Log.w(TAG, "onClick() called for other View: " + pref);
+            return;
         }
+        final CachedBluetoothDevice device =
+                ((BluetoothDevicePreference) pref).getBluetoothDevice();
+        if (device == null) {
+            Log.w(TAG, "No BT device attached with this pref: " + pref);
+            return;
+        }
+        final Bundle args = new Bundle();
+        args.putString(DeviceProfilesSettings.ARG_DEVICE_ADDRESS,
+                device.getDevice().getAddress());
+        final DeviceProfilesSettings profileSettings = new DeviceProfilesSettings();
+        profileSettings.setArguments(args);
+        profileSettings.show(getFragmentManager(),
+                DeviceProfilesSettings.class.getSimpleName());
     };
 
     /**
@@ -506,7 +508,7 @@
         CachedBluetoothDevice cachedDevice = preference.getCachedDevice();
         if (cachedDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
             // Only paired device have an associated advanced settings screen
-            preference.setOnSettingsClickListener(mDeviceProfilesListener);
+            preference.setOnGearClickListener(mDeviceProfilesListener);
         }
     }
 
diff --git a/src/com/android/settings/bluetooth/DevicePickerFragment.java b/src/com/android/settings/bluetooth/DevicePickerFragment.java
index f250c9a..490a3ad 100644
--- a/src/com/android/settings/bluetooth/DevicePickerFragment.java
+++ b/src/com/android/settings/bluetooth/DevicePickerFragment.java
@@ -62,11 +62,6 @@
     }
 
     @Override
-    void initDevicePreference(BluetoothDevicePreference preference) {
-        preference.setWidgetLayoutResource(R.layout.preference_empty_list);
-    }
-
-    @Override
     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
         menu.add(Menu.NONE, MENU_ID_REFRESH, 0, R.string.bluetooth_search_for_devices)
                 .setEnabled(true)
diff --git a/src/com/android/settings/dashboard/ExpandPreference.java b/src/com/android/settings/dashboard/ExpandPreference.java
index 12ca5ac..3939e74 100644
--- a/src/com/android/settings/dashboard/ExpandPreference.java
+++ b/src/com/android/settings/dashboard/ExpandPreference.java
@@ -18,6 +18,7 @@
 
 import android.content.Context;
 import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceViewHolder;
 import android.util.AttributeSet;
 
 import com.android.settings.R;
@@ -51,4 +52,10 @@
         setTitle(R.string.advanced_section_header);
         setOrder(999);
     }
+
+    @Override
+    public void onBindViewHolder(PreferenceViewHolder holder) {
+        super.onBindViewHolder(holder);
+        holder.setDividerAllowedAbove(false);
+    }
 }
diff --git a/src/com/android/settings/development/DevelopmentSettings.java b/src/com/android/settings/development/DevelopmentSettings.java
index 2bfb602..3deedaf 100644
--- a/src/com/android/settings/development/DevelopmentSettings.java
+++ b/src/com/android/settings/development/DevelopmentSettings.java
@@ -396,7 +396,7 @@
             // Block access to developer options if the user is not the owner, if user policy
             // restricts it, or if the device has not been provisioned
             mUnavailable = true;
-            setPreferenceScreen(new PreferenceScreen(getPrefContext(), null));
+            addPreferencesFromResource(R.xml.empty_settings);
             return;
         }
 
diff --git a/src/com/android/settings/deviceinfo/PrivateVolumeSettings.java b/src/com/android/settings/deviceinfo/PrivateVolumeSettings.java
index 9ddf7b7..b5d7ddf 100644
--- a/src/com/android/settings/deviceinfo/PrivateVolumeSettings.java
+++ b/src/com/android/settings/deviceinfo/PrivateVolumeSettings.java
@@ -484,28 +484,13 @@
 
             } break;
             case R.string.storage_detail_images: {
-                intent = new Intent(Intent.ACTION_VIEW);
-                intent.setDataAndType(
-                        DocumentsContract.buildRootUri(AUTHORITY_MEDIA, "images_root"),
-                        DocumentsContract.Root.MIME_TYPE_ITEM);
-                intent.addCategory(Intent.CATEGORY_DEFAULT);
-
+                intent = getIntentForStorage(AUTHORITY_MEDIA, "images_root");
             } break;
             case R.string.storage_detail_videos: {
-                intent = new Intent(Intent.ACTION_VIEW);
-                intent.setDataAndType(
-                        DocumentsContract.buildRootUri(AUTHORITY_MEDIA, "videos_root"),
-                        DocumentsContract.Root.MIME_TYPE_ITEM);
-                intent.addCategory(Intent.CATEGORY_DEFAULT);
-
+                intent = getIntentForStorage(AUTHORITY_MEDIA, "videos_root");
             } break;
             case R.string.storage_detail_audio: {
-                intent = new Intent(DocumentsContract.Root.MIME_TYPE_ITEM);
-                intent.setDataAndType(
-                        DocumentsContract.buildRootUri(AUTHORITY_MEDIA, "audio_root"),
-                        DocumentsContract.Root.MIME_TYPE_ITEM);
-                intent.addCategory(Intent.CATEGORY_DEFAULT);
-
+                intent = getIntentForStorage(AUTHORITY_MEDIA, "audio_root");
             } break;
             case R.string.storage_detail_system: {
                 SystemInfoFragment.show(this);
@@ -546,6 +531,16 @@
         return super.onPreferenceTreeClick(pref);
     }
 
+    private Intent getIntentForStorage(String authority, String root) {
+        Intent intent = new Intent(Intent.ACTION_VIEW);
+        intent.setDataAndType(
+                DocumentsContract.buildRootUri(authority, root),
+                DocumentsContract.Root.MIME_TYPE_ITEM);
+        intent.addCategory(Intent.CATEGORY_DEFAULT);
+
+        return intent;
+    }
+
     private final MeasurementReceiver mReceiver = new MeasurementReceiver() {
         @Override
         public void onDetailsChanged(MeasurementDetails details) {
diff --git a/src/com/android/settings/deviceinfo/StorageDashboardFragment.java b/src/com/android/settings/deviceinfo/StorageDashboardFragment.java
index 75c0e75..602e65f 100644
--- a/src/com/android/settings/deviceinfo/StorageDashboardFragment.java
+++ b/src/com/android/settings/deviceinfo/StorageDashboardFragment.java
@@ -20,6 +20,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.Loader;
+import android.graphics.drawable.Drawable;
 import android.os.Bundle;
 import android.os.UserHandle;
 import android.os.UserManager;
@@ -47,6 +48,7 @@
 import com.android.settings.deviceinfo.storage.StorageAsyncLoader;
 import com.android.settings.deviceinfo.storage.StorageItemPreferenceController;
 import com.android.settings.deviceinfo.storage.StorageSummaryDonutPreferenceController;
+import com.android.settings.deviceinfo.storage.UserIconLoader;
 import com.android.settings.search.BaseSearchIndexProvider;
 import com.android.settings.search.Indexable;
 import com.android.settingslib.applications.StorageStatsSource;
@@ -61,6 +63,7 @@
     implements LoaderManager.LoaderCallbacks<SparseArray<StorageAsyncLoader.AppsStorageResult>> {
     private static final String TAG = "StorageDashboardFrag";
     private static final int STORAGE_JOB_ID = 0;
+    private static final int ICON_JOB_ID = 1;
     private static final int OPTIONS_MENU_MIGRATE_DATA = 100;
 
     private VolumeInfo mVolume;
@@ -71,34 +74,6 @@
     private List<PreferenceController> mSecondaryUsers;
 
     @Override
-    public void onResume() {
-        super.onResume();
-        getLoaderManager().initLoader(STORAGE_JOB_ID, Bundle.EMPTY, this);
-    }
-
-    @Override
-    public Loader<SparseArray<StorageAsyncLoader.AppsStorageResult>> onCreateLoader(int id,
-            Bundle args) {
-        Context context = getContext();
-        return new StorageAsyncLoader(context,
-                new UserManagerWrapperImpl(context.getSystemService(UserManager.class)),
-                mVolume.fsUuid,
-                new StorageStatsSource(context),
-                new PackageManagerWrapperImpl(context.getPackageManager()));
-    }
-
-    @Override
-    public void onLoadFinished(Loader<SparseArray<StorageAsyncLoader.AppsStorageResult>> loader,
-            SparseArray<StorageAsyncLoader.AppsStorageResult> data) {
-        mPreferenceController.onLoadFinished(data.get(UserHandle.myUserId()));
-        updateSecondaryUserControllers(mSecondaryUsers, data);
-    }
-
-    @Override
-    public void onLoaderReset(Loader<SparseArray<StorageAsyncLoader.AppsStorageResult>> loader) {
-    }
-
-    @Override
     public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
 
@@ -140,6 +115,13 @@
     }
 
     @Override
+    public void onResume() {
+        super.onResume();
+        getLoaderManager().initLoader(STORAGE_JOB_ID, Bundle.EMPTY, this);
+        getLoaderManager().initLoader(ICON_JOB_ID, Bundle.EMPTY, new IconLoaderCallbacks());
+    }
+
+    @Override
     public int getMetricsCategory() {
         return MetricsProto.MetricsEvent.SETTINGS_STORAGE_CATEGORY;
     }
@@ -227,4 +209,55 @@
                 }
 
             };
+
+    @Override
+    public Loader<SparseArray<StorageAsyncLoader.AppsStorageResult>> onCreateLoader(int id,
+            Bundle args) {
+        Context context = getContext();
+        return new StorageAsyncLoader(context,
+                new UserManagerWrapperImpl(context.getSystemService(UserManager.class)),
+                mVolume.fsUuid,
+                new StorageStatsSource(context),
+                new PackageManagerWrapperImpl(context.getPackageManager()));
+    }
+
+    @Override
+    public void onLoadFinished(Loader<SparseArray<StorageAsyncLoader.AppsStorageResult>> loader,
+            SparseArray<StorageAsyncLoader.AppsStorageResult> data) {
+        mPreferenceController.onLoadFinished(data.get(UserHandle.myUserId()));
+        updateSecondaryUserControllers(mSecondaryUsers, data);
+    }
+
+    @Override
+    public void onLoaderReset(Loader<SparseArray<StorageAsyncLoader.AppsStorageResult>> loader) {
+    }
+
+    /**
+     * IconLoaderCallbacks exists because StorageDashboardFragment already implements
+     * LoaderCallbacks for a different type.
+     */
+    public final class IconLoaderCallbacks
+            implements LoaderManager.LoaderCallbacks<SparseArray<Drawable>> {
+        @Override
+        public Loader<SparseArray<Drawable>> onCreateLoader(int id, Bundle args) {
+            return new UserIconLoader(
+                    getContext(),
+                    () -> UserIconLoader.loadUserIconsWithContext(getContext()));
+        }
+
+        @Override
+        public void onLoadFinished(
+                Loader<SparseArray<Drawable>> loader, SparseArray<Drawable> data) {
+            mSecondaryUsers
+                    .stream()
+                    .filter(controller -> controller instanceof UserIconLoader.UserIconHandler)
+                    .forEach(
+                            controller ->
+                                    ((UserIconLoader.UserIconHandler) controller)
+                                            .handleUserIcons(data));
+        }
+
+        @Override
+        public void onLoaderReset(Loader<SparseArray<Drawable>> loader) {}
+    }
 }
diff --git a/src/com/android/settings/deviceinfo/storage/SecondaryUserController.java b/src/com/android/settings/deviceinfo/storage/SecondaryUserController.java
index b3e89c6..62e946d 100644
--- a/src/com/android/settings/deviceinfo/storage/SecondaryUserController.java
+++ b/src/com/android/settings/deviceinfo/storage/SecondaryUserController.java
@@ -18,6 +18,7 @@
 
 import android.content.Context;
 import android.content.pm.UserInfo;
+import android.graphics.drawable.Drawable;
 import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.annotation.VisibleForTesting;
@@ -37,8 +38,8 @@
  * SecondaryUserController controls the preferences on the Storage screen which had to do with
  * secondary users.
  */
-public class SecondaryUserController extends PreferenceController implements
-        StorageAsyncLoader.ResultHandler {
+public class SecondaryUserController extends PreferenceController
+        implements StorageAsyncLoader.ResultHandler, UserIconLoader.UserIconHandler {
     // PreferenceGroupKey to try to add our preference onto.
     private static final String TARGET_PREFERENCE_GROUP_KEY = "pref_secondary_users";
     private static final String PREFERENCE_KEY_BASE = "pref_user_";
@@ -69,8 +70,9 @@
             }
 
             if (info == null || Utils.isProfileOf(primaryUser, info)) {
-                controllers.add(new UserProfileController(context, info,
-                        USER_PROFILE_INSERTION_LOCATION));
+                controllers.add(
+                        new UserProfileController(
+                                context, info, userManager, USER_PROFILE_INSERTION_LOCATION));
                 continue;
             }
 
@@ -109,8 +111,6 @@
                 mStoragePreference.setStorageSize(mSize, mTotalSizeBytes);
             }
 
-            // TODO(b/36252572): Set the user icon appropriately here.
-
             group.setVisible(true);
             group.addPreference(mStoragePreference);
         }
@@ -161,6 +161,14 @@
         }
     }
 
+    @Override
+    public void handleUserIcons(SparseArray<Drawable> fetchedIcons) {
+        Drawable userIcon = fetchedIcons.get(mUser.id);
+        if (userIcon != null) {
+            mStoragePreference.setIcon(userIcon);
+        }
+    }
+
     private static class NoSecondaryUserController extends PreferenceController {
         public NoSecondaryUserController(Context context) {
             super(context);
diff --git a/src/com/android/settings/deviceinfo/storage/UserIconLoader.java b/src/com/android/settings/deviceinfo/storage/UserIconLoader.java
new file mode 100644
index 0000000..4f00c3c
--- /dev/null
+++ b/src/com/android/settings/deviceinfo/storage/UserIconLoader.java
@@ -0,0 +1,75 @@
+/*
+ * 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.deviceinfo.storage;
+
+import android.content.Context;
+import android.content.pm.UserInfo;
+import android.graphics.drawable.Drawable;
+import android.os.UserManager;
+import android.util.Log;
+import android.util.SparseArray;
+
+import com.android.internal.util.Preconditions;
+import com.android.settings.Utils;
+import com.android.settings.utils.AsyncLoader;
+
+/**
+ * Fetches a user icon as a loader using a given icon loading lambda.
+ */
+public class UserIconLoader extends AsyncLoader<SparseArray<Drawable>> {
+    private FetchUserIconTask mTask;
+
+    /**
+     * Task to load all user icons.
+     */
+    public interface FetchUserIconTask {
+        SparseArray<Drawable> getUserIcons();
+    }
+
+    /**
+     * Handle the output of this task.
+     */
+    public interface UserIconHandler {
+        void handleUserIcons(SparseArray<Drawable> fetchedIcons);
+    }
+
+    public UserIconLoader(Context context, FetchUserIconTask task) {
+        super(context);
+        mTask = Preconditions.checkNotNull(task);
+    }
+
+    @Override
+    public SparseArray<Drawable> loadInBackground() {
+        return mTask.getUserIcons();
+    }
+
+    @Override
+    protected void onDiscardResult(SparseArray<Drawable> result) {}
+
+    /**
+     * Loads the user icons using a given context. This returns a {@link SparseArray} which maps
+     * user ids to their user icons.
+     */
+    public static SparseArray<Drawable> loadUserIconsWithContext(Context context) {
+        SparseArray<Drawable> value = new SparseArray<>();
+        UserManager um = context.getSystemService(UserManager.class);
+        for (UserInfo userInfo : um.getUsers()) {
+            value.put(userInfo.id, Utils.getUserIcon(context, um, userInfo));
+        }
+        return value;
+    }
+}
diff --git a/src/com/android/settings/deviceinfo/storage/UserProfileController.java b/src/com/android/settings/deviceinfo/storage/UserProfileController.java
index 0e19740..18fa7b7 100644
--- a/src/com/android/settings/deviceinfo/storage/UserProfileController.java
+++ b/src/com/android/settings/deviceinfo/storage/UserProfileController.java
@@ -19,6 +19,7 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.UserInfo;
+import android.graphics.drawable.Drawable;
 import android.os.Bundle;
 import android.os.storage.VolumeInfo;
 import android.support.v7.preference.Preference;
@@ -28,25 +29,27 @@
 import com.android.internal.logging.nano.MetricsProto;
 import com.android.internal.util.Preconditions;
 import com.android.settings.Utils;
+import com.android.settings.applications.UserManagerWrapper;
 import com.android.settings.core.PreferenceController;
 import com.android.settings.deviceinfo.StorageItemPreference;
 import com.android.settings.deviceinfo.StorageProfileFragment;
 import com.android.settingslib.drawer.SettingsDrawerActivity;
 
-/**
- * Defines a {@link PreferenceController} which handles a single profile of the primary user.
- */
-public class UserProfileController extends PreferenceController implements
-        StorageAsyncLoader.ResultHandler {
+/** Defines a {@link PreferenceController} which handles a single profile of the primary user. */
+public class UserProfileController extends PreferenceController
+        implements StorageAsyncLoader.ResultHandler, UserIconLoader.UserIconHandler {
     private static final String PREFERENCE_KEY_BASE = "pref_profile_";
     private StorageItemPreference mStoragePreference;
+    private UserManagerWrapper mUserManager;
     private UserInfo mUser;
     private long mTotalSizeBytes;
     private final int mPreferenceOrder;
 
-    public UserProfileController(Context context, UserInfo info, int preferenceOrder) {
+    public UserProfileController(
+            Context context, UserInfo info, UserManagerWrapper userManager, int preferenceOrder) {
         super(context);
         mUser = Preconditions.checkNotNull(info);
+        mUserManager = userManager;
         mPreferenceOrder = preferenceOrder;
     }
 
@@ -66,7 +69,6 @@
         mStoragePreference.setOrder(mPreferenceOrder);
         mStoragePreference.setKey(PREFERENCE_KEY_BASE + mUser.id);
         mStoragePreference.setTitle(mUser.name);
-        // TODO(b/36252572): Set user icon here.
         screen.addPreference(mStoragePreference);
     }
 
@@ -110,4 +112,12 @@
     public void setTotalSize(long totalSize) {
         mTotalSizeBytes = totalSize;
     }
+
+    @Override
+    public void handleUserIcons(SparseArray<Drawable> fetchedIcons) {
+        Drawable userIcon = fetchedIcons.get(mUser.id);
+        if (userIcon != null) {
+            mStoragePreference.setIcon(userIcon);
+        }
+    }
 }
diff --git a/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetail.java b/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetail.java
index 39b72cc..320031e 100644
--- a/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetail.java
+++ b/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetail.java
@@ -104,10 +104,11 @@
         final Bundle args = new Bundle();
         final BatterySipper sipper = entry.sipper;
         final BatteryStats.Uid uid = sipper.uidObj;
+        final BatteryUtils batteryUtils = BatteryUtils.getInstance(caller);
 
-        final long backgroundTimeMs = BatteryUtils.getProcessTimeMs(
+        final long backgroundTimeMs = batteryUtils.getProcessTimeMs(
                 BatteryUtils.StatusType.BACKGROUND, uid, which);
-        final long foregroundTimeMs = BatteryUtils.getProcessTimeMs(
+        final long foregroundTimeMs = batteryUtils.getProcessTimeMs(
                 BatteryUtils.StatusType.FOREGROUND, uid, which);
 
         if (ArrayUtils.isEmpty(sipper.mPackages)) {
diff --git a/src/com/android/settings/fuelgauge/BatteryUtils.java b/src/com/android/settings/fuelgauge/BatteryUtils.java
index 85bc0fd..a3ea5cd 100644
--- a/src/com/android/settings/fuelgauge/BatteryUtils.java
+++ b/src/com/android/settings/fuelgauge/BatteryUtils.java
@@ -16,9 +16,13 @@
 package com.android.settings.fuelgauge;
 
 import android.annotation.IntDef;
+import android.content.Context;
+import android.content.pm.PackageManager;
 import android.os.BatteryStats;
 import android.os.SystemClock;
 import android.support.annotation.Nullable;
+import android.support.annotation.VisibleForTesting;
+import android.util.Log;
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -38,7 +42,23 @@
         int ALL = 2;
     }
 
-    public static long getProcessTimeMs(@StatusType int type, @Nullable BatteryStats.Uid uid,
+    private static final String TAG = "BatteryUtils";
+    private static BatteryUtils sInstance;
+
+    private PackageManager mPackageManager;
+
+    public static BatteryUtils getInstance(Context context) {
+        if (sInstance == null || sInstance.isDataCorrupted()) {
+            sInstance = new BatteryUtils(context);
+        }
+        return sInstance;
+    }
+
+    private BatteryUtils(Context context) {
+        mPackageManager = context.getPackageManager();
+    }
+
+    public long getProcessTimeMs(@StatusType int type, @Nullable BatteryStats.Uid uid,
             int which) {
         if (uid == null) {
             return 0;
@@ -56,34 +76,46 @@
         return 0;
     }
 
-    private static long getProcessBackgroundTimeMs(BatteryStats.Uid uid, int which) {
+    private long getProcessBackgroundTimeMs(BatteryStats.Uid uid, int which) {
         final long rawRealTimeUs = convertMsToUs(SystemClock.elapsedRealtime());
         final long timeUs = uid.getProcessStateTime(
                 BatteryStats.Uid.PROCESS_STATE_BACKGROUND, rawRealTimeUs, which);
-        return  convertUsToMs(timeUs);
+
+        Log.v(TAG, "package: " + mPackageManager.getNameForUid(uid.getUid()));
+        Log.v(TAG, "background time(us): " + timeUs);
+        return convertUsToMs(timeUs);
     }
 
-    private static long getProcessForegroundTimeMs(BatteryStats.Uid uid, int which) {
+    private long getProcessForegroundTimeMs(BatteryStats.Uid uid, int which) {
         final long rawRealTimeUs = convertMsToUs(SystemClock.elapsedRealtime());
         final int foregroundTypes[] = {BatteryStats.Uid.PROCESS_STATE_TOP,
                 BatteryStats.Uid.PROCESS_STATE_FOREGROUND_SERVICE,
                 BatteryStats.Uid.PROCESS_STATE_TOP_SLEEPING,
                 BatteryStats.Uid.PROCESS_STATE_FOREGROUND};
+        Log.v(TAG, "package: " + mPackageManager.getNameForUid(uid.getUid()));
+
         long timeUs = 0;
         for (int type : foregroundTypes) {
-            timeUs += uid.getProcessStateTime(type, rawRealTimeUs, which);
+            final long localTime = uid.getProcessStateTime(type, rawRealTimeUs, which);
+            Log.v(TAG, "type: " + type + " time(us): " + localTime);
+            timeUs += localTime;
         }
+        Log.v(TAG, "foreground time(us): " + timeUs);
 
         return convertUsToMs(timeUs);
     }
 
-    private static long convertUsToMs(long timeUs) {
+    private long convertUsToMs(long timeUs) {
         return timeUs / 1000;
     }
 
-    private static long convertMsToUs(long timeMs) {
+    private long convertMsToUs(long timeMs) {
         return timeMs * 1000;
     }
 
+    private boolean isDataCorrupted() {
+        return mPackageManager == null;
+    }
+
 }
 
diff --git a/src/com/android/settings/fuelgauge/PowerUsageAdvanced.java b/src/com/android/settings/fuelgauge/PowerUsageAdvanced.java
index b341760..3509834 100644
--- a/src/com/android/settings/fuelgauge/PowerUsageAdvanced.java
+++ b/src/com/android/settings/fuelgauge/PowerUsageAdvanced.java
@@ -74,6 +74,7 @@
     private PackageManager mPackageManager;
     private UserManager mUserManager;
     private Map<Integer, PowerUsageData> mBatteryDataMap;
+    private BatteryUtils mBatteryUtils;
 
     Handler mHandler = new Handler() {
 
@@ -117,6 +118,7 @@
                 .getPowerUsageFeatureProvider(context);
         mPackageManager = context.getPackageManager();
         mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
+        mBatteryUtils = BatteryUtils.getInstance(context);
     }
 
     @Override
@@ -239,8 +241,8 @@
             final PowerUsageData usageData = batteryDataMap.get(extractUsageType(sipper));
             usageData.totalPowerMah += sipper.totalPowerMah;
             if (sipper.drainType == DrainType.APP && sipper.usageTimeMs != 0) {
-                sipper.usageTimeMs = BatteryUtils.getProcessTimeMs(BatteryUtils.StatusType.ALL,
-                        sipper.uidObj, STATUS_TYPE);
+                sipper.usageTimeMs = mBatteryUtils.getProcessTimeMs(
+                        BatteryUtils.StatusType.FOREGROUND, sipper.uidObj, STATUS_TYPE);
             }
             usageData.totalUsageTimeMs += sipper.usageTimeMs;
             usageData.usageList.add(sipper);
diff --git a/src/com/android/settings/fuelgauge/PowerUsageSummary.java b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
index d9323db..b23f9e3 100644
--- a/src/com/android/settings/fuelgauge/PowerUsageSummary.java
+++ b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
@@ -110,6 +110,8 @@
     PowerGaugePreference mLastFullChargePref;
     @VisibleForTesting
     PowerUsageFeatureProvider mPowerFeatureProvider;
+    @VisibleForTesting
+    BatteryUtils mBatteryUtils;
 
     private LayoutPreference mBatteryLayoutPref;
     private PreferenceGroup mAppListGroup;
@@ -127,6 +129,8 @@
                 KEY_TIME_SINCE_LAST_FULL_CHARGE);
         mFooterPreferenceMixin.createFooterPreference().setTitle(R.string.battery_footer_summary);
 
+        mBatteryUtils = BatteryUtils.getInstance(getContext());
+
         initFeatureProvider();
     }
 
@@ -494,7 +498,7 @@
                 pref.setOrder(i + 1);
                 pref.setPercent(percentOfTotal);
                 if (sipper.usageTimeMs == 0 && sipper.drainType == DrainType.APP) {
-                    sipper.usageTimeMs = BatteryUtils.getProcessTimeMs(
+                    sipper.usageTimeMs = mBatteryUtils.getProcessTimeMs(
                             BatteryUtils.StatusType.FOREGROUND, sipper.uidObj, mStatsType);
                 }
                 setUsageSummary(pref, usedTime, sipper.usageTimeMs);
diff --git a/src/com/android/settings/notification/AppNotificationSettings.java b/src/com/android/settings/notification/AppNotificationSettings.java
index c38b89d..78b9b1e 100644
--- a/src/com/android/settings/notification/AppNotificationSettings.java
+++ b/src/com/android/settings/notification/AppNotificationSettings.java
@@ -269,11 +269,6 @@
             if (left.isDeleted() != right.isDeleted()) {
                 return Boolean.compare(left.isDeleted(), right.isDeleted());
             }
-            CharSequence leftName = left.getName();
-            CharSequence rightName = right.getName();
-            if (!Objects.equals(leftName, rightName)) {
-                return sCollator.compare(leftName.toString(), rightName.toString());
-            }
             return left.getId().compareTo(right.getId());
         }
     };
@@ -290,12 +285,6 @@
                     } else if (right.getId() == null && left.getId() != null) {
                         return -1;
                     }
-                    CharSequence leftName = left.getName();
-                    CharSequence rightName = right.getName();
-                    // sort rest of the groups by name
-                    if (!Objects.equals(leftName, rightName)) {
-                        return sCollator.compare(leftName.toString(), rightName.toString());
-                    }
                     return left.getId().compareTo(right.getId());
                 }
             };
diff --git a/src/com/android/settings/search/IndexDatabaseHelper.java b/src/com/android/settings/search/IndexDatabaseHelper.java
index 60378c2..76346ec 100644
--- a/src/com/android/settings/search/IndexDatabaseHelper.java
+++ b/src/com/android/settings/search/IndexDatabaseHelper.java
@@ -245,7 +245,7 @@
         return version;
     }
 
-    public static void clearLocalesIndexed(Context context) {
+    public static void clearCachedIndexed(Context context) {
         context.getSharedPreferences(INDEX, 0).edit().clear().commit();
     }
 
@@ -257,8 +257,16 @@
         return context.getSharedPreferences(INDEX, 0).getBoolean(locale, false);
     }
 
+    public static boolean isBuildIndexed(Context context, String buildNo) {
+        return context.getSharedPreferences(INDEX, 0).getBoolean(buildNo, false);
+    }
+
+    public static void setBuildIndexed(Context context, String buildNo) {
+        context.getSharedPreferences(INDEX, 0).edit().putBoolean(buildNo, true).commit();
+    }
+
     private void dropTables(SQLiteDatabase db) {
-        clearLocalesIndexed(mContext);
+        clearCachedIndexed(mContext);
         db.execSQL("DROP TABLE IF EXISTS " + Tables.TABLE_META_INDEX);
         db.execSQL("DROP TABLE IF EXISTS " + Tables.TABLE_PREFS_INDEX);
         db.execSQL("DROP TABLE IF EXISTS " + Tables.TABLE_SAVED_QUERIES);
diff --git a/src/com/android/settings/search2/DatabaseIndexingManager.java b/src/com/android/settings/search2/DatabaseIndexingManager.java
index 1e664ff..533884d 100644
--- a/src/com/android/settings/search2/DatabaseIndexingManager.java
+++ b/src/com/android/settings/search2/DatabaseIndexingManager.java
@@ -29,6 +29,7 @@
 import android.database.sqlite.SQLiteException;
 import android.net.Uri;
 import android.os.AsyncTask;
+import android.os.Build;
 import android.provider.SearchIndexableData;
 import android.provider.SearchIndexableResource;
 import android.provider.SearchIndexablesContract;
@@ -170,7 +171,16 @@
         final List<ResolveInfo> list =
                 mContext.getPackageManager().queryIntentContentProviders(intent, 0);
 
-        final boolean isLocaleIndexed = isLocaleIndexed();
+        final String localeStr = Locale.getDefault().toString();
+        final String fingerprint = Build.FINGERPRINT;
+        final boolean isFullIndex = isFullIndex(localeStr, fingerprint);
+
+        // Drop the database when the locale or build has changed. This eliminates rows which are
+        // dynamically inserted in the old language, or deprecated settings.
+        if (isFullIndex) {
+            final SQLiteDatabase db = getWritableDatabase();
+            IndexDatabaseHelper.getInstance(mContext).reconstruct(db);
+        }
 
         for (final ResolveInfo info : list) {
             if (!DatabaseIndexingUtils.isWellKnownProvider(info, mContext)) {
@@ -179,22 +189,32 @@
             final String authority = info.providerInfo.authority;
             final String packageName = info.providerInfo.packageName;
 
-            if (!isLocaleIndexed) {
+            if (isFullIndex) {
                 addIndexablesFromRemoteProvider(packageName, authority);
             }
             addNonIndexablesKeysFromRemoteProvider(packageName, authority);
         }
 
-        final String localeStr = Locale.getDefault().toString();
-        updateDatabase(isLocaleIndexed, localeStr);
+        updateDatabase(isFullIndex, localeStr);
 
         IndexDatabaseHelper.setLocaleIndexed(mContext, localeStr);
+        IndexDatabaseHelper.setBuildIndexed(mContext, fingerprint);
     }
 
+    /**
+     * Perform a full index on an OTA or when the locale has changed
+     *
+     * @param locale is the default for the device
+     * @param fingerprint id for the current build.
+     * @return true when the locale or build has changed since last index.
+     */
     @VisibleForTesting
-    boolean isLocaleIndexed() {
-        final String locale = Locale.getDefault().toString();
-        return IndexDatabaseHelper.getInstance(mContext).isLocaleAlreadyIndexed(mContext, locale);
+    boolean isFullIndex(String locale, String fingerprint) {
+        final boolean isLocaleIndexed = IndexDatabaseHelper.getInstance(mContext)
+                .isLocaleAlreadyIndexed(mContext, locale);
+        final boolean isBuildIndexed = IndexDatabaseHelper.getInstance(mContext)
+                .isBuildIndexed(mContext, fingerprint);
+        return !isLocaleIndexed || !isBuildIndexed;
     }
 
     /**
@@ -204,11 +224,11 @@
      * Then search results are verified to have the correct value of enabled.
      * Finally, we record that the locale has been indexed.
      *
-     * @param isIncrementalUpdate true when the language has already been indexed.
+     * @param needsReindexing true the database needs to be rebuilt.
      * @param localeStr the default locale for the device.
      */
     @VisibleForTesting
-    void updateDatabase(boolean isIncrementalUpdate, String localeStr) {
+    void updateDatabase(boolean needsReindexing, String localeStr) {
         mIsAvailable.set(false);
         final UpdateData copy;
 
@@ -236,7 +256,7 @@
 
             // Only check for non-indexable key updates after initial index.
             // Enabled state with non-indexable keys is checked when items are first inserted.
-            if (isIncrementalUpdate) {
+            if (!needsReindexing) {
                 updateDataInDatabase(database, nonIndexableKeys);
             }
 
@@ -284,7 +304,7 @@
      * @param database The database to validate.
      * @param nonIndexableKeys A map between package name and the set of non-indexable keys for it.
      */
-    @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+    @VisibleForTesting
     void updateDataInDatabase(SQLiteDatabase database,
             Map<String, Set<String>> nonIndexableKeys) {
         final String whereEnabled = ENABLED + " = 1";
@@ -348,7 +368,6 @@
     @VisibleForTesting
     boolean addIndexablesFromRemoteProvider(String packageName, String authority) {
         try {
-
             final Context context = mBaseAuthority.equals(authority) ?
                     mContext : mContext.createPackageContext(packageName, 0);
 
diff --git a/src/com/android/settings/vpn2/AppDialogFragment.java b/src/com/android/settings/vpn2/AppDialogFragment.java
index b24db4e..f8e6af0 100644
--- a/src/com/android/settings/vpn2/AppDialogFragment.java
+++ b/src/com/android/settings/vpn2/AppDialogFragment.java
@@ -18,7 +18,6 @@
 
 import android.app.AlertDialog;
 import android.app.Dialog;
-import android.app.DialogFragment;
 import android.app.Fragment;
 import android.content.Context;
 import android.content.DialogInterface;
@@ -67,13 +66,18 @@
 
     public static void show(Fragment parent, PackageInfo packageInfo, String label,
             boolean managing, boolean connected) {
+        if (!managing && !connected) {
+            // We can't display anything useful for this case.
+            return;
+        }
         show(parent, null, packageInfo, label, managing, connected);
     }
 
     public static void show(Fragment parent, Listener listener, PackageInfo packageInfo,
             String label, boolean managing, boolean connected) {
-        if (!parent.isAdded())
+        if (!parent.isAdded()) {
             return;
+        }
 
         Bundle args = new Bundle();
         args.putParcelable(ARG_PACKAGE, packageInfo);
@@ -100,7 +104,7 @@
         final String label = args.getString(ARG_LABEL);
         boolean managing = args.getBoolean(ARG_MANAGING);
         boolean connected = args.getBoolean(ARG_CONNECTED);
-        mPackageInfo = (PackageInfo) args.getParcelable(ARG_PACKAGE);
+        mPackageInfo = args.getParcelable(ARG_PACKAGE);
 
         if (managing) {
             return new AppDialog(getActivity(), this, mPackageInfo, label);
diff --git a/src/com/android/settings/wifi/WifiConfigController.java b/src/com/android/settings/wifi/WifiConfigController.java
index 4380cbe..fe2bbb3 100644
--- a/src/com/android/settings/wifi/WifiConfigController.java
+++ b/src/com/android/settings/wifi/WifiConfigController.java
@@ -106,6 +106,9 @@
     public static final int WIFI_PEAP_PHASE2_NONE       = 0;
     public static final int WIFI_PEAP_PHASE2_MSCHAPV2   = 1;
     public static final int WIFI_PEAP_PHASE2_GTC        = 2;
+    public static final int WIFI_PEAP_PHASE2_SIM        = 3;
+    public static final int WIFI_PEAP_PHASE2_AKA        = 4;
+    public static final int WIFI_PEAP_PHASE2_AKA_PRIME  = 5;
 
     /* Phase2 methods supported by PEAP are limited */
     private final ArrayAdapter<String> mPhase2PeapAdapter;
@@ -176,9 +179,16 @@
         final Resources res = mContext.getResources();
 
         mLevels = res.getStringArray(R.array.wifi_signal);
-        mPhase2PeapAdapter = new ArrayAdapter<String>(
-            mContext, android.R.layout.simple_spinner_item,
-            res.getStringArray(R.array.wifi_peap_phase2_entries));
+        if (Utils.isWifiOnly(mContext) || !mContext.getResources().getBoolean(
+                com.android.internal.R.bool.config_eap_sim_based_auth_supported)) {
+            mPhase2PeapAdapter = new ArrayAdapter<String>(
+                    mContext, android.R.layout.simple_spinner_item,
+                    res.getStringArray(R.array.wifi_peap_phase2_entries));
+        } else {
+            mPhase2PeapAdapter = new ArrayAdapter<String>(
+                    mContext, android.R.layout.simple_spinner_item,
+                    res.getStringArray(R.array.wifi_peap_phase2_entries_with_sim_auth));
+        }
         mPhase2PeapAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 
         mPhase2FullAdapter = new ArrayAdapter<String>(
@@ -532,6 +542,15 @@
                             case WIFI_PEAP_PHASE2_GTC:
                                 config.enterpriseConfig.setPhase2Method(Phase2.GTC);
                                 break;
+                            case WIFI_PEAP_PHASE2_SIM:
+                                config.enterpriseConfig.setPhase2Method(Phase2.SIM);
+                                break;
+                            case WIFI_PEAP_PHASE2_AKA:
+                                config.enterpriseConfig.setPhase2Method(Phase2.AKA);
+                                break;
+                            case WIFI_PEAP_PHASE2_AKA_PRIME:
+                                config.enterpriseConfig.setPhase2Method(Phase2.AKA_PRIME);
+                                break;
                             default:
                                 Log.e(TAG, "Unknown phase2 method" + phase2Method);
                                 break;
@@ -795,6 +814,7 @@
                 mEapMethodSpinner.setAdapter(spinnerAdapter);
             }
             mPhase2Spinner = (Spinner) mView.findViewById(R.id.phase2);
+            mPhase2Spinner.setOnItemSelectedListener(this);
             mEapCaCertSpinner = (Spinner) mView.findViewById(R.id.ca_cert);
             mEapCaCertSpinner.setOnItemSelectedListener(this);
             mEapDomainView = (TextView) mView.findViewById(R.id.domain);
@@ -836,6 +856,15 @@
                             case Phase2.GTC:
                                 mPhase2Spinner.setSelection(WIFI_PEAP_PHASE2_GTC);
                                 break;
+                            case Phase2.SIM:
+                                mPhase2Spinner.setSelection(WIFI_PEAP_PHASE2_SIM);
+                                break;
+                            case Phase2.AKA:
+                                mPhase2Spinner.setSelection(WIFI_PEAP_PHASE2_AKA);
+                                break;
+                            case Phase2.AKA_PRIME:
+                                mPhase2Spinner.setSelection(WIFI_PEAP_PHASE2_AKA_PRIME);
+                                break;
                             default:
                                 Log.e(TAG, "Invalid phase 2 method " + phase2Method);
                                 break;
@@ -874,6 +903,7 @@
                 mEapIdentityView.setText(enterpriseConfig.getIdentity());
                 mEapAnonymousView.setText(enterpriseConfig.getAnonymousIdentity());
             } else {
+                mPhase2Spinner = (Spinner) mView.findViewById(R.id.phase2);
                 showEapFieldsByMethod(mEapMethodSpinner.getSelectedItemPosition());
             }
         } else {
@@ -886,11 +916,11 @@
      *   identity
      *   password
      * EAP-PEAP valid fields include
-     *   phase2: MSCHAPV2, GTC
+     *   phase2: MSCHAPV2, GTC, SIM, AKA, AKA'
      *   ca_cert
      *   identity
      *   anonymous_identity
-     *   password
+     *   password (not required for SIM, AKA, AKA')
      * EAP-TLS valid fields include
      *   user_cert
      *   ca_cert
@@ -938,6 +968,7 @@
                 }
                 mView.findViewById(R.id.l_phase2).setVisibility(View.VISIBLE);
                 mView.findViewById(R.id.l_anonymous).setVisibility(View.VISIBLE);
+                showPeapFields();
                 setUserCertInvisible();
                 break;
             case WIFI_EAP_METHOD_TTLS:
@@ -974,6 +1005,21 @@
         }
     }
 
+    private void showPeapFields() {
+        int phase2Method = mPhase2Spinner.getSelectedItemPosition();
+        if (phase2Method == WIFI_PEAP_PHASE2_SIM || phase2Method == WIFI_PEAP_PHASE2_AKA
+                 || phase2Method == WIFI_PEAP_PHASE2_AKA_PRIME) {
+            mEapIdentityView.setText("");
+            mView.findViewById(R.id.l_identity).setVisibility(View.GONE);
+            setPasswordInvisible();
+        } else {
+            mView.findViewById(R.id.l_identity).setVisibility(View.VISIBLE);
+            mView.findViewById(R.id.l_anonymous).setVisibility(View.VISIBLE);
+            mView.findViewById(R.id.password_layout).setVisibility(View.VISIBLE);
+            mView.findViewById(R.id.show_password_layout).setVisibility(View.VISIBLE);
+        }
+    }
+
     private void setIdentityInvisible() {
         mView.findViewById(R.id.l_identity).setVisibility(View.GONE);
         mPhase2Spinner.setSelection(Phase2.NONE);
@@ -1239,6 +1285,9 @@
             showSecurityFields();
         } else if (parent == mEapMethodSpinner || parent == mEapCaCertSpinner) {
             showSecurityFields();
+        } else if (parent == mPhase2Spinner
+                && mEapMethodSpinner.getSelectedItemPosition() == WIFI_EAP_METHOD_PEAP) {
+            showPeapFields();
         } else if (parent == mProxySettingsSpinner) {
             showProxyFields();
         } else {
diff --git a/src/com/android/settings/wifi/details/WifiDetailPreferenceController.java b/src/com/android/settings/wifi/details/WifiDetailPreferenceController.java
index 92e12b0..faa2a77 100644
--- a/src/com/android/settings/wifi/details/WifiDetailPreferenceController.java
+++ b/src/com/android/settings/wifi/details/WifiDetailPreferenceController.java
@@ -18,18 +18,20 @@
 import android.content.Context;
 import android.graphics.drawable.Drawable;
 import android.net.ConnectivityManager;
-import android.net.DhcpInfo;
+import android.net.IpPrefix;
 import android.net.LinkProperties;
 import android.net.Network;
 import android.net.NetworkBadging;
 import android.net.NetworkInfo;
 import android.net.NetworkUtils;
+import android.net.RouteInfo;
 import android.net.wifi.WifiConfiguration;
 import android.net.wifi.WifiInfo;
 import android.net.wifi.WifiManager;
 import android.support.v7.preference.Preference;
 import android.support.v7.preference.PreferenceCategory;
 import android.support.v7.preference.PreferenceScreen;
+import android.text.TextUtils;
 import android.util.Log;
 
 import com.android.internal.annotations.VisibleForTesting;
@@ -44,7 +46,9 @@
 import java.net.Inet4Address;
 import java.net.Inet6Address;
 import java.net.InetAddress;
+import java.net.UnknownHostException;
 import java.util.List;
+import java.util.StringJoiner;
 
 /**
  * Controller for logic pertaining to displaying Wifi information for the
@@ -65,9 +69,11 @@
     @VisibleForTesting
     static final String KEY_SECURITY_PREF = "security";
     @VisibleForTesting
+    static final String KEY_MAC_ADDRESS_PREF = "mac_address";
+    @VisibleForTesting
     static final String KEY_IP_ADDRESS_PREF = "ip_address";
     @VisibleForTesting
-    static final String KEY_ROUTER_PREF = "router";
+    static final String KEY_GATEWAY_PREF = "gateway";
     @VisibleForTesting
     static final String KEY_SUBNET_MASK_PREF = "subnet_mask";
     @VisibleForTesting
@@ -83,6 +89,7 @@
     private WifiConfiguration mWifiConfig;
     private WifiInfo mWifiInfo;
     private final WifiManager mWifiManager;
+    private final ConnectivityManager mConnectivityManager;
 
     // Preferences - in order of appearance
     private Preference mConnectionDetailPref;
@@ -90,14 +97,15 @@
     private WifiDetailPreference mLinkSpeedPref;
     private WifiDetailPreference mFrequencyPref;
     private WifiDetailPreference mSecurityPref;
+    private WifiDetailPreference mMacAddressPref;
     private WifiDetailPreference mIpAddressPref;
-    private WifiDetailPreference mRouterPref;
+    private WifiDetailPreference mGatewayPref;
     private WifiDetailPreference mSubnetPref;
     private WifiDetailPreference mDnsPref;
     private PreferenceCategory mIpv6AddressCategory;
 
     public WifiDetailPreferenceController(AccessPoint accessPoint, Context context,
-            Lifecycle lifecycle, WifiManager wifiManager) {
+            Lifecycle lifecycle, WifiManager wifiManager, ConnectivityManager connectivityManager) {
         super(context);
 
         mAccessPoint = accessPoint;
@@ -106,6 +114,7 @@
         mSignalStr = context.getResources().getStringArray(R.array.wifi_signal);
         mWifiConfig = accessPoint.getConfig();
         mWifiManager = wifiManager;
+        mConnectivityManager = connectivityManager;
         mWifiInfo = wifiManager.getConnectionInfo();
 
         lifecycle.addObserver(this);
@@ -136,8 +145,9 @@
         mFrequencyPref = (WifiDetailPreference) screen.findPreference(KEY_FREQUENCY_PREF);
         mSecurityPref = (WifiDetailPreference) screen.findPreference(KEY_SECURITY_PREF);
 
+        mMacAddressPref = (WifiDetailPreference) screen.findPreference(KEY_MAC_ADDRESS_PREF);
         mIpAddressPref = (WifiDetailPreference) screen.findPreference(KEY_IP_ADDRESS_PREF);
-        mRouterPref = (WifiDetailPreference) screen.findPreference(KEY_ROUTER_PREF);
+        mGatewayPref = (WifiDetailPreference) screen.findPreference(KEY_GATEWAY_PREF);
         mSubnetPref = (WifiDetailPreference) screen.findPreference(KEY_SUBNET_MASK_PREF);
         mDnsPref = (WifiDetailPreference) screen.findPreference(KEY_DNS_PREF);
 
@@ -174,6 +184,9 @@
         mConnectionDetailPref.setIcon(wifiIcon);
         mConnectionDetailPref.setTitle(mAccessPoint.getSettingsSummary());
 
+        // MAC Address Pref
+        mMacAddressPref.setDetailText(mWifiInfo.getMacAddress());
+
         // Signal Strength Pref
         Drawable wifiIconDark = wifiIcon.getConstantState().newDrawable().mutate();
         wifiIconDark.setTint(mContext.getResources().getColor(
@@ -184,6 +197,8 @@
         mSignalStrengthPref.setDetailText(mSignalStr[summarySignalLevel]);
 
         // Link Speed Pref
+        int linkSpeedMbps = mWifiInfo.getLinkSpeed();
+        mLinkSpeedPref.setVisible(linkSpeedMbps >= 0);
         mLinkSpeedPref.setDetailText(mContext.getString(
                 R.string.link_speed, mWifiInfo.getLinkSpeed()));
 
@@ -203,67 +218,87 @@
     }
 
     private void setIpText() {
+        // Reset all fields
         mIpv6AddressCategory.removeAll();
         mIpv6AddressCategory.setVisible(false);
+        mIpAddressPref.setVisible(false);
+        mSubnetPref.setVisible(false);
+        mGatewayPref.setVisible(false);
+        mDnsPref.setVisible(false);
 
         Network currentNetwork = mWifiManager.getCurrentNetwork();
         if (currentNetwork == null) {
             return;
         }
 
-        ConnectivityManager cm = mContext.getSystemService(ConnectivityManager.class);
-        LinkProperties prop = cm.getLinkProperties(currentNetwork);
-        List<InetAddress> addresses = prop.getAllAddresses();
+        LinkProperties linkProperties = mConnectivityManager.getLinkProperties(currentNetwork);
+        if (linkProperties == null) {
+            return;
+        }
+        List<InetAddress> addresses = linkProperties.getAddresses();
 
-        // Set ip addresses
+        // Set IPv4 and Ipv6 addresses
         for (int i = 0; i < addresses.size(); i++) {
             InetAddress addr = addresses.get(i);
             if (addr instanceof Inet4Address) {
                 mIpAddressPref.setDetailText(addr.getHostAddress());
+                mIpAddressPref.setVisible(true);
             } else if (addr instanceof Inet6Address) {
                 String ip = addr.getHostAddress();
                 Preference pref = new Preference(mPrefContext);
                 pref.setKey(ip);
                 pref.setTitle(ip);
                 mIpv6AddressCategory.addPreference(pref);
-                mIpv6AddressCategory.setVisible(true); // TODO(sghuman): Make sure to
+                mIpv6AddressCategory.setVisible(true);
             }
         }
 
-        String subnetMask = null;
-        String router;
-        DhcpInfo dhcp = mWifiManager.getDhcpInfo();
-        if (dhcp != null) {
-            if (dhcp.netmask == 0) {
-                Log.e(TAG, "invalid netmask value of 0 for DhcpInfo: " + dhcp);
-                mSubnetPref.setVisible(false);
-            } else {
-                subnetMask = NetworkUtils.intToInetAddress(dhcp.netmask).getHostAddress();
-                mSubnetPref.setVisible(true);
+        // Set up IPv4 gateway and subnet mask
+        String gateway = null;
+        String subnet = null;
+        for (RouteInfo routeInfo : linkProperties.getRoutes()) {
+            if (routeInfo.hasGateway() && routeInfo.getGateway() instanceof Inet4Address) {
+                gateway = routeInfo.getGateway().getHostAddress();
             }
-
-            router = NetworkUtils.intToInetAddress(dhcp.gateway).getHostAddress();
-        } else { // Statically configured IP
-
-            // TODO(sghuman): How do we get subnet mask for static ips?
-            mSubnetPref.setVisible(false);
-
-            router = mWifiManager.getWifiApConfiguration().getStaticIpConfiguration().gateway
-                    .getHostAddress();
+            IpPrefix ipPrefix = routeInfo.getDestination();
+            if (ipPrefix != null && ipPrefix.getAddress() instanceof Inet4Address
+                    && ipPrefix.getPrefixLength() > 0) {
+                subnet = ipv4PrefixLengthToSubnetMask(ipPrefix.getPrefixLength());
+            }
         }
-        mRouterPref.setDetailText(router);
-        mSubnetPref.setDetailText(subnetMask);
 
-        // Set DNS
-        addresses = prop.getDnsServers();
-        StringBuilder builder = new StringBuilder();
-
-        // addresses is backed by an ArrayList, so use a hand-written iterator for performance gains
-        for (int i = 0; i < addresses.size(); i++) {
-            if (i > 0) builder.append(", ");
-            builder.append(addresses.get(i).getHostAddress());
+        if (!TextUtils.isEmpty(subnet)) {
+            mSubnetPref.setDetailText(subnet);
+            mSubnetPref.setVisible(true);
         }
-        mDnsPref.setDetailText(builder.toString());
+
+        if (!TextUtils.isEmpty(gateway)) {
+            mGatewayPref.setDetailText(gateway);
+            mGatewayPref.setVisible(true);
+        }
+
+        // Set IPv4 DNS addresses
+        StringJoiner stringJoiner = new StringJoiner(",");
+        for (InetAddress dnsServer : linkProperties.getDnsServers()) {
+            if (dnsServer instanceof Inet4Address) {
+                stringJoiner.add(dnsServer.getHostAddress());
+            }
+        }
+        String dnsText = stringJoiner.toString();
+        if (!dnsText.isEmpty()) {
+            mDnsPref.setDetailText(dnsText);
+            mDnsPref.setVisible(true);
+        }
+    }
+
+    private static String ipv4PrefixLengthToSubnetMask(int prefixLength) {
+        try {
+            InetAddress all = InetAddress.getByAddress(
+                    new byte[]{(byte) 255, (byte) 255, (byte) 255, (byte) 255});
+            return NetworkUtils.getNetworkPart(all, prefixLength).getHostAddress();
+        } catch (UnknownHostException e) {
+            return null;
+        }
     }
 
     /**
diff --git a/src/com/android/settings/wifi/details/WifiNetworkDetailsFragment.java b/src/com/android/settings/wifi/details/WifiNetworkDetailsFragment.java
index 7ebde38..ebd1143 100644
--- a/src/com/android/settings/wifi/details/WifiNetworkDetailsFragment.java
+++ b/src/com/android/settings/wifi/details/WifiNetworkDetailsFragment.java
@@ -16,6 +16,7 @@
 package com.android.settings.wifi.details;
 
 import android.content.Context;
+import android.net.ConnectivityManager;
 import android.net.wifi.WifiManager;
 import android.os.Bundle;
 import android.widget.Button;
@@ -45,13 +46,10 @@
     private AccessPoint mAccessPoint;
     private Button mForgetButton;
     private WifiDetailPreferenceController mWifiDetailPreferenceController;
-    private WifiManager mWifiManager;
 
     @Override
     public void onAttach(Context context) {
         mAccessPoint = new AccessPoint(context, getArguments());
-        mWifiManager = context.getSystemService(WifiManager.class);
-
         super.onAttach(context);
     }
 
@@ -95,7 +93,8 @@
                 mAccessPoint,
                 context,
                 getLifecycle(),
-                mWifiManager);
+                context.getSystemService(WifiManager.class),
+                context.getSystemService(ConnectivityManager.class));
 
         ArrayList<PreferenceController> controllers = new ArrayList(1);
         controllers.add(mWifiDetailPreferenceController);
diff --git a/tests/app/src/com/android/settings/applications/ExternalSourcesSettingsTest.java b/tests/app/src/com/android/settings/applications/ExternalSourcesSettingsTest.java
index 9114c6f..82f0e0a 100644
--- a/tests/app/src/com/android/settings/applications/ExternalSourcesSettingsTest.java
+++ b/tests/app/src/com/android/settings/applications/ExternalSourcesSettingsTest.java
@@ -93,7 +93,7 @@
 
     private Intent createManageExternalSourcesListIntent() {
         final Intent manageExternalSourcesIntent = new Intent();
-        manageExternalSourcesIntent.setAction(Settings.ACTION_MANAGE_EXTERNAL_SOURCES);
+        manageExternalSourcesIntent.setAction(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
         return manageExternalSourcesIntent;
     }
 
diff --git a/tests/app/src/com/android/settings/bluetooth/DevicePickerActivityTest.java b/tests/app/src/com/android/settings/bluetooth/DevicePickerActivityTest.java
new file mode 100644
index 0000000..1b855c9
--- /dev/null
+++ b/tests/app/src/com/android/settings/bluetooth/DevicePickerActivityTest.java
@@ -0,0 +1,46 @@
+/*
+ * 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.bluetooth;
+
+import android.app.Instrumentation;
+import android.content.Intent;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class DevicePickerActivityTest {
+
+    private Instrumentation mInstrumentation;
+
+    @Before
+    public void setUp() throws Exception {
+        mInstrumentation = InstrumentationRegistry.getInstrumentation();
+    }
+
+    @Test
+    public void startActivityNoCrash() {
+        mInstrumentation.startActivitySync(
+                new Intent("android.bluetooth.devicepicker.action.LAUNCH"));
+        // No crash
+    }
+}
diff --git a/tests/app/src/com/android/settings/fuelgauge/PowerUsageSummaryUiTest.java b/tests/app/src/com/android/settings/fuelgauge/PowerUsageSummaryUiTest.java
index 47e644a..6c372c5 100644
--- a/tests/app/src/com/android/settings/fuelgauge/PowerUsageSummaryUiTest.java
+++ b/tests/app/src/com/android/settings/fuelgauge/PowerUsageSummaryUiTest.java
@@ -16,26 +16,11 @@
 
 package com.android.settings.fuelgauge;
 
-import static android.support.test.InstrumentationRegistry.getTargetContext;
-import static android.support.test.espresso.Espresso.onData;
 import static android.support.test.espresso.Espresso.onView;
 import static android.support.test.espresso.action.ViewActions.click;
-import static android.support.test.espresso.intent.Intents.intended;
-import static android.support.test.espresso.intent.Intents.intending;
-import static android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent;
-import static android.support.test.espresso.matcher.PreferenceMatchers.withKey;
-import static android.support.test.espresso.matcher.ViewMatchers.isDescendantOfA;
-import static android.support.test.espresso.matcher.ViewMatchers.withId;
 import static android.support.test.espresso.matcher.ViewMatchers.withText;
 
-import static org.hamcrest.Matchers.allOf;
-import static org.hamcrest.core.IsAnything.anything;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import android.app.Activity;
 import android.app.Instrumentation;
-import android.content.Context;
 import android.content.Intent;
 import android.support.test.InstrumentationRegistry;
 import android.support.test.filters.SmallTest;
diff --git a/tests/robotests/src/android/util/LauncherIcons.java b/tests/robotests/src/android/util/LauncherIcons.java
new file mode 100644
index 0000000..a18cfae
--- /dev/null
+++ b/tests/robotests/src/android/util/LauncherIcons.java
@@ -0,0 +1,32 @@
+/*
+ * 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 android.util;
+
+import android.content.Context;
+import android.graphics.drawable.Drawable;
+
+/**
+ * This class is only needed to get around RoboElectric issue.
+ */
+public final class LauncherIcons {
+
+    public LauncherIcons(Context context) {
+    }
+
+    public Drawable wrapIconDrawableWithShadow(Drawable drawable) {
+        return drawable;
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/TetherServiceTest.java b/tests/robotests/src/com/android/settings/TetherServiceTest.java
new file mode 100644
index 0000000..2d5a2fb
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/TetherServiceTest.java
@@ -0,0 +1,87 @@
+/*
+ * 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;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+import android.content.Context;
+import android.content.Intent;
+import android.net.wifi.WifiManager;
+import java.util.ArrayList;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.annotation.Config;
+import org.robolectric.shadows.ShadowApplication;
+import org.robolectric.util.ReflectionHelpers;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class TetherServiceTest {
+
+    @Mock
+    private Context mContext;
+
+    private ShadowApplication mShadowApplication;
+    private Context mAppContext;
+    private TetherService mService;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mShadowApplication = ShadowApplication.getInstance();
+        mAppContext = mShadowApplication.getApplicationContext();
+        mService = new TetherService();
+        ReflectionHelpers.setField(mService, "mBase", mAppContext);
+        mService.setHotspotOffReceiver(new HotspotOffReceiver(mContext));
+    }
+
+    @Test
+    public void scheduleAlarm_shouldRegisterReceiver() {
+        mService.setHotspotOffReceiver(new HotspotOffReceiver(mAppContext));
+
+        mService.scheduleAlarm();
+
+        assertThat(mShadowApplication.hasReceiverForIntent(
+            new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION))).isTrue();
+    }
+
+    @Test
+    public void cancelAlarmIfNecessary_hasActiveTethers_shouldNotUnregisterReceiver() {
+        mService.scheduleAlarm();
+        final ArrayList<Integer> tethers = new ArrayList<>();
+        tethers.add(1);
+        ReflectionHelpers.setField(mService, "mCurrentTethers", tethers);
+
+        mService.cancelAlarmIfNecessary();
+        verify(mContext, never()).unregisterReceiver(any(HotspotOffReceiver.class));
+    }
+
+    @Test
+    public void cancelAlarmIfNecessary_noActiveTethers_shouldUnregisterReceiver() {
+        final ArrayList<Integer> tethers = new ArrayList<>();
+        ReflectionHelpers.setField(mService, "mCurrentTethers", tethers);
+        mService.scheduleAlarm();
+
+        mService.cancelAlarmIfNecessary();
+        verify(mContext).unregisterReceiver(any(HotspotOffReceiver.class));
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/applications/AppStorageSizesControllerTest.java b/tests/robotests/src/com/android/settings/applications/AppStorageSizesControllerTest.java
index 7204bd1..127100f 100644
--- a/tests/robotests/src/com/android/settings/applications/AppStorageSizesControllerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/AppStorageSizesControllerTest.java
@@ -92,4 +92,22 @@
         assertThat(mDataPreference.getSummary()).isEqualTo("100B");
         assertThat(mTotalPreference.getSummary()).isEqualTo("111B");
     }
+
+    @Test
+    public void fakeCacheFlagSetsCacheToZero() {
+        AppStorageStats result = mock(AppStorageStats.class);
+        when(result.getCodeBytes()).thenReturn(1L);
+        when(result.getCacheBytes()).thenReturn(10L);
+        when(result.getDataBytes()).thenReturn(100L);
+        when(result.getTotalBytes()).thenReturn(111L);
+
+        mController.setResult(result);
+        mController.setCacheCleared(true);
+        mController.updateUi(mContext);
+
+        assertThat(mAppPreference.getSummary()).isEqualTo("1.00B");
+        assertThat(mCachePreference.getSummary()).isEqualTo("0.00B");
+        assertThat(mDataPreference.getSummary()).isEqualTo("100B");
+        assertThat(mTotalPreference.getSummary()).isEqualTo("101B");
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/applications/InstalledAppDetailsTest.java b/tests/robotests/src/com/android/settings/applications/InstalledAppDetailsTest.java
index a33a8c8..5b1019e 100644
--- a/tests/robotests/src/com/android/settings/applications/InstalledAppDetailsTest.java
+++ b/tests/robotests/src/com/android/settings/applications/InstalledAppDetailsTest.java
@@ -74,7 +74,7 @@
     ApplicationFeatureProvider mApplicationFeatureProvider;
     @Mock(answer = Answers.RETURNS_DEEP_STUBS)
     private UserManager mUserManager;
-    @Mock
+    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
     private SettingsActivity mActivity;
     @Mock
     private DevicePolicyManager mDevicePolicyManager;
diff --git a/tests/robotests/src/com/android/settings/bluetooth/BluetoothDevicePreferenceTest.java b/tests/robotests/src/com/android/settings/bluetooth/BluetoothDevicePreferenceTest.java
index 5915118..c4c1f8a 100644
--- a/tests/robotests/src/com/android/settings/bluetooth/BluetoothDevicePreferenceTest.java
+++ b/tests/robotests/src/com/android/settings/bluetooth/BluetoothDevicePreferenceTest.java
@@ -17,8 +17,10 @@
 
 import android.bluetooth.BluetoothDevice;
 import android.content.Context;
+import android.os.UserManager;
 
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.settings.R;
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
 import com.android.settings.core.instrumentation.MetricsFeatureProvider;
@@ -32,7 +34,10 @@
 import org.mockito.MockitoAnnotations;
 import org.robolectric.RuntimeEnvironment;
 import org.robolectric.annotation.Config;
+import org.robolectric.util.ReflectionHelpers;
 
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -66,7 +71,7 @@
         mPreference.onClicked();
 
         verify(mMetricsFeatureProvider).action(
-            mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_DISCONNECT);
+                mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_DISCONNECT);
     }
 
     @Test
@@ -77,7 +82,7 @@
         mPreference.onClicked();
 
         verify(mMetricsFeatureProvider).action(
-            mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_CONNECT);
+                mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_CONNECT);
     }
 
     @Test
@@ -89,6 +94,46 @@
         mPreference.onClicked();
 
         verify(mMetricsFeatureProvider).action(
-            mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_PAIR);
+                mContext, MetricsEvent.ACTION_SETTINGS_BLUETOOTH_PAIR);
+    }
+
+    @Test
+    public void getSecondTargetResource_shouldBeGearIconLayout() {
+        assertThat(mPreference.getSecondTargetResId()).isEqualTo(R.layout.preference_widget_gear);
+    }
+
+    @Test
+    public void shouldHideSecondTarget_noDevice_shouldReturnTrue() {
+        ReflectionHelpers.setField(mPreference, "mCachedDevice", null);
+
+        assertThat(mPreference.shouldHideSecondTarget()).isTrue();
+    }
+
+    @Test
+    public void shouldHideSecondTarget_notBond_shouldReturnTrue() {
+        when(mCachedBluetoothDevice.getBondState()).thenReturn(BluetoothDevice.BOND_NONE);
+
+        assertThat(mPreference.shouldHideSecondTarget()).isTrue();
+    }
+
+    @Test
+    public void shouldHideSecondTarget_hasUserRestriction_shouldReturnTrue() {
+        final UserManager um = mock(UserManager.class);
+        ReflectionHelpers.setField(mPreference, "mUserManager", um);
+        when(um.hasUserRestriction(UserManager.DISALLOW_CONFIG_BLUETOOTH))
+                .thenReturn(true);
+
+        assertThat(mPreference.shouldHideSecondTarget()).isTrue();
+    }
+
+    @Test
+    public void shouldHideSecondTarget_hasBoundDeviceAndNoRestriction_shouldReturnFalse() {
+        when(mCachedBluetoothDevice.getBondState()).thenReturn(BluetoothDevice.BOND_BONDED);
+        final UserManager um = mock(UserManager.class);
+        ReflectionHelpers.setField(mPreference, "mUserManager", um);
+        when(um.hasUserRestriction(UserManager.DISALLOW_CONFIG_BLUETOOTH))
+                .thenReturn(false);
+
+        assertThat(mPreference.shouldHideSecondTarget()).isFalse();
     }
 }
diff --git a/tests/robotests/src/com/android/settings/deviceinfo/storage/SecondaryUserControllerTest.java b/tests/robotests/src/com/android/settings/deviceinfo/storage/SecondaryUserControllerTest.java
index 16bf1ae..c55ba36 100644
--- a/tests/robotests/src/com/android/settings/deviceinfo/storage/SecondaryUserControllerTest.java
+++ b/tests/robotests/src/com/android/settings/deviceinfo/storage/SecondaryUserControllerTest.java
@@ -19,12 +19,14 @@
 import static com.google.common.truth.Truth.assertThat;
 
 import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import android.content.Context;
 import android.content.pm.UserInfo;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.drawable.Drawable;
 import android.support.v7.preference.Preference;
 import android.support.v7.preference.PreferenceGroup;
 import android.support.v7.preference.PreferenceScreen;
@@ -34,7 +36,9 @@
 import com.android.settings.TestConfig;
 import com.android.settings.applications.UserManagerWrapper;
 import com.android.settings.core.PreferenceController;
+import com.android.settingslib.R;
 import com.android.settingslib.applications.StorageStatsSource;
+import com.android.settingslib.drawable.UserIconDrawable;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -187,4 +191,24 @@
         // We should have the NoSecondaryUserController.
         assertThat(controllers.get(0) instanceof SecondaryUserController).isFalse();
     }
+
+    @Test
+    public void iconCallbackChangesPreferenceIcon() throws Exception {
+        SparseArray<Drawable> icons = new SparseArray<>();
+        Bitmap userBitmap =
+                BitmapFactory.decodeResource(
+                        RuntimeEnvironment.application.getResources(), R.drawable.home);
+        UserIconDrawable drawable = new UserIconDrawable(100 /* size */).setIcon(userBitmap).bake();
+        icons.put(10, drawable);
+        mPrimaryUser.name = TEST_NAME;
+        mPrimaryUser.id = 10;
+        mController.displayPreference(mScreen);
+
+        mController.handleUserIcons(icons);
+
+        final ArgumentCaptor<Preference> argumentCaptor = ArgumentCaptor.forClass(Preference.class);
+        verify(mGroup).addPreference(argumentCaptor.capture());
+        Preference preference = argumentCaptor.getValue();
+        assertThat(preference.getIcon()).isEqualTo(drawable);
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/deviceinfo/storage/UserProfileControllerTest.java b/tests/robotests/src/com/android/settings/deviceinfo/storage/UserProfileControllerTest.java
index ed49da4..0c3fc47 100644
--- a/tests/robotests/src/com/android/settings/deviceinfo/storage/UserProfileControllerTest.java
+++ b/tests/robotests/src/com/android/settings/deviceinfo/storage/UserProfileControllerTest.java
@@ -18,7 +18,6 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
-import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -26,6 +25,9 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.UserInfo;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.drawable.Drawable;
 import android.support.v7.preference.Preference;
 import android.support.v7.preference.PreferenceScreen;
 import android.util.SparseArray;
@@ -36,7 +38,9 @@
 import com.android.settings.TestConfig;
 import com.android.settings.applications.UserManagerWrapper;
 import com.android.settings.deviceinfo.StorageProfileFragment;
+import com.android.settingslib.R;
 import com.android.settingslib.applications.StorageStatsSource;
+import com.android.settingslib.drawable.UserIconDrawable;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -66,16 +70,15 @@
         MockitoAnnotations.initMocks(this);
         mContext = spy(RuntimeEnvironment.application);
         mPrimaryProfile = new UserInfo();
-        mController = new UserProfileController(mContext, mPrimaryProfile, 0);
+        mController = new UserProfileController(mContext, mPrimaryProfile, mUserManager, 0);
         when(mScreen.getContext()).thenReturn(mContext);
+        mPrimaryProfile.name = TEST_NAME;
+        mPrimaryProfile.id = 10;
+        mController.displayPreference(mScreen);
     }
 
     @Test
     public void controllerAddsPrimaryProfilePreference() throws Exception {
-        mPrimaryProfile.name = TEST_NAME;
-        mPrimaryProfile.id = 10;
-        mController.displayPreference(mScreen);
-
         final ArgumentCaptor<Preference> argumentCaptor = ArgumentCaptor.forClass(Preference.class);
         verify(mScreen).addPreference(argumentCaptor.capture());
         Preference preference = argumentCaptor.getValue();
@@ -86,9 +89,6 @@
 
     @Test
     public void tappingProfilePreferenceSendsToStorageProfileFragment() throws Exception {
-        mPrimaryProfile.name = TEST_NAME;
-        mPrimaryProfile.id = 10;
-        mController.displayPreference(mScreen);
 
         final ArgumentCaptor<Preference> argumentCaptor = ArgumentCaptor.forClass(Preference.class);
         verify(mScreen).addPreference(argumentCaptor.capture());
@@ -105,9 +105,6 @@
 
     @Test
     public void acceptingResultUpdatesPreferenceSize() throws Exception {
-        mPrimaryProfile.name = TEST_NAME;
-        mPrimaryProfile.id = 10;
-        mController.displayPreference(mScreen);
         SparseArray<StorageAsyncLoader.AppsStorageResult> result = new SparseArray<>();
         StorageAsyncLoader.AppsStorageResult userResult =
                 new StorageAsyncLoader.AppsStorageResult();
@@ -121,4 +118,21 @@
 
         assertThat(preference.getSummary()).isEqualTo("99.00B");
     }
+
+    @Test
+    public void iconCallbackChangesPreferenceIcon() throws Exception {
+        SparseArray<Drawable> icons = new SparseArray<>();
+        Bitmap userBitmap =
+                BitmapFactory.decodeResource(
+                        RuntimeEnvironment.application.getResources(), R.drawable.home);
+        UserIconDrawable drawable = new UserIconDrawable(100 /* size */).setIcon(userBitmap).bake();
+        icons.put(10, drawable);
+
+        mController.handleUserIcons(icons);
+
+        final ArgumentCaptor<Preference> argumentCaptor = ArgumentCaptor.forClass(Preference.class);
+        verify(mScreen).addPreference(argumentCaptor.capture());
+        Preference preference = argumentCaptor.getValue();
+        assertThat(preference.getIcon()).isEqualTo(drawable);
+    }
 }
\ No newline at end of file
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetailTest.java b/tests/robotests/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetailTest.java
index 8b5ce19..03892a3 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetailTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetailTest.java
@@ -21,6 +21,7 @@
 import android.app.Fragment;
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
 import android.graphics.drawable.Drawable;
 import android.os.BatteryStats;
 import android.os.Bundle;
@@ -96,7 +97,8 @@
     private BatteryStatsHelper mBatteryStatsHelper;
     @Mock
     private BatteryStats.Uid mUid;
-    private Bundle mTestBundle;
+    @Mock
+    private PackageManager mPackageManager;
     private AdvancedPowerUsageDetail mFragment;
     private FakeFeatureFactory mFeatureFactory;
     private SettingsActivity mTestActivity;
@@ -141,6 +143,7 @@
         mAppEntry.info = mock(ApplicationInfo.class);
 
         mTestActivity = spy(new SettingsActivity());
+        doReturn(mPackageManager).when(mTestActivity).getPackageManager();
 
         final ArgumentCaptor<Bundle> captor = ArgumentCaptor.forClass(Bundle.class);
 
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/BatteryUtilsTest.java b/tests/robotests/src/com/android/settings/fuelgauge/BatteryUtilsTest.java
index 672cc90..3699147 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/BatteryUtilsTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/BatteryUtilsTest.java
@@ -25,6 +25,7 @@
 import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
 import org.robolectric.annotation.Config;
 
 import static android.os.BatteryStats.Uid.PROCESS_STATE_BACKGROUND;
@@ -56,7 +57,8 @@
     private static final long TIME_EXPECTED_ALL = 15000;
 
     @Mock
-    BatteryStats.Uid mUid;
+    private BatteryStats.Uid mUid;
+    private BatteryUtils mBatteryUtils;
 
     @Before
     public void setUp() {
@@ -72,11 +74,13 @@
                 anyLong(), anyInt());
         doReturn(TIME_STATE_BACKGROUND).when(mUid).getProcessStateTime(eq(PROCESS_STATE_BACKGROUND),
                 anyLong(), anyInt());
+
+        mBatteryUtils = BatteryUtils.getInstance(RuntimeEnvironment.application);
     }
 
     @Test
     public void testGetProcessTimeMs_typeForeground_timeCorrect() {
-        final long time = BatteryUtils.getProcessTimeMs(BatteryUtils.StatusType.FOREGROUND, mUid,
+        final long time = mBatteryUtils.getProcessTimeMs(BatteryUtils.StatusType.FOREGROUND, mUid,
                 BatteryStats.STATS_SINCE_CHARGED);
 
         assertThat(time).isEqualTo(TIME_EXPECTED_FOREGROUND);
@@ -84,7 +88,7 @@
 
     @Test
     public void testGetProcessTimeMs_typeBackground_timeCorrect() {
-        final long time = BatteryUtils.getProcessTimeMs(BatteryUtils.StatusType.BACKGROUND, mUid,
+        final long time = mBatteryUtils.getProcessTimeMs(BatteryUtils.StatusType.BACKGROUND, mUid,
                 BatteryStats.STATS_SINCE_CHARGED);
 
         assertThat(time).isEqualTo(TIME_EXPECTED_BACKGROUND);
@@ -92,7 +96,7 @@
 
     @Test
     public void testGetProcessTimeMs_typeAll_timeCorrect() {
-        final long time = BatteryUtils.getProcessTimeMs(BatteryUtils.StatusType.ALL, mUid,
+        final long time = mBatteryUtils.getProcessTimeMs(BatteryUtils.StatusType.ALL, mUid,
                 BatteryStats.STATS_SINCE_CHARGED);
 
         assertThat(time).isEqualTo(TIME_EXPECTED_ALL);
@@ -100,7 +104,7 @@
 
     @Test
     public void testGetProcessTimeMs_uidNull_returnZero() {
-        final long time = BatteryUtils.getProcessTimeMs(BatteryUtils.StatusType.ALL, null,
+        final long time = mBatteryUtils.getProcessTimeMs(BatteryUtils.StatusType.ALL, null,
                 BatteryStats.STATS_SINCE_CHARGED);
 
         assertThat(time).isEqualTo(0);
diff --git a/tests/robotests/src/com/android/settings/search2/DatabaseIndexingManagerTest.java b/tests/robotests/src/com/android/settings/search2/DatabaseIndexingManagerTest.java
index 327b910..aa4e4f9 100644
--- a/tests/robotests/src/com/android/settings/search2/DatabaseIndexingManagerTest.java
+++ b/tests/robotests/src/com/android/settings/search2/DatabaseIndexingManagerTest.java
@@ -30,6 +30,8 @@
 import android.database.MatrixCursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.net.Uri;
+import android.os.Build;
+import android.provider.SearchIndexableData;
 import android.provider.SearchIndexableResource;
 import android.provider.SearchIndexablesContract;
 import android.util.ArrayMap;
@@ -74,7 +76,7 @@
 
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION,
-        shadows={ShadowRunnableAsyncTask.class})
+        shadows = {ShadowRunnableAsyncTask.class})
 public class DatabaseIndexingManagerTest {
     private final String localeStr = "en_US";
 
@@ -122,7 +124,7 @@
     public void setUp() {
         MockitoAnnotations.initMocks(this);
         mContext = spy(RuntimeEnvironment.application);
-        mManager = spy(new DatabaseIndexingManager(mContext,"com.android.settings"));
+        mManager = spy(new DatabaseIndexingManager(mContext, PACKAGE_ONE));
         mDb = IndexDatabaseHelper.getInstance(mContext).getWritableDatabase();
 
         doReturn(mPackageManager).when(mContext).getPackageManager();
@@ -671,42 +673,95 @@
     // Test new public indexing flow
 
     @Test
-    @Config(shadows= {
-            ShadowDatabaseIndexingUtils.class,
-    })
+    @Config(shadows = {ShadowDatabaseIndexingUtils.class,})
     public void testPerformIndexing_fullIndex_getsDataFromProviders() {
         DummyProvider provider = new DummyProvider();
         provider.onCreate();
-        ShadowContentResolver.registerProvider(
-                AUTHORITY_ONE, provider
-        );
+        ShadowContentResolver.registerProvider(AUTHORITY_ONE, provider);
 
         // Test that Indexables are added for Full indexing
         when(mPackageManager.queryIntentContentProviders(any(Intent.class), anyInt()))
                 .thenReturn(getDummyResolveInfo());
 
         DatabaseIndexingManager manager =
-                spy(new DatabaseIndexingManager(mContext, "com.android.settings"));
-        doReturn(false).when(manager).isLocaleIndexed();
+                spy(new DatabaseIndexingManager(mContext, PACKAGE_ONE));
+        doReturn(true).when(manager).isFullIndex(anyString(), anyString());
 
         manager.performIndexing();
 
-        verify(manager).updateDatabase(false, Locale.getDefault().toString());
-
-        Cursor cursor = mDb.rawQuery("SELECT * FROM prefs_index", null);
-        cursor.moveToPosition(0);
-
-        // Data Title
-        assertThat(cursor.getString(2)).isEqualTo(TITLE_ONE);
+        verify(manager).addIndexablesFromRemoteProvider(PACKAGE_ONE, AUTHORITY_ONE);
+        verify(manager).updateDatabase(true /* isFullIndex */, Locale.getDefault().toString());
     }
 
     @Test
-    @Config(shadows= {
-            ShadowDatabaseIndexingUtils.class,
-    })
+    @Config(shadows = {ShadowDatabaseIndexingUtils.class,})
     public void testPerformIndexing_incrementalIndex_noDataAdded() {
         DummyProvider provider = new DummyProvider();
         provider.onCreate();
+        ShadowContentResolver.registerProvider(AUTHORITY_ONE, provider);
+
+        // Test that Indexables are added for Full indexing
+        when(mPackageManager.queryIntentContentProviders(any(Intent.class), anyInt()))
+                .thenReturn(getDummyResolveInfo());
+
+        DatabaseIndexingManager manager =
+                spy(new DatabaseIndexingManager(mContext, PACKAGE_ONE));
+        doReturn(false).when(manager).isFullIndex(anyString(), anyString());
+
+        manager.mDataToProcess.dataToUpdate.clear();
+
+        manager.performIndexing();
+
+        verify(manager, times(0)).addDataToDatabase(any(SQLiteDatabase.class), anyString(),
+                anyList(), anyMap());
+        verify(manager, times(0)).addIndexablesFromRemoteProvider(PACKAGE_ONE, AUTHORITY_ONE);
+        verify(manager).updateDataInDatabase(any(SQLiteDatabase.class), anyMap());
+    }
+
+    @Test
+    @Config(shadows = {ShadowDatabaseIndexingUtils.class,})
+    public void testPerformIndexing_localeChanged_databaseDropped() {
+        DummyProvider provider = new DummyProvider();
+        provider.onCreate();
+        ShadowContentResolver.registerProvider(AUTHORITY_ONE, provider);
+
+        // Test that Indexables are added for Full indexing
+        when(mPackageManager.queryIntentContentProviders(any(Intent.class), anyInt()))
+                .thenReturn(getDummyResolveInfo());
+
+        // Initialize the Manager
+        DatabaseIndexingManager manager =
+                spy(new DatabaseIndexingManager(mContext, PACKAGE_ONE));
+        doReturn(true).when(manager).isFullIndex(anyString(), anyString());
+
+        // Insert data point which will be dropped
+        final String oldTitle = "This is French";
+        insertSpecialCase(oldTitle, true, "key");
+
+        // Add a data point to be added by the indexing
+        SearchIndexableRaw raw = new SearchIndexableRaw(mContext);
+        final String newTitle = "This is English";
+        raw.title = newTitle;
+        manager.mDataToProcess.dataToUpdate.add(raw);
+
+        manager.performIndexing();
+
+        // Assert that the New Title is inserted
+        final Cursor newCursor = mDb.rawQuery("SELECT * FROM prefs_index WHERE data_title = '" +
+                newTitle + "'", null);
+        assertThat(newCursor.getCount()).isEqualTo(1);
+
+        // Assert that the Old Title is no longer in the database, since it was dropped
+        final Cursor oldCursor = mDb.rawQuery("SELECT * FROM prefs_index WHERE data_title = '" +
+                oldTitle + "'", null);
+        assertThat(oldCursor.getCount()).isEqualTo(0);
+    }
+
+    @Test
+    @Config(shadows = {ShadowDatabaseIndexingUtils.class,})
+    public void testPerformIndexing_onOta_FullIndex() {
+        DummyProvider provider = new DummyProvider();
+        provider.onCreate();
         ShadowContentResolver.registerProvider(
                 AUTHORITY_ONE, provider
         );
@@ -716,19 +771,40 @@
                 .thenReturn(getDummyResolveInfo());
 
         DatabaseIndexingManager manager =
-                spy(new DatabaseIndexingManager(mContext, "com.android.settings"));
-        doReturn(true).when(manager).isLocaleIndexed();
+                spy(new DatabaseIndexingManager(mContext, PACKAGE_ONE));
+        doReturn(true).when(manager).isFullIndex(anyString(), anyString());
 
         manager.performIndexing();
 
-        final Cursor cursor = mDb.rawQuery("SELECT * FROM prefs_index", null);
+        verify(manager).updateDatabase(true /* isFullIndex */, Locale.getDefault().toString());
+    }
 
-        assertThat(cursor.getCount()).isEqualTo(0);
+    @Test
+    @Config(shadows = {ShadowDatabaseIndexingUtils.class,})
+    public void testPerformIndexing_onOta_buildNumberIsCached() {
+        DummyProvider provider = new DummyProvider();
+        provider.onCreate();
+        ShadowContentResolver.registerProvider(
+                AUTHORITY_ONE, provider
+        );
+
+        // Test that Indexables are added for Full indexing
+        when(mPackageManager.queryIntentContentProviders(any(Intent.class), anyInt()))
+                .thenReturn(getDummyResolveInfo());
+
+        DatabaseIndexingManager manager =
+                spy(new DatabaseIndexingManager(mContext, PACKAGE_ONE));
+        doReturn(true).when(manager).isFullIndex(anyString(), anyString());
+
+        manager.performIndexing();
+
+        assertThat(IndexDatabaseHelper.getInstance(mContext).isBuildIndexed(mContext,
+                Build.FINGERPRINT)).isTrue();
     }
 
     @Test
     public void testFullUpdatedDatabase_noData_addDataToDatabaseNotCalled() {
-        mManager.updateDatabase(false, localeStr);
+        mManager.updateDatabase(true /* isFullIndex */, localeStr);
         mManager.mDataToProcess.dataToUpdate.clear();
         verify(mManager, times(0)).addDataToDatabase(any(SQLiteDatabase.class), anyString(),
                 anyList(), anyMap());
@@ -736,13 +812,13 @@
 
     @Test
     public void testFullUpdatedDatabase_updatedDataInDatabaseNotCalled() {
-        mManager.updateDatabase(false, localeStr);
+        mManager.updateDatabase(true /* isFullIndex */, localeStr);
         verify(mManager, times(0)).updateDataInDatabase(any(SQLiteDatabase.class), anyMap());
     }
 
     @Test
     public void testLocaleUpdated_afterIndexing_localeNotAdded() {
-        mManager.updateDatabase(false, localeStr);
+        mManager.updateDatabase(true /* isFullIndex */, localeStr);
         assertThat(IndexDatabaseHelper.getInstance(mContext)
                 .isLocaleAlreadyIndexed(mContext, localeStr)).isFalse();
     }
@@ -758,7 +834,7 @@
     public void testUpdateDatabase_newEligibleData_addedToDatabase() {
         // Test that addDataToDatabase is called when dataToUpdate is non-empty
         mManager.mDataToProcess.dataToUpdate.add(getFakeRaw());
-        mManager.updateDatabase(false, localeStr);
+        mManager.updateDatabase(true /* isFullIndex */, localeStr);
 
         Cursor cursor = mDb.rawQuery("SELECT * FROM prefs_index", null);
         cursor.moveToPosition(0);
diff --git a/tests/robotests/src/com/android/settings/suggestions/SettingsSuggestionsTest.java b/tests/robotests/src/com/android/settings/suggestions/SettingsSuggestionsTest.java
index 3780d35..ad035bd 100644
--- a/tests/robotests/src/com/android/settings/suggestions/SettingsSuggestionsTest.java
+++ b/tests/robotests/src/com/android/settings/suggestions/SettingsSuggestionsTest.java
@@ -54,12 +54,6 @@
   }
 
   @Test
-  public void nightDisplaySettings_isValid() {
-    assertSuggestionEquals("Settings$NightDisplaySettingsActivity",
-        R.string.night_display_suggestion_title, R.string.night_display_suggestion_summary);
-  }
-
-  @Test
   public void fingerprintSuggestion_isValid() {
     assertSuggestionEquals("com.android.settings.Settings$FingerprintSuggestionActivity",
         R.string.suggestion_additional_fingerprints,
diff --git a/tests/robotests/src/com/android/settings/vpn2/AppDialogFragmentTest.java b/tests/robotests/src/com/android/settings/vpn2/AppDialogFragmentTest.java
new file mode 100644
index 0000000..088bfae
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/vpn2/AppDialogFragmentTest.java
@@ -0,0 +1,65 @@
+/*
+ * 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.vpn2;
+
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+import android.app.Fragment;
+import android.content.pm.PackageInfo;
+
+import com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.TestConfig;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.annotation.Config;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class AppDialogFragmentTest {
+
+    @Mock
+    private Fragment mParent;
+
+    private PackageInfo mPackageInfo;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mPackageInfo = new PackageInfo();
+    }
+
+    @Test
+    public void notManagingOrConnected_shouldNotShow() {
+        AppDialogFragment.show(mParent, mPackageInfo, "label", false /* manage */,
+                false /* connected */);
+
+        verify(mParent, never()).isAdded();
+    }
+
+    @Test
+    public void notManagingAndConnected_showShow() {
+        AppDialogFragment.show(mParent, mPackageInfo, "label", false /* manage */,
+                true /* connected */);
+
+        verify(mParent).isAdded();
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/wifi/details/WifiDetailPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/wifi/details/WifiDetailPreferenceControllerTest.java
index f60c106..7cb69ea 100644
--- a/tests/robotests/src/com/android/settings/wifi/details/WifiDetailPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/wifi/details/WifiDetailPreferenceControllerTest.java
@@ -18,14 +18,22 @@
 import static com.google.common.truth.Truth.assertThat;
 
 import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import android.content.Context;
 import android.graphics.drawable.Drawable;
+import android.net.ConnectivityManager;
+import android.net.IpPrefix;
+import android.net.LinkAddress;
+import android.net.LinkProperties;
+import android.net.Network;
 import android.net.NetworkBadging;
 import android.net.NetworkInfo;
+import android.net.RouteInfo;
 import android.net.wifi.WifiConfiguration;
 import android.net.wifi.WifiInfo;
 import android.net.wifi.WifiManager;
@@ -46,8 +54,14 @@
 import org.mockito.Answers;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
+import org.robolectric.annotation.Config;
 import org.robolectric.RuntimeEnvironment;
 import org.robolectric.annotation.Config;
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
 
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
@@ -56,28 +70,35 @@
     private static final int LEVEL = 1;
     private static final int RSSI = -55;
     private static final int LINK_SPEED = 123;
+    private static final String MAC_ADDRESS = WifiInfo.DEFAULT_MAC_ADDRESS;
     private static final String SECURITY = "None";
 
+    private InetAddress mIpv4Address;
+
     @Mock(answer = Answers.RETURNS_DEEP_STUBS)
     private PreferenceScreen mockScreen;
 
     @Mock private AccessPoint mockAccessPoint;
     @Mock private WifiManager mockWifiManager;
+    @Mock private ConnectivityManager mockConnectivityManager;
     @Mock private NetworkInfo mockNetworkInfo;
     @Mock private WifiConfiguration mockWifiConfig;
     @Mock private WifiInfo mockWifiInfo;
+    @Mock private Network mockNetwork;
 
     @Mock private Preference mockConnectionDetailPref;
     @Mock private WifiDetailPreference mockSignalStrengthPref;
     @Mock private WifiDetailPreference mockLinkSpeedPref;
     @Mock private WifiDetailPreference mockFrequencyPref;
     @Mock private WifiDetailPreference mockSecurityPref;
+    @Mock private WifiDetailPreference mockMacAddressPref;
     @Mock private WifiDetailPreference mockIpAddressPref;
-    @Mock private WifiDetailPreference mockRouterPref;
+    @Mock private WifiDetailPreference mockGatewayPref;
     @Mock private WifiDetailPreference mockSubnetPref;
     @Mock private WifiDetailPreference mockDnsPref;
     @Mock private PreferenceCategory mockIpv6AddressCategory;
 
+    private LinkProperties mLinkProperties;
     private Context mContext = RuntimeEnvironment.application;
     private Lifecycle mLifecycle;
     private WifiDetailPreferenceController mController;
@@ -88,6 +109,13 @@
 
         mLifecycle = new Lifecycle();
 
+        try {
+            mIpv4Address = InetAddress.getByAddress(
+                    new byte[] { (byte) 255, (byte) 255, (byte) 255, (byte) 255 });
+        } catch (UnknownHostException e) {
+            throw new RuntimeException(e);
+        }
+
         when(mockAccessPoint.getConfig()).thenReturn(mockWifiConfig);
         when(mockAccessPoint.getLevel()).thenReturn(LEVEL);
         when(mockAccessPoint.getNetworkInfo()).thenReturn(mockNetworkInfo);
@@ -96,16 +124,20 @@
 
         when(mockWifiInfo.getLinkSpeed()).thenReturn(LINK_SPEED);
         when(mockWifiInfo.getRssi()).thenReturn(RSSI);
+        when(mockWifiInfo.getMacAddress()).thenReturn(MAC_ADDRESS);
         when(mockWifiManager.getConnectionInfo()).thenReturn(mockWifiInfo);
 
+        when(mockWifiManager.getCurrentNetwork()).thenReturn(mockNetwork);
+        mLinkProperties = new LinkProperties();
+        when(mockConnectivityManager.getLinkProperties(mockNetwork)).thenReturn(mLinkProperties);
+
         mController = new WifiDetailPreferenceController(
-                mockAccessPoint, mContext, mLifecycle, mockWifiManager);
+                mockAccessPoint, mContext, mLifecycle, mockWifiManager, mockConnectivityManager);
 
         setupMockedPreferenceScreen();
     }
 
     private void setupMockedPreferenceScreen() {
-
         when(mockScreen.findPreference(WifiDetailPreferenceController.KEY_CONNECTION_DETAIL_PREF))
                 .thenReturn(mockConnectionDetailPref);
         when(mockScreen.findPreference(WifiDetailPreferenceController.KEY_SIGNAL_STRENGTH_PREF))
@@ -116,10 +148,12 @@
                 .thenReturn(mockFrequencyPref);
         when(mockScreen.findPreference(WifiDetailPreferenceController.KEY_SECURITY_PREF))
                 .thenReturn(mockSecurityPref);
+        when(mockScreen.findPreference(WifiDetailPreferenceController.KEY_MAC_ADDRESS_PREF))
+                .thenReturn(mockMacAddressPref);
         when(mockScreen.findPreference(WifiDetailPreferenceController.KEY_IP_ADDRESS_PREF))
                 .thenReturn(mockIpAddressPref);
-        when(mockScreen.findPreference(WifiDetailPreferenceController.KEY_ROUTER_PREF))
-                .thenReturn(mockRouterPref);
+        when(mockScreen.findPreference(WifiDetailPreferenceController.KEY_GATEWAY_PREF))
+                .thenReturn(mockGatewayPref);
         when(mockScreen.findPreference(WifiDetailPreferenceController.KEY_SUBNET_MASK_PREF))
                 .thenReturn(mockSubnetPref);
         when(mockScreen.findPreference(WifiDetailPreferenceController.KEY_DNS_PREF))
@@ -195,11 +229,101 @@
     }
 
     @Test
+    public void linkSpeedPref_shouldNotShowIfNotSet() {
+        when(mockWifiInfo.getLinkSpeed()).thenReturn(-1);
+
+        mController.onResume();
+
+        verify(mockLinkSpeedPref).setVisible(false);
+    }
+
+    @Test
+    public void macAddressPref_shouldHaveDetailTextSet() {
+        mController.onResume();
+
+        verify(mockMacAddressPref).setDetailText(MAC_ADDRESS);
+    }
+
+    @Test
+    public void ipAddressPref_shouldHaveDetailTextSet() {
+        LinkAddress ipv4Address = new LinkAddress(mIpv4Address, 32);
+
+        mLinkProperties.addLinkAddress(ipv4Address);
+
+        mController.onResume();
+
+        verify(mockIpAddressPref).setDetailText(mIpv4Address.getHostAddress());
+    }
+
+    @Test
+    public void gatewayAndSubnet_shouldHaveDetailTextSet() {
+        int prefixLength = 24;
+        IpPrefix subnet = new IpPrefix(mIpv4Address, prefixLength);
+        InetAddress gateway = mIpv4Address;
+        mLinkProperties.addRoute(new RouteInfo(subnet, gateway));
+
+        mController.onResume();
+
+        verify(mockSubnetPref).setDetailText("255.255.255.0");
+        verify(mockGatewayPref).setDetailText(mIpv4Address.getHostAddress());
+    }
+
+    @Test
+    public void dnsServersPref_shouldHaveDetailTextSet() throws UnknownHostException {
+        mLinkProperties.addDnsServer(InetAddress.getByAddress(new byte[]{8,8,4,4}));
+        mLinkProperties.addDnsServer(InetAddress.getByAddress(new byte[]{8,8,8,8}));
+
+        mController.onResume();
+
+        verify(mockDnsPref).setDetailText("8.8.4.4,8.8.8.8");
+    }
+
+    @Test
+    public void noCurrentNetwork_allIpDetailsHidden() {
+        when(mockWifiManager.getCurrentNetwork()).thenReturn(null);
+        reset(mockIpv6AddressCategory, mockIpAddressPref, mockSubnetPref, mockGatewayPref,
+                mockDnsPref);
+
+        mController.onResume();
+
+        verify(mockIpv6AddressCategory).setVisible(false);
+        verify(mockIpAddressPref).setVisible(false);
+        verify(mockSubnetPref).setVisible(false);
+        verify(mockGatewayPref).setVisible(false);
+        verify(mockDnsPref).setVisible(false);
+        verify(mockIpv6AddressCategory, never()).setVisible(true);
+        verify(mockIpAddressPref, never()).setVisible(true);
+        verify(mockSubnetPref, never()).setVisible(true);
+        verify(mockGatewayPref, never()).setVisible(true);
+        verify(mockDnsPref, never()).setVisible(true);
+    }
+
+    @Test
+    public void noLinkProperties_allIpDetailsHidden() {
+        when(mockConnectivityManager.getLinkProperties(mockNetwork)).thenReturn(null);
+        reset(mockIpv6AddressCategory, mockIpAddressPref, mockSubnetPref, mockGatewayPref,
+                mockDnsPref);
+
+        mController.onResume();
+
+        verify(mockIpv6AddressCategory).setVisible(false);
+        verify(mockIpAddressPref).setVisible(false);
+        verify(mockSubnetPref).setVisible(false);
+        verify(mockGatewayPref).setVisible(false);
+        verify(mockDnsPref).setVisible(false);
+        verify(mockIpv6AddressCategory, never()).setVisible(true);
+        verify(mockIpAddressPref, never()).setVisible(true);
+        verify(mockSubnetPref, never()).setVisible(true);
+        verify(mockGatewayPref, never()).setVisible(true);
+        verify(mockDnsPref, never()).setVisible(true);
+    }
+
+    @Test
     public void canForgetNetwork_noNetwork() {
         when(mockAccessPoint.getConfig()).thenReturn(null);
 
         mController = new WifiDetailPreferenceController(
-                mockAccessPoint, mContext, mLifecycle, mockWifiManager);
+                mockAccessPoint, mContext, mLifecycle, mockWifiManager, mockConnectivityManager);
 
         assertThat(mController.canForgetNetwork()).isFalse();
     }
@@ -210,7 +334,7 @@
         when(mockAccessPoint.getConfig()).thenReturn(null);
 
         mController = new WifiDetailPreferenceController(
-                mockAccessPoint, mContext, mLifecycle, mockWifiManager);
+                mockAccessPoint, mContext, mLifecycle, mockWifiManager, mockConnectivityManager);
 
         assertThat(mController.canForgetNetwork()).isTrue();
     }