Merge "Add related assist-gesture keywords"
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index e09b4b1..7dd42df 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -82,6 +82,7 @@
     <uses-permission android:name="android.permission.PEERS_MAC_ADDRESS"/>
     <uses-permission android:name="android.permission.MANAGE_NOTIFICATIONS"/>
     <uses-permission android:name="android.permission.DELETE_PACKAGES"/>
+    <uses-permission android:name="android.permission.MANAGE_APP_OPS_RESTRICTIONS"/>
 
     <application android:label="@string/settings_label"
             android:icon="@drawable/ic_launcher_settings"
@@ -1498,6 +1499,7 @@
             android:theme="@android:style/Theme.NoDisplay">
             <intent-filter android:priority="1">
                 <action android:name="android.app.action.CONFIRM_DEVICE_CREDENTIAL" />
+                <action android:name="android.app.action.CONFIRM_FRP_CREDENTIAL" />
                 <category android:name="android.intent.category.DEFAULT" />
             </intent-filter>
         </activity>
@@ -2530,8 +2532,6 @@
             </intent-filter>
             <meta-data android:name="com.android.settings.category"
                 android:value="com.android.settings.category.ia.apps"/>
-            <meta-data android:name="com.android.settings.summary"
-                android:resource="@string/summary_empty"/>
             <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
                 android:value="com.android.settings.notification.ConfigureNotificationSettings" />
             <meta-data android:name="com.android.settings.PRIMARY_PROFILE_CONTROLLED"
diff --git a/res/drawable/ic_password.xml b/res/drawable/ic_password.xml
new file mode 100644
index 0000000..57591c2
--- /dev/null
+++ b/res/drawable/ic_password.xml
@@ -0,0 +1,34 @@
+<!--
+    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.
+-->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportHeight="24.0"
+    android:viewportWidth="24.0">
+    <path
+        android:fillColor="?attr/suwListItemIconColor"
+        android:pathData="M21.5,9.39l-1.63,0l0.81,-1.42l-0.86,-0.5l-0.82,1.42l-0.82,-1.42l-0.86,0.5l0.81,1.42l-1.63,0l0,1l1.63,0l-0.81,1.41l0.86,0.5l0.82,-1.41l0.82,1.41l0.86,-0.5l-0.81,-1.41l1.63,0z" />
+    <path
+        android:fillColor="?attr/suwListItemIconColor"
+        android:pathData="M13.68,7.97l-0.86,-0.5l-0.82,1.42l-0.82,-1.42l-0.86,0.5l0.81,1.42l-1.63,0l0,1l1.63,0l-0.81,1.41l0.86,0.5l0.82,-1.41l0.82,1.41l0.86,-0.5l-0.81,-1.41l1.63,0l0,-1l-1.63,0z" />
+    <path
+        android:fillColor="?attr/suwListItemIconColor"
+        android:pathData="M6.68,7.97l-0.86,-0.5l-0.82,1.42l-0.82,-1.42l-0.86,0.5l0.81,1.42l-1.63,0l0,1l1.63,0l-0.81,1.41l0.86,0.5l0.82,-1.41l0.82,1.41l0.86,-0.5l-0.81,-1.41l1.63,0l0,-1l-1.63,0z" />
+    <path
+        android:fillColor="?attr/suwListItemIconColor"
+        android:pathData="M21,17.89H3c-0.28,0 -0.5,-0.22 -0.5,-0.5v-1c0,-0.28 0.22,-0.5 0.5,-0.5h18c0.28,0 0.5,0.22 0.5,0.5v1C21.5,17.66 21.28,17.89 21,17.89z" />
+</vector>
diff --git a/res/drawable/ic_pattern.xml b/res/drawable/ic_pattern.xml
new file mode 100644
index 0000000..003111e
--- /dev/null
+++ b/res/drawable/ic_pattern.xml
@@ -0,0 +1,37 @@
+<!--
+    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.
+-->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportHeight="24.0"
+    android:viewportWidth="24.0">
+    <path
+        android:fillColor="?attr/suwListItemIconColor"
+        android:pathData="M4,4m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0" />
+    <path
+        android:fillColor="?attr/suwListItemIconColor"
+        android:pathData="M4,12m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0" />
+    <path
+        android:fillColor="?attr/suwListItemIconColor"
+        android:pathData="M12,4m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0" />
+    <path
+        android:fillColor="?attr/suwListItemIconColor"
+        android:pathData="M20,12m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0" />
+    <path
+        android:fillColor="?attr/suwListItemIconColor"
+        android:pathData="M20,18c-0.93,0 -1.7,0.64 -1.93,1.5h-4.14c-0.22,-0.86 -1,-1.5 -1.93,-1.5s-1.7,0.64 -1.93,1.5H5.93c-0.05,-0.18 -0.12,-0.35 -0.21,-0.51l5.28,-5.28C11.29,13.89 11.63,14 12,14c1.1,0 2,-0.9 2,-2c0,-0.37 -0.11,-0.71 -0.28,-1.01l5.28,-5.28C19.29,5.89 19.63,6 20,6c1.1,0 2,-0.9 2,-2s-0.9,-2 -2,-2s-2,0.9 -2,2c0,0.37 0.11,0.71 0.28,1.01l-5.28,5.28C12.71,10.11 12.37,10 12,10c-1.1,0 -2,0.9 -2,2c0,0.37 0.11,0.71 0.28,1.01l-5.28,5.28C4.71,18.11 4.37,18 4,18c-1.1,0 -2,0.9 -2,2s0.9,2 2,2c0.93,0 1.7,-0.64 1.93,-1.5h4.14c0.22,0.86 1,1.5 1.93,1.5s1.7,-0.64 1.93,-1.5h4.14c0.22,0.86 1,1.5 1.93,1.5c1.1,0 2,-0.9 2,-2S21.1,18 20,18z" />
+</vector>
diff --git a/res/drawable/ic_pin.xml b/res/drawable/ic_pin.xml
new file mode 100644
index 0000000..0176019
--- /dev/null
+++ b/res/drawable/ic_pin.xml
@@ -0,0 +1,25 @@
+<!--
+    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.
+-->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+    android:width="24dp"
+    android:height="24dp"
+    android:viewportHeight="24.0"
+    android:viewportWidth="24.0">
+    <path
+        android:fillColor="?attr/suwListItemIconColor"
+        android:pathData="M20,4L4,4A2,2 0,0 0,2 6L2,18a2,2 0,0 0,2 2L20,20a2,2 0,0 0,2 -2L22,6A2,2 0,0 0,20 4ZM7.1,15L5.9,15L5.9,10.2L4.7,10.2L4.7,9L7.1,9v6ZM13.2,11.4A1.2,1.2 0,0 1,12 12.6L10.8,12.6v1.2h2.4L13.2,15L9.6,15L9.6,12.6a1.2,1.2 0,0 1,1.2 -1.2L12,11.4L12,10.2L9.6,10.2L9.6,9L12,9a1.2,1.2 0,0 1,1.2 1.2v1.2ZM19.3,11.1a0.9,0.9 0,0 1,-0.9 0.9,0.9 0.9,0 0,1 0.9,0.9v0.9A1.2,1.2 0,0 1,18.1 15L15.7,15L15.7,13.8h2.4L18.1,12.6L16.9,12.6L16.9,11.4h1.2L18.1,10.2L15.7,10.2L15.7,9h2.4a1.2,1.2 0,0 1,1.2 1.2v0.9Z" />
+</vector>
diff --git a/res/layout-land/fingerprint_enroll_finish.xml b/res/layout-land/fingerprint_enroll_finish.xml
index ca1a2d2..b9e2a64 100644
--- a/res/layout-land/fingerprint_enroll_finish.xml
+++ b/res/layout-land/fingerprint_enroll_finish.xml
@@ -20,6 +20,7 @@
     android:id="@+id/setup_wizard_layout"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
+    android:layout="@layout/suw_glif_blank_template"
     style="?attr/fingerprint_layout_theme">
 
     <LinearLayout
@@ -28,18 +29,34 @@
         android:layout_height="match_parent"
         android:orientation="horizontal"
         android:clipToPadding="false"
-        android:clipChildren="false"
-        android:paddingBottom="0dp">
+        android:clipChildren="false">
 
         <LinearLayout
             android:layout_width="0dp"
             android:layout_weight="1"
-            android:layout_height="wrap_content"
-            android:layout_gravity="center_vertical"
+            android:layout_height="match_parent"
             android:clipChildren="false"
             android:clipToPadding="false"
             android:orientation="vertical">
 
+            <ImageView
+                android:id="@+id/suw_layout_icon"
+                style="@style/SuwGlifIcon"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_marginLeft="0dp"
+                android:layout_marginRight="0dp"
+                android:contentDescription="@null"
+                android:src="@drawable/ic_fingerprint_header"/>
+
+            <TextView
+                android:id="@+id/suw_layout_title"
+                style="@style/SuwGlifHeaderTitle"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:layout_marginLeft="0dp"
+                android:layout_marginRight="0dp"/>
+
             <TextView
                 android:id="@+id/message"
                 style="@style/SuwDescription.Glif"
@@ -57,6 +74,11 @@
                 android:textColor="?android:attr/textColorSecondary"
                 android:visibility="gone" />
 
+            <Space
+                android:layout_width="0dp"
+                android:layout_height="0dp"
+                android:layout_weight="1" />
+
             <LinearLayout
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
@@ -89,21 +111,20 @@
 
         </LinearLayout>
 
-        <FrameLayout
+        <com.android.setupwizardlib.view.FillContentLayout
             android:layout_width="0dp"
             android:layout_weight="1"
-            android:layout_height="wrap_content"
-            android:layout_gravity="center_vertical">
+            android:layout_height="match_parent">
 
             <ImageView
                 android:id="@+id/fingerprint_in_app_indicator"
-                android:layout_width="@dimen/fingerprint_in_app_indicator_size"
-                android:layout_height="@dimen/fingerprint_in_app_indicator_size"
-                android:layout_gravity="center_horizontal"
+                style="@style/SuwContentIllustration"
+                android:layout_width="match_parent"
+                android:layout_height="match_parent"
                 android:contentDescription="@android:string/fingerprint_icon_content_description"
                 android:src="@drawable/fp_app_indicator" />
 
-        </FrameLayout>
+        </com.android.setupwizardlib.view.FillContentLayout>
 
     </LinearLayout>
 
diff --git a/res/layout/account_type_preference.xml b/res/layout/account_type_preference.xml
deleted file mode 100644
index f7ba859..0000000
--- a/res/layout/account_type_preference.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2014 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.
--->
-
-<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
-        android:id="@+id/accountTypeIcon"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center"
-        android:contentDescription="@null" />
diff --git a/res/layout/app_domains_dialog.xml b/res/layout/app_domains_dialog.xml
index f9c6b64..d006027 100644
--- a/res/layout/app_domains_dialog.xml
+++ b/res/layout/app_domains_dialog.xml
@@ -15,18 +15,12 @@
      limitations under the License.
 -->
 
-<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
-             android:layout_width="match_parent"
-             android:layout_height="match_parent"
-             android:paddingStart="24dp"
-             android:paddingTop="16dp"
-             android:paddingEnd="24dp">
+<ListView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@android:id/list"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:divider="@null"
+    android:scrollbarStyle="insideOverlay"
+    android:padding="24dp" />
 
-    <ListView
-            android:id="@android:id/list"
-            android:layout_width="match_parent"
-            android:layout_height="match_parent"
-            android:divider="@null"
-            android:scrollbarStyle="insideOverlay" />
-
-</FrameLayout>
diff --git a/res/layout/app_domains_item.xml b/res/layout/app_domains_item.xml
index e2ccbd3..5aa9cfa 100644
--- a/res/layout/app_domains_item.xml
+++ b/res/layout/app_domains_item.xml
@@ -15,12 +15,12 @@
      limitations under the License.
 -->
 
-<TextView xmlns:android="http://schemas.android.com/apk/res/android"
+<TextView
+    xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/domain_name"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:paddingStart="4dp"
     android:paddingEnd="4dp"
-    android:paddingTop="16dp"
-    android:divider="@null"
-    />
+    android:paddingTop="8dp"
+    android:paddingBottom="8dp" />
diff --git a/res/layout/choose_lock_dialog_item.xml b/res/layout/choose_lock_dialog_item.xml
new file mode 100644
index 0000000..8e78f99
--- /dev/null
+++ b/res/layout/choose_lock_dialog_item.xml
@@ -0,0 +1,29 @@
+<?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.
+-->
+
+<TextView xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@android:id/text1"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:drawablePadding="24dp"
+    android:ellipsize="marquee"
+    android:gravity="center_vertical"
+    android:minHeight="?android:attr/listPreferredItemHeight"
+    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
+    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
+    android:textAppearance="@android:style/TextAppearance.Material.Subhead"
+    android:textColor="?android:attr/textColorAlertDialogListItem" />
diff --git a/res/layout/choose_lock_password.xml b/res/layout/choose_lock_password.xml
index 988f331..02912ee 100644
--- a/res/layout/choose_lock_password.xml
+++ b/res/layout/choose_lock_password.xml
@@ -32,20 +32,11 @@
         android:gravity="center_horizontal"
         android:orientation="vertical">
 
-        <!-- header text ('Enter Pin') -->
-        <TextView
-            android:id="@+id/headerText"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:accessibilityLiveRegion="polite"
-            android:gravity="center"
-            android:lines="2"
-            android:textAppearance="?android:attr/textAppearanceMedium"/>
-
         <LinearLayout
             android:id="@+id/password_container"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
+            android:layout_marginTop="16dp"
             android:clipChildren="false"
             android:clipToPadding="false"
             android:orientation="vertical"
diff --git a/res/layout/fingerprint_enroll_finish_base.xml b/res/layout/fingerprint_enroll_finish_base.xml
index bdecd72..f0bd882 100644
--- a/res/layout/fingerprint_enroll_finish_base.xml
+++ b/res/layout/fingerprint_enroll_finish_base.xml
@@ -50,29 +50,20 @@
             android:textColor="?android:attr/textColorSecondary"
             android:visibility="gone" />
 
-        <View
-            android:layout_height="24dp"
+        <com.android.setupwizardlib.view.FillContentLayout
             android:layout_width="match_parent"
-            android:layout_weight="1"/>
-
-        <ImageView
-            android:id="@+id/fingerprint_in_app_indicator"
             android:layout_height="0dp"
-            android:layout_width="wrap_content"
-            android:layout_weight="5"
-            android:adjustViewBounds="true"
-            android:minHeight="@dimen/fingerprint_in_app_indicator_min_size"
-            android:minWidth="@dimen/fingerprint_in_app_indicator_min_size"
-            android:maxHeight="@dimen/fingerprint_in_app_indicator_max_size"
-            android:maxWidth="@dimen/fingerprint_in_app_indicator_max_size"
-            android:layout_gravity="center_horizontal"
-            android:contentDescription="@android:string/fingerprint_icon_content_description"
-            android:src="@drawable/fp_app_indicator" />
+            android:layout_weight="1">
 
-        <View
-            android:layout_height="24dp"
-            android:layout_width="match_parent"
-            android:layout_weight="1"/>
+            <ImageView
+                android:id="@+id/fingerprint_in_app_indicator"
+                style="@style/SuwContentIllustration"
+                android:layout_width="match_parent"
+                android:layout_height="match_parent"
+                android:contentDescription="@android:string/fingerprint_icon_content_description"
+                android:src="@drawable/fp_app_indicator" />
+
+        </com.android.setupwizardlib.view.FillContentLayout>
 
     </LinearLayout>
 
diff --git a/res/layout/preference_small_icon.xml b/res/layout/preference_small_icon.xml
new file mode 100644
index 0000000..a9f4c2f
--- /dev/null
+++ b/res/layout/preference_small_icon.xml
@@ -0,0 +1,82 @@
+<?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.
+  -->
+
+<!-- Same as preference_material except that it uses a 24dp fixed size icon -->
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+              xmlns:app="http://schemas.android.com/apk/res-auto"
+              android:layout_width="match_parent"
+              android:layout_height="wrap_content"
+              android:minHeight="?android:attr/listPreferredItemHeightSmall"
+              android:gravity="center_vertical"
+              android:paddingStart="?android:attr/listPreferredItemPaddingStart"
+              android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
+              android:background="?android:attr/selectableItemBackground"
+              android:clipToPadding="false"
+              android:focusable="true" >
+
+    <LinearLayout
+        android:id="@android:id/icon_frame"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:minWidth="56dp"
+        android:gravity="start|center_vertical"
+        android:orientation="horizontal"
+        android:paddingEnd="12dp"
+        android:paddingTop="4dp"
+        android:paddingBottom="4dp">
+        <android.support.v7.internal.widget.PreferenceImageView
+            android:id="@android:id/icon"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            app:maxWidth="24dp"
+            app:maxHeight="24dp" />
+    </LinearLayout>
+
+    <RelativeLayout
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_weight="1"
+        android:paddingTop="16dp"
+        android:paddingBottom="16dp">
+
+        <TextView android:id="@android:id/title"
+                  android:layout_width="wrap_content"
+                  android:layout_height="wrap_content"
+                  android:singleLine="true"
+                  android:textAppearance="?android:attr/textAppearanceListItem"
+                  android:ellipsize="marquee" />
+
+        <TextView android:id="@android:id/summary"
+                  android:layout_width="wrap_content"
+                  android:layout_height="wrap_content"
+                  android:layout_below="@android:id/title"
+                  android:layout_alignStart="@android:id/title"
+                  android:textAppearance="?android:attr/textAppearanceListItemSecondary"
+                  android:textColor="?android:attr/textColorSecondary"
+                  android:maxLines="10" />
+
+    </RelativeLayout>
+
+    <!-- Preference should place its actual preference widget here. -->
+    <LinearLayout android:id="@android:id/widget_frame"
+                  android:layout_width="wrap_content"
+                  android:layout_height="match_parent"
+                  android:gravity="end|center_vertical"
+                  android:paddingStart="16dp"
+                  android:orientation="vertical" />
+
+</LinearLayout>
\ No newline at end of file
diff --git a/res/layout/preference_widget_seekbar_settings.xml b/res/layout/preference_widget_seekbar_settings.xml
index 87fea99..c25c598 100644
--- a/res/layout/preference_widget_seekbar_settings.xml
+++ b/res/layout/preference_widget_seekbar_settings.xml
@@ -19,36 +19,36 @@
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
-    android:minHeight="?android:attr/listPreferredItemHeight"
+    android:layout_marginTop="6dp"
+    android:layout_marginBottom="6dp"
     android:gravity="center_vertical"
+    android:minHeight="?android:attr/listPreferredItemHeight"
     android:paddingStart="?android:attr/listPreferredItemPaddingStart"
-    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
-    android:paddingBottom="6dp"
-    android:paddingTop="6dp">
+    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd">
 
     <TextView
         android:id="@android:id/title"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:layout_marginStart="60dp"
-        android:layout_marginEnd="8dp"
+        android:ellipsize="marquee"
+        android:fadingEdge="horizontal"
+        android:paddingStart="56dp"
+        android:paddingEnd="8dp"
         android:singleLine="true"
         android:textAppearance="@android:style/TextAppearance.Material.Subhead"
-        android:textColor="?android:attr/textColorPrimary"
-        android:ellipsize="marquee"
-        android:fadingEdge="horizontal" />
+        android:textColor="?android:attr/textColorPrimary" />
 
     <TextView
         android:id="@android:id/summary"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:layout_marginStart="60dp"
-        android:layout_marginEnd="8dp"
-        android:layout_below="@android:id/title"
         android:layout_alignStart="@android:id/title"
+        android:layout_below="@android:id/title"
+        android:maxLines="4"
+        android:paddingStart="56dp"
+        android:paddingEnd="8dp"
         android:textAppearance="?android:attr/textAppearanceListItemSecondary"
-        android:textColor="?android:attr/textColorSecondary"
-        android:maxLines="4" />
+        android:textColor="?android:attr/textColorSecondary" />
 
     <com.android.settings.widget.DefaultIndicatorSeekBar
         android:id="@*android:id/seekbar"
@@ -57,7 +57,7 @@
         android:layout_height="48dp"
         android:layout_alignParentEnd="true"
         android:layout_below="@android:id/summary"
-        android:layout_marginEnd="8dp"
-        android:layout_marginStart="44dp" />
+        android:paddingStart="56dp"
+        android:paddingEnd="8dp" />
 
 </RelativeLayout>
diff --git a/res/layout/wifi_network_details_two_buttons_panel.xml b/res/layout/wifi_network_details_two_buttons_panel.xml
new file mode 100644
index 0000000..6abfac3
--- /dev/null
+++ b/res/layout/wifi_network_details_two_buttons_panel.xml
@@ -0,0 +1,50 @@
+<?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.
+-->
+
+<!--
+  Defines a panel with two buttons and a spacer in between.
+  The right button uses the Material.Button.Colored style.
+-->
+
+<LinearLayout
+        xmlns:android="http://schemas.android.com/apk/res/android"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:gravity="bottom"
+        android:paddingTop="4dip"
+        android:orientation="horizontal">
+        <Button
+            android:id="@+id/forget_button"
+            android:layout_width="120dip"
+            android:layout_weight="0.4"
+            android:layout_height="wrap_content"
+            android:layout_gravity="center_vertical"/>
+        <!-- Spacer -->
+        <View
+            android:id="@+id/buttons_spacer_left"
+            android:layout_width="0dip"
+            android:layout_height="wrap_content"
+            android:visibility="invisible"
+            android:layout_weight="0.2" />
+        <Button
+            style="@android:style/Widget.Material.Button.Colored"
+            android:id="@+id/signin_button"
+            android:layout_width="120dip"
+            android:text="@string/cancel"
+            android:layout_weight="0.4"
+            android:layout_height="wrap_content"
+            android:layout_gravity="center_vertical"/>
+</LinearLayout>
diff --git a/res/values-sw400dp/dimens.xml b/res/values-sw400dp/dimens.xml
index 7ae4061..0c35d84 100755
--- a/res/values-sw400dp/dimens.xml
+++ b/res/values-sw400dp/dimens.xml
@@ -17,7 +17,6 @@
 
 <resources>
     <dimen name="fingerprint_enrolling_content_margin_top">56dp</dimen>
-    <dimen name="fingerprint_in_app_indicator_size">176dp</dimen>
     <dimen name="fingerprint_find_sensor_graphic_size">240dp</dimen>
 
     <dimen name="support_escalation_card_padding_start">56dp</dimen>
diff --git a/res/values/attrs.xml b/res/values/attrs.xml
index 9f87d03..5e7ee7e 100644
--- a/res/values/attrs.xml
+++ b/res/values/attrs.xml
@@ -94,6 +94,10 @@
 
     <attr name="footerPreferenceStyle" format="reference" />
 
+    <declare-styleable name="FixedLineSummaryPreference">
+        <attr name="summaryLineCount" format="integer" />
+    </declare-styleable>
+
     <!-- For Search -->
     <declare-styleable name="Preference">
         <attr name="keywords" format="string" />
@@ -155,7 +159,7 @@
     </declare-styleable>
 
     <declare-styleable name="TintablePreference">
-        <attr name="android:tint" format="color|reference"/>
+        <attr name="android:tint" format="color|reference" />
     </declare-styleable>
 
 </resources>
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index 5c6796c..592b30a 100755
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -222,9 +222,6 @@
     <dimen name="fingerprint_progress_bar_max_size">220dp</dimen>
     <dimen name="fingerprint_progress_bar_min_size">120dp</dimen>
     <dimen name="fingerprint_enrolling_content_margin_top">36dp</dimen>
-    <dimen name="fingerprint_in_app_indicator_size">124dp</dimen>
-    <dimen name="fingerprint_in_app_indicator_min_size">124dp</dimen>
-    <dimen name="fingerprint_in_app_indicator_max_size">264dp</dimen>
 
     <dimen name="confirm_credentials_security_method_margin">48dp</dimen>
     <dimen name="confirm_credentials_layout_width">@dimen/match_parent</dimen>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 6b99663..1b6ec19 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -1099,6 +1099,9 @@
     <!-- Label for button in screen lock settings, allowing users to choose other types of screen locks. [CHAR LIMIT=40] -->
     <string name="setup_lock_settings_options_button_label">Screen lock options</string>
 
+    <!-- Title for dialog in screen lock settings, allowing users to choose other types of screen locks. [CHAR LIMIT=40] -->
+    <string name="setup_lock_settings_options_dialog_title">Screen lock options</string>
+
     <!--  Main Security lock settings --><skip />
     <!--  Title for PreferenceScreen to launch picker for security method when there is none [CHAR LIMIT=22] -->
     <string name="unlock_set_unlock_launch_picker_title">Screen lock</string>
@@ -1240,20 +1243,38 @@
     <!-- Title shown on security settings to allow the user to change their lockscreen password [CHAR LIMIT=22]-->
     <string name="unlock_change_lock_password_title">Change unlock password</string>
 
-    <!-- Message shown when the user incorrectly enters their lock and it counts towards the max attempts before wiping the work profile. -->
-    <string name="lock_profile_wipe_attempts">Try again. Attempt <xliff:g id="current_attempts">%1$d</xliff:g> of <xliff:g id="total_attempts">%2$d</xliff:g>.</string>
-    <!-- Title of a dialog shown when the user only has one attempt left to provide the lock before the work profile is wiped. -->
-    <string name="lock_profile_wipe_warning_title">Last try</string>
-    <!-- Content of the dialog shown when the user only has one attempt left to provide the work pattern before the work profile is wiped. -->
-    <string name="lock_profile_wipe_warning_content_pattern">If you enter an incorrect work pattern on this attempt, your work profile and associated data will be removed from this device.</string>
-    <!-- Content of the dialog shown when the user only has one attempt left to provide the work PIN before the work profile is wiped. -->
-    <string name="lock_profile_wipe_warning_content_pin">If you enter an incorrect work PIN on this attempt, your work profile and associated data will be removed from this device.</string>
-    <!-- Content of the dialog shown when the user only has one attempt left to provide the work password before the work profile is wiped. -->
-    <string name="lock_profile_wipe_warning_content_password">If you enter an incorrect work password on this attempt, your work profile and associated data will be removed from this device.</string>
-    <!-- Content of the dialog shown when the user has failed to provide the work lock too many times and the work profile is wiped. -->
-    <string name="lock_profile_wipe_content">Too many incorrect attempts. Your work profile and associated data will be removed from this device.</string>
+    <!-- Message shown on the lock screen when the user incorrectly enters their lock and it counts towards the max attempts before their data on the device is wiped. [CHAR LIMIT=NONE] -->
+    <string name="lock_failed_attempts_before_wipe">Try again. Attempt <xliff:g id="current_attempts">%1$d</xliff:g> of <xliff:g id="total_attempts">%2$d</xliff:g>.</string>
+
+    <!-- Title of a dialog shown when the user only has one attempt left to provide the lock before the device, one of its users, or a work profile is wiped. [CHAR LIMIT=NONE] -->
+    <string name="lock_last_attempt_before_wipe_warning_title">Your data will be deleted</string>
+    <!-- Content of the dialog shown when the user only has one attempt left to provide the device lock pattern before the device is wiped. [CHAR LIMIT=NONE] -->
+    <string name="lock_last_pattern_attempt_before_wipe_device">If you enter an incorrect pattern on the next attempt, this device's data will be deleted</string>
+    <!-- Content of the dialog shown when the user only has one attempt left to provide the device lock PIN before the device is wiped. [CHAR LIMIT=NONE] -->
+    <string name="lock_last_pin_attempt_before_wipe_device">If you enter an incorrect PIN on the next attempt, this device's data will be deleted</string>
+    <!-- Content of the dialog shown when the user only has one attempt left to provide the device lock password before the device is wiped. [CHAR LIMIT=NONE] -->
+    <string name="lock_last_password_attempt_before_wipe_device">If you enter an incorrect password on the next attempt, this device's data will be deleted</string>
+    <!-- Content of the dialog shown when the user only has one attempt left to provide the user lock pattern before the user is removed. [CHAR LIMIT=NONE] -->
+    <string name="lock_last_pattern_attempt_before_wipe_user">If you enter an incorrect pattern on the next attempt, this user will be deleted</string>
+    <!-- Content of the dialog shown when the user only has one attempt left to provide the user lock PIN before the user is removed. [CHAR LIMIT=NONE] -->
+    <string name="lock_last_pin_attempt_before_wipe_user">If you enter an incorrect PIN on the next attempt, this user will be deleted</string>
+    <!-- Content of the dialog shown when the user only has one attempt left to provide the user lock password before the user is removed. [CHAR LIMIT=NONE] -->
+    <string name="lock_last_password_attempt_before_wipe_user">If you enter an incorrect password on the next attempt, this user will be deleted</string>
+    <!-- Content of the dialog shown when the user only has one attempt left to provide the work lock pattern before the work profile is removed. [CHAR LIMIT=NONE] -->
+    <string name="lock_last_pattern_attempt_before_wipe_profile">If you enter an incorrect pattern on the next attempt, your work profile and its data will be deleted</string>
+    <!-- Content of the dialog shown when the user only has one attempt left to provide the work lock PIN before the work profile is removed. [CHAR LIMIT=NONE] -->
+    <string name="lock_last_pin_attempt_before_wipe_profile">If you enter an incorrect PIN on the next attempt, your work profile and its data will be deleted</string>
+    <!-- Content of the dialog shown when the user only has one attempt left to provide the work lock password before the work profile is removed. [CHAR LIMIT=NONE] -->
+    <string name="lock_last_password_attempt_before_wipe_profile">If you enter an incorrect password on the next attempt, your work profile and its data will be deleted</string>
+
+    <!-- Content of the dialog shown when the user has failed to provide the device lock too many times and the device is wiped. [CHAR LIMIT=NONE] -->
+    <string name="lock_failed_attempts_now_wiping_device">Too many incorrect attempts. This device's data will be deleted.</string>
+    <!-- Content of the dialog shown when the user has failed to provide the user lock too many times and the user is removed. [CHAR LIMIT=NONE] -->
+    <string name="lock_failed_attempts_now_wiping_user">Too many incorrect attempts. This user will be deleted.</string>
+    <!-- Content of the dialog shown when the user has failed to provide the work lock too many times and the work profile is removed. [CHAR LIMIT=NONE] -->
+    <string name="lock_failed_attempts_now_wiping_profile">Too many incorrect attempts. This work profile and its data will be deleted.</string>
     <!-- Button label to dismiss the dialog telling the user the work profile has been wiped. [CHAR LIMIT=40] -->
-    <string name="lock_profile_wipe_dismiss">Dismiss</string>
+    <string name="lock_failed_attempts_now_wiping_dialog_dismiss">Dismiss</string>
 
     <!-- Hint shown in dialog screen when password is too short -->
     <string name="lockpassword_password_too_short">Must be at least <xliff:g id="count" example="3">%d</xliff:g> characters</string>
@@ -2403,9 +2424,18 @@
     <string name="automatic_brightness">Automatic brightness</string>
     <!-- [CHAR LIMIT=40] Display settings screen, setting option name to change whether the device wakes up when a lift gesture is detected. -->
     <string name="lift_to_wake_title">Lift to wake</string>
-    <!-- [CHAR LIMIT=30] Display settings screen, setting option name to change whether the ambient display feature is enabled. -->
-    <string name="doze_title">Ambient display</string>
-    <!-- [CHAR LIMIT=NONE] Display settings screen, setting description for the ambient display feature. -->
+
+    <!-- [CHAR LIMIT=30] Title of the preference that opens the Ambient display settings screen. -->
+    <string name="ambient_display_screen_title">Ambient display</string>
+    <!-- [CHAR LIMIT=30] Summary of the preference that opens the Ambient display settings screen, when Ambient display is set to be always on -->
+    <string name="ambient_display_screen_summary_always_on">Always on</string>
+    <!-- [CHAR LIMIT=30] Summary of the preference that opens the Ambient display settings screen, when Ambient display is set to show when new notifications come in. -->
+    <string name="ambient_display_screen_summary_notifications">New notifications</string>
+    <!-- [CHAR LIMIT=30] Category title for the settings that control when Ambient display shows. -->
+    <string name="ambient_display_category_triggers">When to show</string>
+    <!-- [CHAR LIMIT=30] Ambient display screen, title for setting to change whether the ambient display feature is triggered for new incoming notifications. -->
+    <string name="doze_title">New notifications</string>
+    <!-- [CHAR LIMIT=NONE] Ambient display screen, summary for setting to change whether the ambient display feature is triggered for new incoming notifications. -->
     <string name="doze_summary">Wake screen when you receive notifications</string>
     <!-- [CHAR LIMIT=30] Display settings screen, setting option name to change whether the always-on ambient display feature is enabled. -->
     <string name="doze_always_on_title">Always on</string>
@@ -3005,6 +3035,8 @@
     <string name="error_mcc_not3">MCC field must be 3 digits.</string>
     <!-- APN error dialog messages: -->
     <string name="error_mnc_not23">MNC field must be 2 or 3 digits.</string>
+    <!-- APN error dialog messages: -->
+    <string name="error_adding_apn_type">Carrier does not allow adding APNs of type %s.</string>
     <!-- The message of dialog indicated restoring default APN settings in progress -->
     <string name="restore_default_apn">Restoring default APN settings.</string>
     <!-- APNs screen menu option to reset default APN settings -->
@@ -3500,9 +3532,9 @@
     <!-- Applications settings screen, setting check box title. If checked, the system allows installation of applications that are downloaded from random places, such as web sites.  [CHAR LIMIT=30] -->
     <string name="install_applications_title">Allow all app sources</string>
     <!-- Category title listing recently used apps [CHAR_LIMIT=50]-->
-    <string name="recent_app_category_title">Recently used apps</string>
+    <string name="recent_app_category_title">Recently opened</string>
     <!-- Preference title for showing all apps on device [CHAR_LIMIT=50]-->
-    <string name="see_all_apps_title">See all apps</string>
+    <string name="see_all_apps_title">See all <xliff:g>%1$d</xliff:g> installed apps</string>
 
     <!-- Warning that appears below the unknown sources switch in settings -->
     <string name="install_all_warning" product="tablet">
@@ -4342,11 +4374,6 @@
          can't verify user consent. [CHAR LIMIT=NONE] -->
     <string name="touch_filtered_warning">Because an app is obscuring a permission request, Settings
         can’t verify your response.</string>
-    <!-- Warning shown when user input has been blocked due to another app overlaying screen
-         content. Since we don't know what the app is showing on top of the input target, we
-         can't verify user consent. [CHAR LIMIT=NONE] -->
-    <string name="window_obscured_warning">Because another app is displaying on top of these options,
-        Settings can\u2019t respond to your action.</string>
     <!-- Warning that the device data will not be encrypted with password or PIN if
         enabling an accessibility service and there is a secure lock setup. [CHAR LIMIT=NONE] -->
     <string name="enable_service_encryption_warning">If you turn on <xliff:g id="service"
@@ -6577,8 +6604,8 @@
     <!-- Configure Notifications: Work profile section header [CHAR LIMIT=30] -->
     <string name="profile_section_header">Work notifications</string>
 
-    <!-- Configure Notifications: Title for the notification badging option. [CHAR LIMIT=30] -->
-    <string name="notification_badging_title">Allow icon badges</string>
+    <!-- Configure Notifications: Title for the notification badging option. [CHAR LIMIT=30 BACKUP_MESSAGE_ID=5125022693565388760] -->
+    <string name="notification_badging_title">Allow notification dots</string>
 
     <!-- Configure Notifications: Title for the pulse notification light option. [CHAR LIMIT=30] -->
     <string name="notification_pulse_title">Blink light</string>
@@ -6807,9 +6834,6 @@
         <item quantity="other"><xliff:g id="count" example="10">%d</xliff:g> categories deleted</item>
     </plurals>
 
-    <!-- [CHAR LIMIT=45\ Global notification badge setting -->
-    <string name="notification_badges">Notification badges</string>
-
     <!-- [CHAR LIMIT=NONE] App notification settings: notifications enabled-->
     <string name="notification_toggle_on">On</string>
 
@@ -6828,8 +6852,11 @@
     <!-- [CHAR LIMIT=NONE] Channel notification settings: Block option description-->
     <string name="notification_content_block_summary">Never show notifications in the shade or on peripheral devices</string>
 
-    <!-- [CHAR LIMIT=NONE] [BACKUP_MESSAGE_ID:7166470350070693657] Channel notification settings: Badging option title -->
-    <string name="notification_badge_title">Allow icon badge</string>
+    <!-- [CHAR LIMIT=NONE BACKUP_MESSAGE_ID:7166470350070693657] App notification settings: Badging option title -->
+    <string name="notification_badge_title">Allow notification dot</string>
+
+    <!-- [CHAR LIMIT=NONE BACKUP_MESSAGE_ID:7166470350070693657] Channel notification settings: Badging option title -->
+    <string name="notification_channel_badge_title">Show notification dot</string>
 
     <!-- [CHAR LIMIT=NONE] App notification settings: Override DND option title -->
     <string name="app_notification_override_dnd_title">Override Do Not Disturb</string>
@@ -8416,7 +8443,7 @@
     <!-- Preference menu title for accessing the deletion helper from the storage manager settings. [CHAR LIMIT=30]-->
     <string name="deletion_helper_preference_title">Free up space now</string>
 
-    <!-- Preference title for gesture settings [CHAR LIMIT=25]-->
+    <!-- Preference title for gesture settings [CHAR LIMIT=40]-->
     <string name="gesture_preference_title">Gesture shortcuts</string>
 
     <!-- Preference summary for gesture settings (phone) [CHAR LIMIT=NONE]-->
@@ -8445,8 +8472,8 @@
     <!-- Title text for ambient display double tap (device) [CHAR LIMIT=60]-->
     <string name="ambient_display_title" product="device">Double-tap to check device</string>
 
-    <!-- Summary text for ambient display double tap [CHAR LIMIT=160]-->
-    <string name="ambient_display_summary">To quickly check your notifications, double-tap your screen.</string>
+    <!-- Summary text for ambient display double tap [CHAR LIMIT=NONE]-->
+    <string name="ambient_display_summary">To check time, notification icons, and other info, double-tap your screen.</string>
 
     <!-- Title text for ambient display pick up (phone) [CHAR LIMIT=60]-->
     <string name="ambient_display_pickup_title" product="default">Lift to check phone</string>
@@ -8455,12 +8482,12 @@
     <!-- Title text for ambient display pick up (device) [CHAR LIMIT=60]-->
     <string name="ambient_display_pickup_title" product="device">Lift to check device</string>
 
-    <!-- Summary text for ambient display (phone) [CHAR LIMIT=160]-->
-    <string name="ambient_display_pickup_summary" product="default">To quickly check your notifications, pick up your phone.</string>
-    <!-- Summary text for ambient display (tablet) [CHAR LIMIT=160]-->
-    <string name="ambient_display_pickup_summary" product="tablet">To quickly check your notifications, pick up your tablet.</string>
-    <!-- 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>
+    <!-- Summary text for ambient display (phone) [CHAR LIMIT=NONE]-->
+    <string name="ambient_display_pickup_summary" product="default">To check time, notification icons, and other info, pick up your phone.</string>
+    <!-- Summary text for ambient display (tablet) [CHAR LIMIT=NONE]-->
+    <string name="ambient_display_pickup_summary" product="tablet">To check time, notification icons, and other info, pick up your tablet.</string>
+    <!-- Summary text for ambient display (device) [CHAR LIMIT=NONE]-->
+    <string name="ambient_display_pickup_summary" product="device">To check time, notification icons, and other info, pick up your device.</string>
 
     <!-- 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>
@@ -8479,7 +8506,7 @@
     <string name="camera_lift_trigger_summary">To open the camera automatically, lift up your phone into a photo-taking position (landscape or portrait). Works when your phone is asleep or locked.</string>
 
     <!-- Settings suggestion summary text for opening camera when lifting the phone to a photo-taking position [CHAR LIMIT=60]-->
-    <string name="camera_lift_trigger_suggestion_summary">Take photos from lock screen</string>
+    <string name="camera_lift_trigger_suggestion_summary">Take photos when phone is asleep or locked</string>
 
     <!-- Title text for the assist gesture [CHAR LIMIT=60]-->
     <string name="assist_gesture_title">Assist gesture</string>
@@ -8752,4 +8779,10 @@
 
     <!-- Help URI, USB Audio [DO NOT TRANSLATE] -->
     <string name="help_url_audio_accessory_not_supported" translatable="false"></string>
+
+    <!-- Title label for new device suggestion, which is displayed in Settings homepage [CHAR LIMIT=100] -->
+    <string name="new_device_suggestion_title">What's new and exciting?</string>
+
+    <!-- Summary label for new device suggestion, which is displayed in Settings homepage [CHAR LIMIT=100] -->
+    <string name="new_device_suggestion_summary">Check out the top 5 features</string>
 </resources>
diff --git a/res/xml/ambient_display_settings.xml b/res/xml/ambient_display_settings.xml
new file mode 100644
index 0000000..47fed8a
--- /dev/null
+++ b/res/xml/ambient_display_settings.xml
@@ -0,0 +1,51 @@
+<?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
+        xmlns:android="http://schemas.android.com/apk/res/android"
+        android:title="@string/ambient_display_screen_title">
+
+    <PreferenceCategory
+            android:title="@string/ambient_display_category_triggers">
+
+        <SwitchPreference
+            android:key="ambient_display_always_on"
+            android:title="@string/doze_always_on_title"
+            android:summary="@string/doze_always_on_summary" />
+
+        <Preference
+            android:key="ambient_display_double_tap"
+            android:title="@string/ambient_display_title"
+            android:fragment="com.android.settings.gestures.DoubleTapScreenSettings" />
+
+        <Preference
+            android:key="ambient_display_pick_up"
+            android:title="@string/ambient_display_pickup_title"
+            android:fragment="com.android.settings.gestures.PickupGestureSettings" />
+
+    </PreferenceCategory>
+
+    <PreferenceCategory>
+
+        <SwitchPreference
+            android:key="ambient_display_notification"
+            android:title="@string/doze_title"
+            android:summary="@string/doze_summary" />
+
+    </PreferenceCategory>
+
+</PreferenceScreen>
\ No newline at end of file
diff --git a/res/xml/app_and_notification.xml b/res/xml/app_and_notification.xml
index 9ddff85..47fc378 100644
--- a/res/xml/app_and_notification.xml
+++ b/res/xml/app_and_notification.xml
@@ -30,7 +30,6 @@
         <Preference
             android:title="@string/applications_settings"
             android:key="all_app_info"
-            android:summary="@string/summary_placeholder"
             android:order="20">
             <intent
                 android:action="android.intent.action.MAIN"
diff --git a/res/xml/display_settings.xml b/res/xml/display_settings.xml
index 749b87d..11b2676 100644
--- a/res/xml/display_settings.xml
+++ b/res/xml/display_settings.xml
@@ -78,6 +78,11 @@
         android:title="@string/screensaver_settings_title"
         android:fragment="com.android.settings.dream.DreamSettings" />
 
+    <Preference
+        android:key="ambient_display"
+        android:title="@string/ambient_display_screen_title"
+        android:fragment="com.android.settings.display.AmbientDisplaySettings" />
+
     <!-- Hide night mode for now
     <ListPreference
         android:key="night_mode"
@@ -96,26 +101,6 @@
         android:key="lift_to_wake"
         android:title="@string/lift_to_wake_title" />
 
-    <Preference
-        android:key="gesture_double_tap_screen_display_summary"
-        android:title="@string/ambient_display_title"
-        android:fragment="com.android.settings.gestures.DoubleTapScreenSettings" />
-
-    <Preference
-        android:key="gesture_pick_up_display_summary"
-        android:title="@string/ambient_display_pickup_title"
-        android:fragment="com.android.settings.gestures.PickupGestureSettings" />
-
-    <SwitchPreference
-        android:key="doze"
-        android:title="@string/doze_title"
-        android:summary="@string/doze_summary" />
-
-    <SwitchPreference
-        android:key="doze_always_on"
-        android:title="@string/doze_always_on_title"
-        android:summary="@string/doze_always_on_summary" />
-
     <SwitchPreference
         android:key="tap_to_wake"
         android:title="@string/tap_to_wake"
diff --git a/res/xml/installed_app_details.xml b/res/xml/installed_app_details.xml
index 12f0442..865f41f 100644
--- a/res/xml/installed_app_details.xml
+++ b/res/xml/installed_app_details.xml
@@ -15,7 +15,9 @@
   limitations under the License.
   -->
 
-<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
+<PreferenceScreen
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:app="http://schemas.android.com/apk/res-auto">
 
     <com.android.settings.applications.LayoutPreference
         android:key="header_view"
@@ -40,11 +42,12 @@
         android:title="@string/notifications_label"
         android:selectable="true"/>
 
-    <com.android.settings.widget.SingleLineSummaryPreference
+    <com.android.settings.widget.FixedLineSummaryPreference
         android:key="permission_settings"
         android:title="@string/permissions_label"
-        android:summary="@string/summary_placeholder"
-        android:selectable="true"/>
+        android:summary="@string/summary_two_lines_placeholder"
+        android:selectable="true"
+        app:summaryLineCount="2" />
 
     <Preference
         android:key="storage_settings"
diff --git a/res/xml/location_settings.xml b/res/xml/location_settings.xml
index e063d13..77063bd 100644
--- a/res/xml/location_settings.xml
+++ b/res/xml/location_settings.xml
@@ -24,7 +24,7 @@
             android:key="location_mode"
             android:title="@string/location_mode_title"
             settings:keywords="@string/keywords_location_mode"
-            android:summary="@string/location_mode_location_off_title" />
+            android:summary="@string/summary_placeholder" />
 
         <!-- This preference category gets removed if there is no managed profile -->
         <com.android.settingslib.RestrictedSwitchPreference
diff --git a/res/xml/security_lockscreen_settings.xml b/res/xml/security_lockscreen_settings.xml
index 2a4416e..d10440e 100644
--- a/res/xml/security_lockscreen_settings.xml
+++ b/res/xml/security_lockscreen_settings.xml
@@ -15,21 +15,32 @@
 -->
 
 <PreferenceScreen
-        xmlns:android="http://schemas.android.com/apk/res/android"
-        android:title="@string/lockscreen_settings_title">
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:title="@string/lockscreen_settings_title">
+
+    <com.android.settings.notification.RestrictedDropDownPreference
+        android:key="security_setting_lock_screen_notif"
+        android:title="@string/lock_screen_notifications_title"
+        android:summary="@string/summary_placeholder" />
+
+    <com.android.settingslib.RestrictedSwitchPreference
+        android:key="add_users_when_locked"
+        android:title="@string/user_add_on_lockscreen_menu" />
+
+    <com.android.settingslib.RestrictedPreference
+        android:key="owner_info_settings"
+        android:title="@string/owner_info_settings_title"
+        android:summary="@string/owner_info_settings_summary" />
+
+    <PreferenceCategory
+        android:key="security_setting_lock_screen_notif_work_header"
+        android:title="@string/profile_section_header">
 
         <com.android.settings.notification.RestrictedDropDownPreference
-            android:key="lock_screen_notifications"
+            android:key="security_setting_lock_screen_notif_work"
             android:title="@string/lock_screen_notifications_title"
-            android:summary="@string/summary_placeholder"/>
+            android:summary="@string/summary_placeholder" />
 
-        <com.android.settingslib.RestrictedSwitchPreference
-            android:key="add_users_when_locked"
-            android:title="@string/user_add_on_lockscreen_menu"/>
-
-        <com.android.settingslib.RestrictedPreference
-            android:key="owner_info_settings"
-            android:title="@string/owner_info_settings_title"
-            android:summary="@string/owner_info_settings_summary"/>
+    </PreferenceCategory>
 
 </PreferenceScreen>
diff --git a/res/xml/upgraded_channel_notification_settings.xml b/res/xml/upgraded_channel_notification_settings.xml
index 4cf171f..7925bb7 100644
--- a/res/xml/upgraded_channel_notification_settings.xml
+++ b/res/xml/upgraded_channel_notification_settings.xml
@@ -40,7 +40,7 @@
     <!-- Show badge -->
     <com.android.settingslib.RestrictedSwitchPreference
         android:key="badge"
-        android:title="@string/notification_badge_title"
+        android:title="@string/notification_channel_badge_title"
         settings:useAdditionalSummary="true"
         settings:restrictedSwitchSummary="@string/enabled_by_admin" />
 
diff --git a/res/xml/wifi_network_details_fragment.xml b/res/xml/wifi_network_details_fragment.xml
index 5d5958d..fafbbb0 100644
--- a/res/xml/wifi_network_details_fragment.xml
+++ b/res/xml/wifi_network_details_fragment.xml
@@ -29,7 +29,7 @@
         <!-- Buttons -->
         <com.android.settings.applications.LayoutPreference
             android:key="buttons"
-            android:layout="@layout/two_buttons_panel"
+            android:layout="@layout/wifi_network_details_two_buttons_panel"
             android:selectable="false" />
 
         <com.android.settings.wifi.WifiDetailPreference
diff --git a/src/com/android/settings/ApnEditor.java b/src/com/android/settings/ApnEditor.java
index d5affa8..11d8ea2 100644
--- a/src/com/android/settings/ApnEditor.java
+++ b/src/com/android/settings/ApnEditor.java
@@ -213,6 +213,18 @@
         mReadOnlyApnTypes = null;
         mReadOnlyApnFields = null;
 
+        CarrierConfigManager configManager = (CarrierConfigManager)
+                getSystemService(Context.CARRIER_CONFIG_SERVICE);
+        if (configManager != null) {
+            PersistableBundle b = configManager.getConfig();
+            if (b != null) {
+                mReadOnlyApnTypes = b.getStringArray(
+                        CarrierConfigManager.KEY_READ_ONLY_APN_TYPES_STRING_ARRAY);
+                mReadOnlyApnFields = b.getStringArray(
+                        CarrierConfigManager.KEY_READ_ONLY_APN_FIELDS_STRING_ARRAY);
+            }
+        }
+
         if (action.equals(Intent.ACTION_EDIT)) {
             Uri uri = intent.getData();
             if (!uri.isPathPrefixMatch(Telephony.Carriers.CONTENT_URI)) {
@@ -220,17 +232,6 @@
                 finish();
                 return;
             }
-            CarrierConfigManager configManager = (CarrierConfigManager)
-                    getSystemService(Context.CARRIER_CONFIG_SERVICE);
-            if (configManager != null) {
-                PersistableBundle b = configManager.getConfig();
-                if (b != null) {
-                    mReadOnlyApnTypes = b.getStringArray(
-                            CarrierConfigManager.KEY_READ_ONLY_APN_TYPES_STRING_ARRAY);
-                    mReadOnlyApnFields = b.getStringArray(
-                            CarrierConfigManager.KEY_READ_ONLY_APN_FIELDS_STRING_ARRAY);
-                }
-            }
             mUri = uri;
         } else if (action.equals(Intent.ACTION_INSERT)) {
             if (mFirstTime || icicle.getInt(SAVED_POS) == 0) {
@@ -295,7 +296,7 @@
      * @param apnTypes array of APN types. "*" indicates all types.
      * @return true if all apn types are included in the array, false otherwise
      */
-    private boolean hasAllApns(String[] apnTypes) {
+    static boolean hasAllApns(String[] apnTypes) {
         if (ArrayUtils.isEmpty(apnTypes)) {
             return false;
         }
@@ -1052,6 +1053,24 @@
             errorMsg = mRes.getString(R.string.error_mnc_not23);
         }
 
+        if (errorMsg == null) {
+            // if carrier does not allow editing certain apn types, make sure type does not include
+            // those
+            if (mReadOnlyApnTypes.length > 0
+                    && apnTypesMatch(mReadOnlyApnTypes, mApnType.getText())) {
+                StringBuilder stringBuilder = new StringBuilder();
+                for (String type : mReadOnlyApnTypes) {
+                    stringBuilder.append(type).append(", ");
+                }
+                // remove last ", "
+                if (stringBuilder.length() >= 2) {
+                    stringBuilder.delete(stringBuilder.length() - 2, stringBuilder.length());
+                }
+                errorMsg = String.format(mRes.getString(R.string.error_adding_apn_type),
+                        stringBuilder);
+            }
+        }
+
         return errorMsg;
     }
 
diff --git a/src/com/android/settings/ApnSettings.java b/src/com/android/settings/ApnSettings.java
index 206d74f..d554301 100755
--- a/src/com/android/settings/ApnSettings.java
+++ b/src/com/android/settings/ApnSettings.java
@@ -173,6 +173,15 @@
         PersistableBundle b = configManager.getConfig();
         mHideImsApn = b.getBoolean(CarrierConfigManager.KEY_HIDE_IMS_APN_BOOL);
         mAllowAddingApns = b.getBoolean(CarrierConfigManager.KEY_ALLOW_ADDING_APNS_BOOL);
+        if (mAllowAddingApns) {
+            String[] readOnlyApnTypes = b.getStringArray(
+                    CarrierConfigManager.KEY_READ_ONLY_APN_TYPES_STRING_ARRAY);
+            // if no apn type can be edited, do not allow adding APNs
+            if (ApnEditor.hasAllApns(readOnlyApnTypes)) {
+                Log.d(TAG, "not allowing adding APN because all APN types are read only");
+                mAllowAddingApns = false;
+            }
+        }
         mUserManager = UserManager.get(activity);
     }
 
diff --git a/src/com/android/settings/DeviceAdminAdd.java b/src/com/android/settings/DeviceAdminAdd.java
index 3bb82cf..5978f5e 100644
--- a/src/com/android/settings/DeviceAdminAdd.java
+++ b/src/com/android/settings/DeviceAdminAdd.java
@@ -40,6 +40,7 @@
 import android.os.Binder;
 import android.os.Bundle;
 import android.os.Handler;
+import android.os.IBinder;
 import android.os.RemoteCallback;
 import android.os.RemoteException;
 import android.os.UserHandle;
@@ -65,8 +66,6 @@
 import com.android.settings.users.UserDialogs;
 import com.android.settingslib.RestrictedLockUtils;
 import com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
-import com.android.settingslib.SecureTouchListener;
-
 import org.xmlpull.v1.XmlPullParserException;
 
 import java.io.IOException;
@@ -92,6 +91,7 @@
     public static final String EXTRA_CALLED_FROM_SUPPORT_DIALOG =
             "android.app.extra.CALLED_FROM_SUPPORT_DIALOG";
 
+    private final IBinder mToken = new Binder();
     Handler mHandler;
 
     DevicePolicyManager mDPM;
@@ -120,8 +120,6 @@
     boolean mWaitingForRemoveMsg;
     boolean mAddingProfileOwner;
     boolean mAdminPoliciesInitialized;
-    int mCurSysAppOpMode;
-    int mCurToastAppOpMode;
 
     boolean mIsCalledFromSupportDialog = false;
 
@@ -352,10 +350,11 @@
 
         final View restrictedAction = findViewById(R.id.restricted_action);
         restrictedAction.setFilterTouchesWhenObscured(true);
-        restrictedAction.setOnTouchListener(
-                new SecureTouchListener(getString(R.string.window_obscured_warning)));
         restrictedAction.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
+                if (!mActionButton.isEnabled()) {
+                    return;
+                }
                 if (mAdding) {
                     addAndFinish();
                 } else if (isManagedProfile(mDeviceAdmin)
@@ -477,24 +476,21 @@
     @Override
     protected void onResume() {
         super.onResume();
+        mActionButton.setEnabled(true);
         updateInterface();
-        // As long as we are running, don't let this admin overlay stuff on top of the screen.
-        final int uid = mDeviceAdmin.getActivityInfo().applicationInfo.uid;
-        final String pkg = mDeviceAdmin.getActivityInfo().applicationInfo.packageName;
-        mCurSysAppOpMode = mAppOps.checkOp(AppOpsManager.OP_SYSTEM_ALERT_WINDOW, uid, pkg);
-        mCurToastAppOpMode = mAppOps.checkOp(AppOpsManager.OP_TOAST_WINDOW, uid, pkg);
-        mAppOps.setMode(AppOpsManager.OP_SYSTEM_ALERT_WINDOW, uid, pkg, AppOpsManager.MODE_IGNORED);
-        mAppOps.setMode(AppOpsManager.OP_TOAST_WINDOW, uid, pkg, AppOpsManager.MODE_IGNORED);
+        // As long as we are running, don't let anyone overlay stuff on top of the screen.
+        mAppOps.setUserRestriction(AppOpsManager.OP_SYSTEM_ALERT_WINDOW, true, mToken);
+        mAppOps.setUserRestriction(AppOpsManager.OP_TOAST_WINDOW, true, mToken);
+
     }
 
     @Override
     protected void onPause() {
         super.onPause();
-        // As long as we are running, don't let this admin overlay stuff on top of the screen.
-        final int uid = mDeviceAdmin.getActivityInfo().applicationInfo.uid;
-        final String pkg = mDeviceAdmin.getActivityInfo().applicationInfo.packageName;
-        mAppOps.setMode(AppOpsManager.OP_SYSTEM_ALERT_WINDOW, uid, pkg, mCurSysAppOpMode);
-        mAppOps.setMode(AppOpsManager.OP_TOAST_WINDOW, uid, pkg, mCurToastAppOpMode);
+        // This just greys out the button. The actual listener is attached to R.id.restricted_action
+        mActionButton.setEnabled(false);
+        mAppOps.setUserRestriction(AppOpsManager.OP_SYSTEM_ALERT_WINDOW, false, mToken);
+        mAppOps.setUserRestriction(AppOpsManager.OP_TOAST_WINDOW, false, mToken);
         try {
             ActivityManager.getService().resumeAppSwitches();
         } catch (RemoteException e) {
diff --git a/src/com/android/settings/DisplaySettings.java b/src/com/android/settings/DisplaySettings.java
index 26503e4..1b54f97 100644
--- a/src/com/android/settings/DisplaySettings.java
+++ b/src/com/android/settings/DisplaySettings.java
@@ -17,19 +17,17 @@
 package com.android.settings;
 
 import android.content.Context;
-import android.os.UserHandle;
 import android.provider.SearchIndexableResource;
 
 import com.android.internal.hardware.AmbientDisplayConfiguration;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.settings.core.PreferenceController;
 import com.android.settings.dashboard.DashboardFragment;
+import com.android.settings.display.AmbientDisplayPreferenceController;
 import com.android.settings.display.AutoBrightnessPreferenceController;
 import com.android.settings.display.AutoRotatePreferenceController;
 import com.android.settings.display.BrightnessLevelPreferenceController;
 import com.android.settings.display.CameraGesturePreferenceController;
-import com.android.settings.display.DozeAlwaysOnPreferenceController;
-import com.android.settings.display.DozePreferenceController;
 import com.android.settings.display.FontSizePreferenceController;
 import com.android.settings.display.LiftToWakePreferenceController;
 import com.android.settings.display.NightDisplayPreferenceController;
@@ -40,9 +38,6 @@
 import com.android.settings.display.TimeoutPreferenceController;
 import com.android.settings.display.VrDisplayPreferenceController;
 import com.android.settings.display.WallpaperPreferenceController;
-import com.android.settings.gestures.DoubleTapScreenPreferenceController;
-import com.android.settings.gestures.PickupGesturePreferenceController;
-import com.android.settings.overlay.FeatureFactory;
 import com.android.settings.search.BaseSearchIndexProvider;
 import com.android.settings.search.Indexable;
 import com.android.settingslib.core.lifecycle.Lifecycle;
@@ -57,8 +52,7 @@
     public static final String KEY_DISPLAY_SIZE = "screen_zoom";
 
     private static final String KEY_SCREEN_TIMEOUT = "screen_timeout";
-    private static final String KEY_PICK_UP = "gesture_pick_up_display_summary";
-    private static final String KEY_DOUBLE_TAP_SCREEN = "gesture_double_tap_screen_display_summary";
+    private static final String KEY_AMBIENT_DISPLAY = "ambient_display";
 
     @Override
     public int getMetricsCategory() {
@@ -98,19 +92,13 @@
         controllers.add(new AutoBrightnessPreferenceController(context, KEY_AUTO_BRIGHTNESS));
         controllers.add(new AutoRotatePreferenceController(context, lifecycle));
         controllers.add(new CameraGesturePreferenceController(context));
-        controllers.add(new DozePreferenceController(context, ambientDisplayConfig,
-                FeatureFactory.getFactory(context).getMetricsFeatureProvider()));
-        controllers.add(new DozeAlwaysOnPreferenceController(context, ambientDisplayConfig));
         controllers.add(new FontSizePreferenceController(context));
         controllers.add(new LiftToWakePreferenceController(context));
         controllers.add(new NightDisplayPreferenceController(context));
         controllers.add(new NightModePreferenceController(context));
         controllers.add(new ScreenSaverPreferenceController(context));
-        controllers.add(new PickupGesturePreferenceController(
-                context, lifecycle, ambientDisplayConfig, UserHandle.myUserId(), KEY_PICK_UP));
-        controllers.add(new DoubleTapScreenPreferenceController(
-                context, lifecycle, ambientDisplayConfig, UserHandle.myUserId(),
-                KEY_DOUBLE_TAP_SCREEN));
+        controllers.add(new AmbientDisplayPreferenceController(context, ambientDisplayConfig,
+                KEY_AMBIENT_DISPLAY));
         controllers.add(new TapToWakePreferenceController(context));
         controllers.add(new TimeoutPreferenceController(context, KEY_SCREEN_TIMEOUT));
         controllers.add(new VrDisplayPreferenceController(context));
diff --git a/src/com/android/settings/MasterClear.java b/src/com/android/settings/MasterClear.java
index 77c6091..dc4c995 100644
--- a/src/com/android/settings/MasterClear.java
+++ b/src/com/android/settings/MasterClear.java
@@ -23,6 +23,7 @@
 import android.accounts.AuthenticatorDescription;
 import android.app.Activity;
 import android.app.FragmentManager;
+import android.content.ContentResolver;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.PackageManager;
@@ -34,6 +35,7 @@
 import android.os.SystemProperties;
 import android.os.UserHandle;
 import android.os.UserManager;
+import android.provider.Settings;
 import android.support.annotation.VisibleForTesting;
 import android.telephony.euicc.EuiccManager;
 import android.util.Log;
@@ -208,9 +210,7 @@
             });
         }
 
-        EuiccManager euiccManager =
-                        (EuiccManager) getActivity().getSystemService(Context.EUICC_SERVICE);
-        if (euiccManager.isEnabled()) {
+        if (showWipeEuicc()) {
             mEsimStorageContainer.setOnClickListener(new View.OnClickListener() {
 
                 @Override
@@ -244,6 +244,30 @@
         mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);
     }
 
+    /**
+     * Whether to show the checkbox to wipe the eUICC.
+     *
+     * <p>We show the checkbox on any device which supports eUICC as long as either the eUICC was
+     * ever provisioned (that is, at least one profile was ever downloaded onto it), or if the user
+     * has enabled development mode.
+     */
+    @VisibleForTesting
+    boolean showWipeEuicc() {
+        Context context = getContext();
+        if (!isEuiccEnabled(context)) {
+            return false;
+        }
+        ContentResolver cr = context.getContentResolver();
+        return Settings.Global.getInt(cr, Settings.Global.EUICC_PROVISIONED, 0) != 0
+                || Settings.Global.getInt(cr, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0;
+    }
+
+    @VisibleForTesting
+    protected boolean isEuiccEnabled(Context context) {
+        EuiccManager euiccManager = (EuiccManager) context.getSystemService(Context.EUICC_SERVICE);
+        return euiccManager.isEnabled();
+    }
+
     @VisibleForTesting
     boolean hasReachedBottom(final ScrollView scrollView) {
         if (scrollView.getChildCount() < 1) {
diff --git a/src/com/android/settings/SettingsPreferenceFragment.java b/src/com/android/settings/SettingsPreferenceFragment.java
index 3fc7964..5bcbc11 100644
--- a/src/com/android/settings/SettingsPreferenceFragment.java
+++ b/src/com/android/settings/SettingsPreferenceFragment.java
@@ -26,6 +26,7 @@
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.os.Bundle;
+import android.support.annotation.VisibleForTesting;
 import android.support.annotation.XmlRes;
 import android.support.v7.preference.Preference;
 import android.support.v7.preference.PreferenceGroup;
@@ -423,11 +424,28 @@
         return -1;
     }
 
-    protected void removePreference(String key) {
-        Preference pref = findPreference(key);
-        if (pref != null) {
-            getPreferenceScreen().removePreference(pref);
+    protected boolean removePreference(String key) {
+        return removePreference(getPreferenceScreen(), key);
+    }
+
+    @VisibleForTesting
+    boolean removePreference(PreferenceGroup group, String key) {
+        final int preferenceCount = group.getPreferenceCount();
+        for (int i = 0; i < preferenceCount; i++) {
+            final Preference preference = group.getPreference(i);
+            final String curKey = preference.getKey();
+
+            if (TextUtils.equals(curKey, key)) {
+                return group.removePreference(preference);
+            }
+
+            if (preference instanceof PreferenceGroup) {
+                if (removePreference((PreferenceGroup) preference, key)) {
+                    return true;
+                }
+            }
         }
+        return false;
     }
 
     /**
diff --git a/src/com/android/settings/Utils.java b/src/com/android/settings/Utils.java
index 0142ea2..f0d5107 100644
--- a/src/com/android/settings/Utils.java
+++ b/src/com/android/settings/Utils.java
@@ -25,6 +25,7 @@
 import android.app.ActivityManager;
 import android.app.AlertDialog;
 import android.app.AppGlobals;
+import android.app.AppOpsManager;
 import android.app.Dialog;
 import android.app.Fragment;
 import android.app.IActivityManager;
@@ -1011,7 +1012,24 @@
             return getCredentialOwnerUserId(context);
         }
         int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
-        return enforceSameOwner(context, userId);
+        if (userId == LockPatternUtils.USER_FRP) {
+            return enforceSystemUser(context, userId);
+        } else {
+            return enforceSameOwner(context, userId);
+        }
+    }
+
+    /**
+     * Returns the given user id if the current user is the system user.
+     *
+     * @throws SecurityException if the current user is not the system user.
+     */
+    public static int enforceSystemUser(Context context, int userId) {
+        if (UserHandle.myUserId() == UserHandle.USER_SYSTEM) {
+            return userId;
+        }
+        throw new SecurityException("Given user id " + userId + " must only be used from "
+                + "USER_SYSTEM, but current user is " + UserHandle.myUserId());
     }
 
     /**
@@ -1272,6 +1290,20 @@
         return info.enabled ? R.string.installed : R.string.disabled;
     }
 
+    /**
+     * Control if other apps can display overlays. By default this is allowed. Be sure to
+     * re-enable overlays, as the effect is system-wide.
+     */
+    public static void setOverlayAllowed(Context context, IBinder token, boolean allowed) {
+        AppOpsManager appOpsManager = context.getSystemService(AppOpsManager.class);
+        if (appOpsManager != null) {
+            appOpsManager.setUserRestriction(AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
+                    !allowed, token);
+            appOpsManager.setUserRestriction(AppOpsManager.OP_TOAST_WINDOW,
+                    !allowed, token);
+        }
+    }
+
     private static boolean isVolumeValid(VolumeInfo volume) {
         return (volume != null) && (volume.getType() == VolumeInfo.TYPE_PRIVATE)
                 && volume.isMountedReadable();
diff --git a/src/com/android/settings/accessibility/AccessibilityServiceWarning.java b/src/com/android/settings/accessibility/AccessibilityServiceWarning.java
index e0c58db..0a6932f 100644
--- a/src/com/android/settings/accessibility/AccessibilityServiceWarning.java
+++ b/src/com/android/settings/accessibility/AccessibilityServiceWarning.java
@@ -48,14 +48,14 @@
                 .setTitle(parentActivity.getString(R.string.enable_service_title,
                         getServiceName(parentActivity, info)))
                 .setView(createEnableDialogContentView(parentActivity, info))
-                .setCancelable(true)
                 .setPositiveButton(android.R.string.ok, listener)
                 .setNegativeButton(android.R.string.cancel, listener)
                 .create();
 
         final View.OnTouchListener filterTouchListener = (View v, MotionEvent event) -> {
             // Filter obscured touches by consuming them.
-            if ((event.getFlags() & MotionEvent.FLAG_WINDOW_IS_PARTIALLY_OBSCURED) != 0) {
+            if (((event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0)
+                    || ((event.getFlags() & MotionEvent.FLAG_WINDOW_IS_PARTIALLY_OBSCURED) != 0)) {
                 if (event.getAction() == MotionEvent.ACTION_UP) {
                     Toast.makeText(v.getContext(), R.string.touch_filtered_warning,
                             Toast.LENGTH_SHORT).show();
@@ -67,6 +67,8 @@
 
         ad.create();
         ad.getButton(AlertDialog.BUTTON_POSITIVE).setOnTouchListener(filterTouchListener);
+        ad.setCanceledOnTouchOutside(true);
+
         return ad;
     }
 
diff --git a/src/com/android/settings/accessibility/ShortcutServicePickerFragment.java b/src/com/android/settings/accessibility/ShortcutServicePickerFragment.java
index d7749ea..ae57f06 100644
--- a/src/com/android/settings/accessibility/ShortcutServicePickerFragment.java
+++ b/src/com/android/settings/accessibility/ShortcutServicePickerFragment.java
@@ -16,26 +16,24 @@
 package com.android.settings.accessibility;
 
 import static android.content.DialogInterface.BUTTON_POSITIVE;
+import static com.android.settings.Utils.setOverlayAllowed;
 
 import android.accessibilityservice.AccessibilityServiceInfo;
 import android.app.Activity;
-import android.app.AlertDialog;
 import android.app.Dialog;
 import android.app.DialogFragment;
 import android.app.Fragment;
 import android.content.ComponentName;
 import android.content.DialogInterface;
-import android.content.pm.PackageManager;
-import android.content.pm.PackageParser;
+import android.os.Binder;
 import android.os.Bundle;
+import android.os.IBinder;
 import android.os.UserHandle;
 import android.provider.Settings;
-import android.support.v7.preference.Preference;
 import android.text.TextUtils;
 import android.view.accessibility.AccessibilityManager;
 
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.settings.DialogCreatable;
 import com.android.settings.applications.defaultapps.DefaultAppInfo;
 import com.android.settings.applications.defaultapps.DefaultAppPickerFragment;
 import com.android.settings.core.instrumentation.InstrumentedDialogFragment;
@@ -118,6 +116,7 @@
             implements DialogInterface.OnClickListener {
         private static final String EXTRA_KEY = "extra_key";
         private static final String TAG = "ConfirmationDialogFragment";
+        private IBinder mToken;
 
         public static ConfirmationDialogFragment newInstance(ShortcutServicePickerFragment parent,
                 String key) {
@@ -126,6 +125,7 @@
             argument.putString(EXTRA_KEY, key);
             fragment.setArguments(argument);
             fragment.setTargetFragment(parent, 0);
+            fragment.mToken = new Binder();
             return fragment;
         }
 
@@ -147,6 +147,22 @@
         }
 
         @Override
+        public void onResume() {
+            super.onResume();
+            if (mToken != null) {
+                setOverlayAllowed(getActivity(), mToken, false);
+            }
+        }
+
+        @Override
+        public void onPause() {
+            super.onPause();
+            if (mToken != null) {
+                setOverlayAllowed(getActivity(), mToken, true);
+            }
+        }
+
+        @Override
         public void onClick(DialogInterface dialog, int which) {
             final Fragment fragment = getTargetFragment();
             if ((which == BUTTON_POSITIVE) && (fragment instanceof DefaultAppPickerFragment)) {
diff --git a/src/com/android/settings/accessibility/ToggleAccessibilityServicePreferenceFragment.java b/src/com/android/settings/accessibility/ToggleAccessibilityServicePreferenceFragment.java
index b345e05..976a743 100644
--- a/src/com/android/settings/accessibility/ToggleAccessibilityServicePreferenceFragment.java
+++ b/src/com/android/settings/accessibility/ToggleAccessibilityServicePreferenceFragment.java
@@ -26,8 +26,10 @@
 import android.content.Intent;
 import android.content.pm.ResolveInfo;
 import android.net.Uri;
+import android.os.Binder;
 import android.os.Bundle;
 import android.os.Handler;
+import android.os.IBinder;
 import android.os.UserHandle;
 import android.os.storage.StorageManager;
 import android.provider.Settings;
@@ -46,6 +48,8 @@
 
 import java.util.List;
 
+import static com.android.settings.Utils.setOverlayAllowed;
+
 public class ToggleAccessibilityServicePreferenceFragment
         extends ToggleFeaturePreferenceFragment implements DialogInterface.OnClickListener {
 
@@ -68,6 +72,8 @@
 
     private int mShownDialogId;
 
+    private final IBinder mToken = new Binder();
+
     @Override
     public int getMetricsCategory() {
         return MetricsEvent.ACCESSIBILITY_SERVICE;
@@ -90,12 +96,18 @@
     public void onResume() {
         mSettingsContentObserver.register(getContentResolver());
         updateSwitchBarToggleSwitch();
+        if (mToken != null) {
+            setOverlayAllowed(getActivity(), mToken, false);
+        }
         super.onResume();
     }
 
     @Override
     public void onPause() {
         mSettingsContentObserver.unregister(getContentResolver());
+        if (mToken != null) {
+            setOverlayAllowed(getActivity(), mToken, true);
+        }
         super.onPause();
     }
 
diff --git a/src/com/android/settings/accounts/AccountTypePreference.java b/src/com/android/settings/accounts/AccountTypePreference.java
index 4f92829..f66970d 100644
--- a/src/com/android/settings/accounts/AccountTypePreference.java
+++ b/src/com/android/settings/accounts/AccountTypePreference.java
@@ -72,6 +72,7 @@
             String titleResPackageName, int titleResId, CharSequence summary, String fragment,
             Bundle fragmentArguments, Drawable icon) {
         super(context);
+        setLayoutResource(R.layout.preference_small_icon);
         mTitle = account.name;
         mTitleResPackageName = titleResPackageName;
         mTitleResId = titleResId;
@@ -79,7 +80,6 @@
         mFragment = fragment;
         mFragmentArguments = fragmentArguments;
         mMetricsCategory = metricsCategory;
-        setWidgetLayoutResource(R.layout.account_type_preference);
 
         setKey(buildKey(account));
         setTitle(mTitle);
diff --git a/src/com/android/settings/applications/AdvancedAppSettings.java b/src/com/android/settings/applications/AdvancedAppSettings.java
index cce8b7d..b623801 100644
--- a/src/com/android/settings/applications/AdvancedAppSettings.java
+++ b/src/com/android/settings/applications/AdvancedAppSettings.java
@@ -18,8 +18,8 @@
 import android.app.Activity;
 import android.content.Context;
 import android.provider.SearchIndexableResource;
-
 import android.text.TextUtils;
+
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.settings.R;
 import com.android.settings.applications.defaultapps.DefaultBrowserPreferenceController;
@@ -57,6 +57,15 @@
 
     @Override
     protected List<PreferenceController> getPreferenceControllers(Context context) {
+        return buildPreferenceControllers(context);
+    }
+
+    @Override
+    public int getMetricsCategory() {
+        return MetricsEvent.APPLICATIONS_ADVANCED;
+    }
+
+    private static List<PreferenceController> buildPreferenceControllers(Context context) {
         final List<PreferenceController> controllers = new ArrayList<>();
         controllers.add(new DefaultBrowserPreferenceController(context));
         controllers.add(new DefaultWorkBrowserPreferenceController(context));
@@ -68,11 +77,6 @@
         return controllers;
     }
 
-    @Override
-    public int getMetricsCategory() {
-        return MetricsEvent.APPLICATIONS_ADVANCED;
-    }
-
     public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
             new BaseSearchIndexProvider() {
                 @Override
@@ -94,6 +98,11 @@
                             .getPreferenceKey());
                     return keys;
                 }
+
+                @Override
+                public List<PreferenceController> getPreferenceControllers(Context context) {
+                    return buildPreferenceControllers(context);
+                }
             };
 
     static class SummaryProvider implements SummaryLoader.SummaryProvider {
@@ -118,10 +127,10 @@
                 return;
             }
             CharSequence summary = concatSummaryText(
-                mDefaultSmsPreferenceController.getDefaultAppLabel(),
-                mDefaultBrowserPreferenceController.getDefaultAppLabel());
+                    mDefaultSmsPreferenceController.getDefaultAppLabel(),
+                    mDefaultBrowserPreferenceController.getDefaultAppLabel());
             summary = concatSummaryText(summary,
-                mDefaultPhonePreferenceController.getDefaultAppLabel());
+                    mDefaultPhonePreferenceController.getDefaultAppLabel());
             if (!TextUtils.isEmpty(summary)) {
                 mSummaryLoader.setSummary(this, summary);
             }
@@ -139,11 +148,11 @@
     }
 
     public static final SummaryLoader.SummaryProviderFactory SUMMARY_PROVIDER_FACTORY =
-        new SummaryLoader.SummaryProviderFactory() {
-            @Override
-            public SummaryLoader.SummaryProvider createSummaryProvider(Activity activity,
-                    SummaryLoader summaryLoader) {
-                return new AdvancedAppSettings.SummaryProvider(activity, summaryLoader);
-            }
-        };
+            new SummaryLoader.SummaryProviderFactory() {
+                @Override
+                public SummaryLoader.SummaryProvider createSummaryProvider(Activity activity,
+                        SummaryLoader summaryLoader) {
+                    return new AdvancedAppSettings.SummaryProvider(activity, summaryLoader);
+                }
+            };
 }
diff --git a/src/com/android/settings/applications/ManageApplications.java b/src/com/android/settings/applications/ManageApplications.java
index 6274374..8fd41df 100644
--- a/src/com/android/settings/applications/ManageApplications.java
+++ b/src/com/android/settings/applications/ManageApplications.java
@@ -418,14 +418,14 @@
             mFilterAdapter.enableFilter(FILTER_APPS_POWER_WHITELIST_ALL);
         }
 
-        AppFilter overrideFilter = getOverrideFilter(mListType, mStorageType, mVolumeUuid);
-        if (overrideFilter != null) {
-            mApplications.setOverrideFilter(overrideFilter);
+        AppFilter compositeFilter = getCompositeFilter(mListType, mStorageType, mVolumeUuid);
+        if (compositeFilter != null) {
+            mApplications.setCompositeFilter(compositeFilter);
         }
     }
 
     @VisibleForTesting
-    static @Nullable AppFilter getOverrideFilter(int listType, int storageType, String volumeUuid) {
+    static @Nullable AppFilter getCompositeFilter(int listType, int storageType, String volumeUuid) {
         AppFilter filter = new VolumeFilter(volumeUuid);
         if (listType == LIST_TYPE_STORAGE) {
             if (storageType == STORAGE_TYPE_MUSIC) {
@@ -840,7 +840,7 @@
         private int mWhichSize = SIZE_TOTAL;
         CharSequence mCurFilterPrefix;
         private PackageManager mPm;
-        private AppFilter mOverrideFilter;
+        private AppFilter mCompositeFilter;
         private boolean mHasReceivedLoadEntries;
         private boolean mHasReceivedBridgeCallback;
         private FileViewHolderController mExtraViewController;
@@ -904,8 +904,8 @@
             }
         }
 
-        public void setOverrideFilter(AppFilter overrideFilter) {
-            mOverrideFilter = overrideFilter;
+        public void setCompositeFilter(AppFilter compositeFilter) {
+            mCompositeFilter = compositeFilter;
             rebuild(true);
         }
 
@@ -983,8 +983,8 @@
                 mWhichSize = SIZE_INTERNAL;
             }
             filterObj = FILTERS[mFilterMode];
-            if (mOverrideFilter != null) {
-                filterObj = mOverrideFilter;
+            if (mCompositeFilter != null) {
+                filterObj = new CompoundFilter(filterObj, mCompositeFilter);
             }
             if (!mManageApplications.mShowSystem) {
                 if (LIST_TYPES_WITH_INSTANT.contains(mManageApplications.mListType)) {
diff --git a/src/com/android/settings/applications/PackageManagerWrapper.java b/src/com/android/settings/applications/PackageManagerWrapper.java
index 0cfbdc5..580b578 100644
--- a/src/com/android/settings/applications/PackageManagerWrapper.java
+++ b/src/com/android/settings/applications/PackageManagerWrapper.java
@@ -111,4 +111,6 @@
      */
     void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int flags,
             int userId);
+
+    int getPackageUidAsUser(String pkg, int userId) throws PackageManager.NameNotFoundException;
 }
diff --git a/src/com/android/settings/applications/PackageManagerWrapperImpl.java b/src/com/android/settings/applications/PackageManagerWrapperImpl.java
index 3a78e3c..a47137c 100644
--- a/src/com/android/settings/applications/PackageManagerWrapperImpl.java
+++ b/src/com/android/settings/applications/PackageManagerWrapperImpl.java
@@ -103,4 +103,10 @@
             int userId) {
         mPm.deletePackageAsUser(packageName, observer, flags, userId);
     }
+
+    @Override
+    public int getPackageUidAsUser(String pkg, int userId)
+            throws PackageManager.NameNotFoundException {
+        return mPm.getPackageUidAsUser(pkg, userId);
+    }
 }
diff --git a/src/com/android/settings/applications/RecentAppsPreferenceController.java b/src/com/android/settings/applications/RecentAppsPreferenceController.java
index 43ede2f..7a99508 100644
--- a/src/com/android/settings/applications/RecentAppsPreferenceController.java
+++ b/src/com/android/settings/applications/RecentAppsPreferenceController.java
@@ -77,6 +77,7 @@
 
     private PreferenceCategory mCategory;
     private Preference mSeeAllPref;
+    private boolean mHasRecentApps;
 
     static {
         SKIP_SYSTEM_PACKAGES.addAll(Arrays.asList(
@@ -133,15 +134,20 @@
     @Override
     public void updateState(Preference preference) {
         super.updateState(preference);
+        refreshUi(mCategory.getContext());
         // Show total number of installed apps as See all's summary.
         new InstalledAppCounter(mContext, InstalledAppCounter.IGNORE_INSTALL_REASON,
                 new PackageManagerWrapperImpl(mContext.getPackageManager())) {
             @Override
             protected void onCountComplete(int num) {
-                mSeeAllPref.setSummary(mContext.getString(R.string.apps_summary, num));
+                if (mHasRecentApps) {
+                    mSeeAllPref.setTitle(mContext.getString(R.string.see_all_apps_title, num));
+                } else {
+                    mSeeAllPref.setSummary(mContext.getString(R.string.apps_summary, num));
+                }
             }
         }.execute();
-        refreshUi(mCategory.getContext());
+
     }
 
     @Override
@@ -155,8 +161,10 @@
         reloadData();
         final List<UsageStats> recentApps = getDisplayableRecentAppList();
         if (recentApps != null && !recentApps.isEmpty()) {
+            mHasRecentApps = true;
             displayRecentApps(prefContext, recentApps);
         } else {
+            mHasRecentApps = false;
             displayOnlyAppInfo();
         }
     }
@@ -185,7 +193,7 @@
 
     private void displayRecentApps(Context prefContext, List<UsageStats> recentApps) {
         mCategory.setTitle(R.string.recent_app_category_title);
-        mSeeAllPref.setTitle(R.string.see_all_apps_title);
+        mSeeAllPref.setSummary(null);
         mSeeAllPref.setIcon(R.drawable.ic_chevron_right_24dp);
 
         // Rebind prefs/avoid adding new prefs if possible. Adding/removing prefs causes jank.
diff --git a/src/com/android/settings/applications/defaultapps/DefaultAppPickerFragment.java b/src/com/android/settings/applications/defaultapps/DefaultAppPickerFragment.java
index a08711c..d3617ef 100644
--- a/src/com/android/settings/applications/defaultapps/DefaultAppPickerFragment.java
+++ b/src/com/android/settings/applications/defaultapps/DefaultAppPickerFragment.java
@@ -23,11 +23,11 @@
 import android.app.Fragment;
 import android.content.Context;
 import android.content.DialogInterface;
-import android.content.DialogInterface.OnClickListener;
 import android.os.Bundle;
 import android.text.TextUtils;
+import android.util.Pair;
 
-import com.android.internal.logging.nano.MetricsProto;
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.settings.R;
 import com.android.settings.applications.PackageManagerWrapper;
 import com.android.settings.applications.PackageManagerWrapperImpl;
@@ -63,6 +63,16 @@
     }
 
     @Override
+    protected void onRadioButtonConfirmed(String selectedKey) {
+        mMetricsFeatureProvider.action(getContext(),
+                MetricsEvent.ACTION_SETTINGS_UPDATE_DEFAULT_APP,
+                selectedKey,
+                Pair.create(MetricsEvent.FIELD_CONTEXT, getMetricsCategory()));
+
+        super.onRadioButtonConfirmed(selectedKey);
+    }
+
+    @Override
     public void bindPreferenceExtra(RadioButtonPreference pref,
             String key, CandidateInfo info, String defaultKey, String systemDefaultKey) {
         if (!(info instanceof DefaultAppInfo)) {
@@ -97,7 +107,7 @@
 
         @Override
         public int getMetricsCategory() {
-            return MetricsProto.MetricsEvent.DEFAULT_APP_PICKER_CONFIRMATION_DIALOG;
+            return MetricsEvent.DEFAULT_APP_PICKER_CONFIRMATION_DIALOG;
         }
 
         /**
diff --git a/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceController.java b/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceController.java
index 5c0f9a3..219ce0f 100644
--- a/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceController.java
+++ b/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceController.java
@@ -18,16 +18,20 @@
 
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.ComponentInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.net.Uri;
 import android.support.v7.preference.Preference;
 import android.text.TextUtils;
+import android.util.Log;
 
 import java.util.List;
 
 public class DefaultBrowserPreferenceController extends DefaultAppPreferenceController {
 
+    private static final String TAG = "BrowserPrefCtrl";
+
     static final Intent BROWSE_PROBE = new Intent()
             .setAction(Intent.ACTION_VIEW)
             .addCategory(Intent.CATEGORY_BROWSABLE)
@@ -60,9 +64,10 @@
     @Override
     protected DefaultAppInfo getDefaultAppInfo() {
         try {
+            final String packageName = mPackageManager.getDefaultBrowserPackageNameAsUser(mUserId);
+            Log.d(TAG, "Get default browser package: " + packageName);
             return new DefaultAppInfo(mPackageManager,
-                    mPackageManager.getPackageManager().getApplicationInfo(
-                            mPackageManager.getDefaultBrowserPackageNameAsUser(mUserId), 0));
+                    mPackageManager.getPackageManager().getApplicationInfo(packageName, 0));
         } catch (PackageManager.NameNotFoundException e) {
             return null;
         }
@@ -90,7 +95,12 @@
         // Resolve that intent and check that the handleAllWebDataURI boolean is set
         final List<ResolveInfo> list = getCandidates();
         if (list != null && list.size() == 1) {
-            return list.get(0).loadLabel(mPackageManager.getPackageManager()).toString();
+            final ResolveInfo info = list.get(0);
+            final String label = info.loadLabel(mPackageManager.getPackageManager()).toString();
+            final ComponentInfo cn = info.getComponentInfo();
+            final String packageName = cn == null ? null : cn.packageName;
+            Log.d(TAG, "Getting label for the only browser app: " + packageName + label);
+            return label;
         }
         return null;
     }
diff --git a/src/com/android/settings/applications/defaultapps/DefaultHomePicker.java b/src/com/android/settings/applications/defaultapps/DefaultHomePicker.java
index 038267b..dca7ad1 100644
--- a/src/com/android/settings/applications/defaultapps/DefaultHomePicker.java
+++ b/src/com/android/settings/applications/defaultapps/DefaultHomePicker.java
@@ -63,13 +63,15 @@
             }
 
             final String summary;
+            boolean enabled = true;
             if (mustSupportManagedProfile && !launcherHasManagedProfilesFeature(resolveInfo)) {
                 summary = getContext().getString(R.string.home_work_profile_not_supported);
+                enabled = false;
             } else {
                 summary = null;
             }
             final DefaultAppInfo candidate =
-                    new DefaultAppInfo(mPm, mUserId, activityName, summary);
+                    new DefaultAppInfo(mPm, mUserId, activityName, summary, enabled);
             candidates.add(candidate);
         }
         return candidates;
diff --git a/src/com/android/settings/bluetooth/BluetoothFeatureProvider.java b/src/com/android/settings/bluetooth/BluetoothFeatureProvider.java
index 358223d..a6ae31c 100644
--- a/src/com/android/settings/bluetooth/BluetoothFeatureProvider.java
+++ b/src/com/android/settings/bluetooth/BluetoothFeatureProvider.java
@@ -21,7 +21,12 @@
  */
 public interface BluetoothFeatureProvider {
     /**
-     * Check whether additional pairing page is enabled
+     * @return whether additional pairing page is enabled
      */
     boolean isPairingPageEnabled();
+
+    /**
+     * @return whether device details should be shown as a separate page (true) or a dialog (false)
+     */
+    boolean isDeviceDetailPageEnabled();
 }
diff --git a/src/com/android/settings/bluetooth/BluetoothFeatureProviderImpl.java b/src/com/android/settings/bluetooth/BluetoothFeatureProviderImpl.java
index f5b65b7..8d9e1c4 100644
--- a/src/com/android/settings/bluetooth/BluetoothFeatureProviderImpl.java
+++ b/src/com/android/settings/bluetooth/BluetoothFeatureProviderImpl.java
@@ -9,4 +9,9 @@
     public boolean isPairingPageEnabled() {
         return false;
     }
+
+    @Override
+    public boolean isDeviceDetailPageEnabled() {
+        return false;
+    }
 }
diff --git a/src/com/android/settings/core/instrumentation/SharedPreferencesLogger.java b/src/com/android/settings/core/instrumentation/SharedPreferencesLogger.java
index 51102a6..b57ff6a 100644
--- a/src/com/android/settings/core/instrumentation/SharedPreferencesLogger.java
+++ b/src/com/android/settings/core/instrumentation/SharedPreferencesLogger.java
@@ -20,6 +20,7 @@
 import android.content.SharedPreferences;
 import android.content.pm.PackageManager;
 import android.os.AsyncTask;
+import android.support.annotation.VisibleForTesting;
 import android.text.TextUtils;
 import android.util.Log;
 import android.util.Pair;
@@ -145,12 +146,11 @@
         }
     }
 
-    private void logPackageName(String key, String value) {
+    @VisibleForTesting
+    void logPackageName(String key, String value) {
         final String prefKey = mTag + "/" + key;
-        mMetricsFeature.action(mContext, MetricsEvent.ACTION_SETTINGS_PREFERENCE_CHANGE,
+        mMetricsFeature.action(mContext, MetricsEvent.ACTION_SETTINGS_PREFERENCE_CHANGE, value,
                 Pair.create(MetricsEvent.FIELD_SETTINGS_PREFERENCE_CHANGE_NAME, prefKey));
-        mMetricsFeature.action(mContext, MetricsEvent.ACTION_GENERIC_PACKAGE,
-                prefKey + "|" + value);
     }
 
     private void safeLogValue(String key, String value) {
diff --git a/src/com/android/settings/datausage/AppDataUsage.java b/src/com/android/settings/datausage/AppDataUsage.java
index af6306d..d9643f2 100644
--- a/src/com/android/settings/datausage/AppDataUsage.java
+++ b/src/com/android/settings/datausage/AppDataUsage.java
@@ -36,12 +36,15 @@
 import android.text.format.Formatter;
 import android.util.ArraySet;
 import android.util.IconDrawableFactory;
+import android.util.Log;
 import android.view.View;
 import android.widget.AdapterView;
 
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.settings.R;
 import com.android.settings.applications.AppInfoBase;
+import com.android.settings.applications.PackageManagerWrapper;
+import com.android.settings.applications.PackageManagerWrapperImpl;
 import com.android.settings.widget.EntityHeaderController;
 import com.android.settingslib.AppItem;
 import com.android.settingslib.net.ChartData;
@@ -71,6 +74,7 @@
     private static final int LOADER_CHART_DATA = 2;
     private static final int LOADER_APP_PREF = 3;
 
+    private PackageManagerWrapper mPackageManagerWrapper;
     private final ArraySet<String> mPackages = new ArraySet<>();
     private Preference mTotalUsage;
     private Preference mForegroundUsage;
@@ -99,6 +103,7 @@
     @Override
     public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
+        mPackageManagerWrapper = new PackageManagerWrapperImpl(getPackageManager());
         final Bundle args = getArguments();
 
         try {
@@ -142,11 +147,11 @@
 
         if (mAppItem.key > 0) {
             if (mPackages.size() != 0) {
-                PackageManager pm = getPackageManager();
                 try {
-                    ApplicationInfo info = pm.getApplicationInfo(mPackages.valueAt(0), 0);
+                    ApplicationInfo info = mPackageManagerWrapper.getApplicationInfoAsUser(
+                            mPackages.valueAt(0), 0, UserHandle.getUserId(mAppItem.key));
                     mIcon = IconDrawableFactory.newInstance(getActivity()).getBadgedIcon(info);
-                    mLabel = info.loadLabel(pm);
+                    mLabel = info.loadLabel(mPackageManagerWrapper.getPackageManager());
                     mPackageName = info.packageName;
                 } catch (PackageManager.NameNotFoundException e) {
                 }
@@ -317,9 +322,13 @@
 
         String pkg = mPackages.size() != 0 ? mPackages.valueAt(0) : null;
         int uid = 0;
-        try {
-            uid = pkg != null ? getPackageManager().getPackageUid(pkg, 0) : 0;
-        } catch (PackageManager.NameNotFoundException e) {
+        if (pkg != null) {
+            try {
+                uid = mPackageManagerWrapper.getPackageUidAsUser(pkg,
+                        UserHandle.getUserId(mAppItem.key));
+            } catch (PackageManager.NameNotFoundException e) {
+                Log.w(TAG, "Skipping UID because cannot find package " + pkg);
+            }
         }
 
         final boolean showInfoButton = mAppItem.key > 0;
@@ -328,6 +337,7 @@
         final Preference pref = EntityHeaderController
                 .newInstance(activity, this, null /* header */)
                 .setRecyclerView(getListView(), getLifecycle())
+                .setUid(uid)
                 .setButtonActions(showInfoButton
                                 ? EntityHeaderController.ActionType.ACTION_APP_INFO
                                 : EntityHeaderController.ActionType.ACTION_NONE,
@@ -335,7 +345,6 @@
                 .setIcon(mIcon)
                 .setLabel(mLabel)
                 .setPackageName(pkg)
-                .setUid(uid)
                 .done(activity, getPrefContext());
         getPreferenceScreen().addPreference(pref);
     }
diff --git a/src/com/android/settings/development/DevelopmentSettings.java b/src/com/android/settings/development/DevelopmentSettings.java
index 6b33a5b..bd96777 100644
--- a/src/com/android/settings/development/DevelopmentSettings.java
+++ b/src/com/android/settings/development/DevelopmentSettings.java
@@ -1457,7 +1457,7 @@
     private void updateBluetoothEnableInbandRingingOptions() {
         if (mBluetoothEnableInbandRinging != null) {
             updateSwitchPreference(mBluetoothEnableInbandRinging,
-                SystemProperties.getBoolean(BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY, false));
+                SystemProperties.getBoolean(BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY, true));
         }
     }
 
diff --git a/src/com/android/settings/display/DozeAlwaysOnPreferenceController.java b/src/com/android/settings/display/AmbientDisplayAlwaysOnPreferenceController.java
similarity index 82%
rename from src/com/android/settings/display/DozeAlwaysOnPreferenceController.java
rename to src/com/android/settings/display/AmbientDisplayAlwaysOnPreferenceController.java
index e3e2e2d..bed04d3 100644
--- a/src/com/android/settings/display/DozeAlwaysOnPreferenceController.java
+++ b/src/com/android/settings/display/AmbientDisplayAlwaysOnPreferenceController.java
@@ -27,22 +27,23 @@
 import com.android.internal.hardware.AmbientDisplayConfiguration;
 import com.android.settings.core.PreferenceController;
 
-public class DozeAlwaysOnPreferenceController extends PreferenceController implements
-        Preference.OnPreferenceChangeListener {
+public class AmbientDisplayAlwaysOnPreferenceController extends PreferenceController
+        implements Preference.OnPreferenceChangeListener {
 
-    private static final String KEY_DOZE_ALWAYS_ON = "doze_always_on";
+    private static final String KEY_ALWAYS_ON = "ambient_display_always_on";
     private static final int MY_USER = UserHandle.myUserId();
 
     private final AmbientDisplayConfiguration mConfig;
 
-    public DozeAlwaysOnPreferenceController(Context context, AmbientDisplayConfiguration config) {
+    public AmbientDisplayAlwaysOnPreferenceController(Context context,
+            AmbientDisplayConfiguration config) {
         super(context);
         mConfig = config;
     }
 
     @Override
     public String getPreferenceKey() {
-        return KEY_DOZE_ALWAYS_ON;
+        return KEY_ALWAYS_ON;
     }
 
     @Override
diff --git a/src/com/android/settings/display/DozePreferenceController.java b/src/com/android/settings/display/AmbientDisplayNotificationsPreferenceController.java
similarity index 81%
rename from src/com/android/settings/display/DozePreferenceController.java
rename to src/com/android/settings/display/AmbientDisplayNotificationsPreferenceController.java
index 36c850e..9e15afb 100644
--- a/src/com/android/settings/display/DozePreferenceController.java
+++ b/src/com/android/settings/display/AmbientDisplayNotificationsPreferenceController.java
@@ -27,18 +27,18 @@
 import static android.provider.Settings.Secure.DOZE_ENABLED;
 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.ACTION_AMBIENT_DISPLAY;
 
-public class DozePreferenceController extends PreferenceController implements
-        Preference.OnPreferenceChangeListener {
+public class AmbientDisplayNotificationsPreferenceController extends PreferenceController
+        implements Preference.OnPreferenceChangeListener {
 
     @VisibleForTesting
-    static final String KEY_DOZE = "doze";
+    static final String KEY_AMBIENT_DISPLAY_NOTIFICATIONS = "ambient_display_notification";
     private static final int MY_USER = UserHandle.myUserId();
 
     private final MetricsFeatureProvider mMetricsFeatureProvider;
     private final AmbientDisplayConfiguration mConfig;
 
-    public DozePreferenceController(Context context, AmbientDisplayConfiguration config,
-            MetricsFeatureProvider metricsFeatureProvider) {
+    public AmbientDisplayNotificationsPreferenceController(Context context,
+            AmbientDisplayConfiguration config, MetricsFeatureProvider metricsFeatureProvider) {
         super(context);
         mMetricsFeatureProvider = metricsFeatureProvider;
         mConfig = config;
@@ -46,12 +46,12 @@
 
     @Override
     public String getPreferenceKey() {
-        return KEY_DOZE;
+        return KEY_AMBIENT_DISPLAY_NOTIFICATIONS;
     }
 
     @Override
     public boolean handlePreferenceTreeClick(Preference preference) {
-        if (KEY_DOZE.equals(preference.getKey())) {
+        if (KEY_AMBIENT_DISPLAY_NOTIFICATIONS.equals(preference.getKey())) {
             mMetricsFeatureProvider.action(mContext, ACTION_AMBIENT_DISPLAY);
         }
         return false;
diff --git a/src/com/android/settings/display/AmbientDisplayPreferenceController.java b/src/com/android/settings/display/AmbientDisplayPreferenceController.java
new file mode 100644
index 0000000..f3e3046
--- /dev/null
+++ b/src/com/android/settings/display/AmbientDisplayPreferenceController.java
@@ -0,0 +1,64 @@
+/*
+ * 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.display;
+
+import android.content.Context;
+import android.os.UserHandle;
+import android.support.v7.preference.Preference;
+
+import com.android.internal.app.NightDisplayController;
+import com.android.internal.hardware.AmbientDisplayConfiguration;
+import com.android.settings.R;
+import com.android.settings.core.PreferenceController;
+
+public class AmbientDisplayPreferenceController extends PreferenceController {
+
+    private static final int MY_USER_ID = UserHandle.myUserId();
+
+    private final AmbientDisplayConfiguration mConfig;
+    private final String mKey;
+
+    public AmbientDisplayPreferenceController(Context context, AmbientDisplayConfiguration config,
+            String key) {
+        super(context);
+        mConfig = config;
+        mKey = key;
+    }
+
+    @Override
+    public boolean isAvailable() {
+        return mConfig.available();
+    }
+
+    @Override
+    public void updateState(Preference preference) {
+        super.updateState(preference);
+        if (mConfig.alwaysOnEnabled(MY_USER_ID)) {
+            preference.setSummary(R.string.ambient_display_screen_summary_always_on);
+        } else if (mConfig.pulseOnNotificationEnabled(MY_USER_ID)) {
+            preference.setSummary(R.string.ambient_display_screen_summary_notifications);
+        } else if (mConfig.enabled(MY_USER_ID)) {
+            preference.setSummary(R.string.switch_on_text);
+        } else {
+            preference.setSummary(R.string.switch_off_text);
+        }
+    }
+
+    @Override
+    public String getPreferenceKey() {
+        return mKey;
+    }
+}
diff --git a/src/com/android/settings/display/AmbientDisplaySettings.java b/src/com/android/settings/display/AmbientDisplaySettings.java
new file mode 100644
index 0000000..011cccb
--- /dev/null
+++ b/src/com/android/settings/display/AmbientDisplaySettings.java
@@ -0,0 +1,107 @@
+/*
+ * 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.display;
+
+import android.content.Context;
+import android.os.Bundle;
+import android.os.UserHandle;
+import android.provider.SearchIndexableResource;
+
+import com.android.internal.hardware.AmbientDisplayConfiguration;
+import com.android.internal.logging.nano.MetricsProto;
+import com.android.settings.R;
+import com.android.settings.core.PreferenceController;
+import com.android.settings.core.instrumentation.MetricsFeatureProvider;
+import com.android.settings.dashboard.DashboardFragment;
+import com.android.settings.gestures.DoubleTapScreenPreferenceController;
+import com.android.settings.gestures.PickupGesturePreferenceController;
+import com.android.settings.search.BaseSearchIndexProvider;
+import com.android.settings.search.Indexable;
+import com.android.settingslib.core.lifecycle.Lifecycle;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Settings screen for Ambient display.
+ */
+public class AmbientDisplaySettings extends DashboardFragment {
+
+    private static final String TAG = "AmbientDisplaySettings";
+    private static final int MY_USER_ID = UserHandle.myUserId();
+
+    private static final String KEY_AMBIENT_DISPLAY_ALWAYS_ON = "ambient_display_always_on";
+    private static final String KEY_AMBIENT_DISPLAY_DOUBLE_TAP = "ambient_display_double_tap";
+    private static final String KEY_AMBIENT_DISPLAY_PICK_UP = "ambient_display_pick_up";
+    private static final String KEY_AMBIENT_DISPLAY_NOTIFICATION = "ambient_display_notification";
+
+    private static List<PreferenceController> buildPreferenceControllers(Context context,
+            Lifecycle lifecycle, AmbientDisplayConfiguration config,
+            MetricsFeatureProvider metricsFeatureProvider) {
+        final List<PreferenceController> controllers = new ArrayList<>();
+        controllers.add(new AmbientDisplayNotificationsPreferenceController(context, config,
+                metricsFeatureProvider));
+        controllers.add(new AmbientDisplayAlwaysOnPreferenceController(context, config));
+        controllers.add(new DoubleTapScreenPreferenceController(context, lifecycle, config,
+                MY_USER_ID, KEY_AMBIENT_DISPLAY_DOUBLE_TAP));
+        controllers.add(new PickupGesturePreferenceController(context, lifecycle, config,
+                MY_USER_ID, KEY_AMBIENT_DISPLAY_PICK_UP));
+        return controllers;
+    }
+
+
+    @Override
+    protected String getLogTag() {
+        return TAG;
+    }
+
+    @Override
+    protected int getPreferenceScreenResId() {
+        return R.xml.ambient_display_settings;
+    }
+
+    @Override
+    protected List<PreferenceController> getPreferenceControllers(Context context) {
+        return buildPreferenceControllers(context, getLifecycle(),
+                new AmbientDisplayConfiguration(context), mMetricsFeatureProvider);
+    }
+
+    @Override
+    public int getMetricsCategory() {
+        return MetricsProto.MetricsEvent.AMBIENT_DISPLAY_SETTINGS;
+    }
+
+    public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
+            new BaseSearchIndexProvider() {
+                @Override
+                public List<SearchIndexableResource> getXmlResourcesToIndex(Context context,
+                        boolean enabled) {
+                    final ArrayList<SearchIndexableResource> result = new ArrayList<>();
+
+                    final SearchIndexableResource sir = new SearchIndexableResource(context);
+                    sir.xmlResId = R.xml.ambient_display_settings;
+                    result.add(sir);
+                    return result;
+                }
+
+                @Override
+                public List<PreferenceController> getPreferenceControllers(Context context) {
+                    return buildPreferenceControllers(context, null,
+                            new AmbientDisplayConfiguration(context), null);
+                }
+            };
+}
diff --git a/src/com/android/settings/fingerprint/FingerprintEnrollFindSensor.java b/src/com/android/settings/fingerprint/FingerprintEnrollFindSensor.java
index 2aad313..e34a90b 100644
--- a/src/com/android/settings/fingerprint/FingerprintEnrollFindSensor.java
+++ b/src/com/android/settings/fingerprint/FingerprintEnrollFindSensor.java
@@ -20,6 +20,8 @@
 import android.hardware.fingerprint.FingerprintManager;
 import android.os.Bundle;
 import android.os.UserHandle;
+import android.support.annotation.Nullable;
+import android.view.View;
 
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.settings.R;
@@ -36,6 +38,7 @@
     private static final int ENROLLING = 2;
     public static final String EXTRA_KEY_LAUNCHED_CONFIRM = "launched_confirm_lock";
 
+    @Nullable
     private FingerprintFindSensorAnimation mAnimation;
     private boolean mLaunchedConfirmLock;
     private FingerprintEnrollSidecar mSidecar;
@@ -56,8 +59,12 @@
         } else if (mToken != null) {
             startLookingForFingerprint(); // already confirmed, so start looking for fingerprint
         }
-        mAnimation = (FingerprintFindSensorAnimation) findViewById(
-                R.id.fingerprint_sensor_location_animation);
+        View animationView = findViewById(R.id.fingerprint_sensor_location_animation);
+        if (animationView instanceof FingerprintFindSensorAnimation) {
+            mAnimation = (FingerprintFindSensorAnimation) animationView;
+        } else {
+            mAnimation = null;
+        }
     }
 
     protected int getContentView() {
@@ -67,7 +74,9 @@
     @Override
     protected void onStart() {
         super.onStart();
-        mAnimation.startAnimation();
+        if (mAnimation != null) {
+            mAnimation.startAnimation();
+        }
     }
 
     private void startLookingForFingerprint() {
@@ -102,13 +111,17 @@
     @Override
     protected void onStop() {
         super.onStop();
-        mAnimation.pauseAnimation();
+        if (mAnimation != null) {
+            mAnimation.pauseAnimation();
+        }
     }
 
     @Override
     protected void onDestroy() {
         super.onDestroy();
-        mAnimation.stopAnimation();
+        if (mAnimation != null) {
+            mAnimation.stopAnimation();
+        }
     }
 
     @Override
diff --git a/src/com/android/settings/fuelgauge/AppButtonsPreferenceController.java b/src/com/android/settings/fuelgauge/AppButtonsPreferenceController.java
index f4f6c36..6b4c8a9 100644
--- a/src/com/android/settings/fuelgauge/AppButtonsPreferenceController.java
+++ b/src/com/android/settings/fuelgauge/AppButtonsPreferenceController.java
@@ -98,6 +98,8 @@
     @VisibleForTesting
     Button mUninstallButton;
     @VisibleForTesting
+    String mPackageName;
+    @VisibleForTesting
     boolean mDisableAfterUninstall = false;
 
     private final int mRequestUninstall;
@@ -113,7 +115,6 @@
     private MetricsFeatureProvider mMetricsFeatureProvider;
 
     private LayoutPreference mButtonsPref;
-    private String mPackageName;
     private int mUserId;
     private boolean mUpdatedSysApp = false;
     private boolean mListeningToPackageRemove = false;
@@ -134,7 +135,6 @@
         mMetricsFeatureProvider = FeatureFactory.getFactory(activity).getMetricsFeatureProvider();
 
         mState = state;
-        mSession = mState.newSession(this);
         mDpm = dpm;
         mUserManager = userManager;
         mPm = packageManager;
@@ -145,10 +145,10 @@
         mRequestUninstall = requestUninstall;
         mRequestRemoveDeviceAdmin = requestRemoveDeviceAdmin;
 
-        lifecycle.addObserver(this);
-
         if (packageName != null) {
             mAppEntry = mState.getEntry(packageName, mUserId);
+            mSession = mState.newSession(this);
+            lifecycle.addObserver(this);
         } else {
             mFinishing = true;
         }
@@ -620,7 +620,11 @@
         return false;
     }
 
-    private boolean refreshUi() {
+    @VisibleForTesting
+    boolean refreshUi() {
+        if (mPackageName == null) {
+            return false;
+        }
         retrieveAppEntry();
         if (mAppEntry == null || mPackageInfo == null) {
             return false;
diff --git a/src/com/android/settings/fuelgauge/BatteryUtils.java b/src/com/android/settings/fuelgauge/BatteryUtils.java
index 327d3a4..194b2fb 100644
--- a/src/com/android/settings/fuelgauge/BatteryUtils.java
+++ b/src/com/android/settings/fuelgauge/BatteryUtils.java
@@ -33,6 +33,8 @@
 
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
+import java.util.Collections;
+import java.util.Comparator;
 import java.util.List;
 
 /**
@@ -219,7 +221,7 @@
      * Calculate the whole running time in the state {@code statsType}
      *
      * @param batteryStatsHelper utility class that contains the data
-     * @param statsType state that we want to calculate the time for
+     * @param statsType          state that we want to calculate the time for
      * @return the running time in millis
      */
     public long calculateRunningTimeBasedOnStatsType(BatteryStatsHelper batteryStatsHelper,
@@ -247,6 +249,18 @@
         return ArrayUtils.isEmpty(packageNames) ? null : packageNames[0];
     }
 
+    /**
+     * Sort the {@code usageList} based on {@link BatterySipper#totalPowerMah}
+     */
+    public void sortUsageList(List<BatterySipper> usageList) {
+        Collections.sort(usageList, new Comparator<BatterySipper>() {
+            @Override
+            public int compare(BatterySipper a, BatterySipper b) {
+                return Double.compare(b.totalPowerMah, a.totalPowerMah);
+            }
+        });
+    }
+
     private long convertUsToMs(long timeUs) {
         return timeUs / 1000;
     }
diff --git a/src/com/android/settings/fuelgauge/PowerUsageFeatureProviderImpl.java b/src/com/android/settings/fuelgauge/PowerUsageFeatureProviderImpl.java
index 2cc6899..5ef6fe5 100644
--- a/src/com/android/settings/fuelgauge/PowerUsageFeatureProviderImpl.java
+++ b/src/com/android/settings/fuelgauge/PowerUsageFeatureProviderImpl.java
@@ -80,12 +80,12 @@
 
     @Override
     public boolean isAdvancedUiEnabled() {
-        return false;
+        return true;
     }
 
     @Override
     public boolean isPowerAccountingToggleEnabled() {
-        return false;
+        return true;
     }
 
     @Override
diff --git a/src/com/android/settings/fuelgauge/PowerUsageSummary.java b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
index de80d3b..275b78c 100644
--- a/src/com/android/settings/fuelgauge/PowerUsageSummary.java
+++ b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
@@ -77,8 +77,6 @@
 
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collections;
-import java.util.Comparator;
 import java.util.List;
 
 /**
@@ -399,7 +397,7 @@
      *
      * @return A sorted list of apps using power.
      */
-    private static List<BatterySipper> getCoalescedUsageList(final List<BatterySipper> sippers) {
+    private List<BatterySipper> getCoalescedUsageList(final List<BatterySipper> sippers) {
         final SparseArray<BatterySipper> uidList = new SparseArray<>();
 
         final ArrayList<BatterySipper> results = new ArrayList<>();
@@ -474,12 +472,7 @@
         }
 
         // The sort order must have changed, so re-sort based on total power use.
-        Collections.sort(results, new Comparator<BatterySipper>() {
-            @Override
-            public int compare(BatterySipper a, BatterySipper b) {
-                return Double.compare(b.totalPowerMah, a.totalPowerMah);
-            }
-        });
+        mBatteryUtils.sortUsageList(results);
         return results;
     }
 
@@ -531,9 +524,9 @@
         if (averagePower >= MIN_AVERAGE_POWER_THRESHOLD_MILLI_AMP || USE_FAKE_DATA) {
             final List<BatterySipper> usageList = getCoalescedUsageList(
                     USE_FAKE_DATA ? getFakeStats() : mStatsHelper.getUsageList());
-
             double hiddenPowerMah = mShowAllApps ? 0 :
                     mBatteryUtils.removeHiddenBatterySippers(usageList);
+            mBatteryUtils.sortUsageList(usageList);
 
             final int numSippers = usageList.size();
             for (int i = 0; i < numSippers; i++) {
diff --git a/src/com/android/settings/gestures/AssistGestureSettings.java b/src/com/android/settings/gestures/AssistGestureSettings.java
index a080bec..64187a3 100644
--- a/src/com/android/settings/gestures/AssistGestureSettings.java
+++ b/src/com/android/settings/gestures/AssistGestureSettings.java
@@ -38,7 +38,7 @@
 
     @Override
     public int getMetricsCategory() {
-        return MetricsProto.MetricsEvent.VIEW_UNKNOWN;
+        return MetricsProto.MetricsEvent.SETTINGS_ASSIST_GESTURE;
     }
 
     @Override
diff --git a/src/com/android/settings/network/TetherPreferenceController.java b/src/com/android/settings/network/TetherPreferenceController.java
index 58d45d6..31a8526 100644
--- a/src/com/android/settings/network/TetherPreferenceController.java
+++ b/src/com/android/settings/network/TetherPreferenceController.java
@@ -18,7 +18,10 @@
 import android.bluetooth.BluetoothAdapter;
 import android.bluetooth.BluetoothPan;
 import android.bluetooth.BluetoothProfile;
+import android.content.BroadcastReceiver;
 import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
 import android.database.ContentObserver;
 import android.net.ConnectivityManager;
 import android.net.Uri;
@@ -67,6 +70,7 @@
 
     private SettingObserver mAirplaneModeObserver;
     private Preference mPreference;
+    private TetherBroadcastReceiver mTetherReceiver;
 
     @VisibleForTesting(otherwise = VisibleForTesting.NONE)
     TetherPreferenceController() {
@@ -131,6 +135,11 @@
         if (mAirplaneModeObserver == null) {
             mAirplaneModeObserver = new SettingObserver();
         }
+        if (mTetherReceiver == null) {
+            mTetherReceiver = new TetherBroadcastReceiver();
+        }
+        mContext.registerReceiver(
+            mTetherReceiver, new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
         mContext.getContentResolver()
                 .registerContentObserver(mAirplaneModeObserver.uri, false, mAirplaneModeObserver);
     }
@@ -140,6 +149,9 @@
         if (mAirplaneModeObserver != null) {
             mContext.getContentResolver().unregisterContentObserver(mAirplaneModeObserver);
         }
+        if (mTetherReceiver != null) {
+            mContext.unregisterReceiver(mTetherReceiver);
+        }
     }
 
     @Override
@@ -238,4 +250,14 @@
             }
         }
     }
+
+    @VisibleForTesting
+    class TetherBroadcastReceiver extends BroadcastReceiver {
+
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            updateSummary();
+        }
+
+    }
 }
diff --git a/src/com/android/settings/notification/AppNotificationSettings.java b/src/com/android/settings/notification/AppNotificationSettings.java
index e7be62f..4cbe692 100644
--- a/src/com/android/settings/notification/AppNotificationSettings.java
+++ b/src/com/android/settings/notification/AppNotificationSettings.java
@@ -201,7 +201,8 @@
             final NotificationChannel channel) {
         MasterSwitchPreference channelPref = new MasterSwitchPreference(
                 getPrefContext());
-        channelPref.setSwitchEnabled(mSuspendedAppsAdmin == null && !mAppRow.systemApp);
+        channelPref.setSwitchEnabled(mSuspendedAppsAdmin == null
+                &&  isChannelBlockable(mAppRow.systemApp, channel));
         channelPref.setKey(channel.getId());
         channelPref.setTitle(channel.getName());
         channelPref.setChecked(channel.getImportance() != IMPORTANCE_NONE);
diff --git a/src/com/android/settings/notification/ChannelNotificationSettings.java b/src/com/android/settings/notification/ChannelNotificationSettings.java
index f7bf1ca..6b4129c 100644
--- a/src/com/android/settings/notification/ChannelNotificationSettings.java
+++ b/src/com/android/settings/notification/ChannelNotificationSettings.java
@@ -228,7 +228,7 @@
         mBlockBar.setKey(KEY_BLOCK);
         getPreferenceScreen().addPreference(mBlockBar);
 
-        if (mAppRow.systemApp && mChannel.getImportance() != NotificationManager.IMPORTANCE_NONE) {
+        if (!isChannelBlockable(mAppRow.systemApp, mChannel)) {
             setVisible(mBlockBar, false);
         }
 
diff --git a/src/com/android/settings/notification/ConfigureNotificationSettings.java b/src/com/android/settings/notification/ConfigureNotificationSettings.java
index 3e363d7..26fc0a0 100644
--- a/src/com/android/settings/notification/ConfigureNotificationSettings.java
+++ b/src/com/android/settings/notification/ConfigureNotificationSettings.java
@@ -69,7 +69,10 @@
         final PulseNotificationPreferenceController pulseController =
                 new PulseNotificationPreferenceController(context);
         final LockScreenNotificationPreferenceController lockScreenNotificationController =
-                new LockScreenNotificationPreferenceController(context);
+                new LockScreenNotificationPreferenceController(context,
+                        "lock_screen_notifications",
+                        "lock_screen_notifications_profile_header",
+                        "lock_screen_notifications_profile");
         if (lifecycle != null) {
             lifecycle.addObserver(pulseController);
             lifecycle.addObserver(lockScreenNotificationController);
diff --git a/src/com/android/settings/notification/LockScreenNotificationPreferenceController.java b/src/com/android/settings/notification/LockScreenNotificationPreferenceController.java
index b84d961..228e185 100644
--- a/src/com/android/settings/notification/LockScreenNotificationPreferenceController.java
+++ b/src/com/android/settings/notification/LockScreenNotificationPreferenceController.java
@@ -26,6 +26,7 @@
 import android.provider.Settings;
 import android.support.v7.preference.Preference;
 import android.support.v7.preference.PreferenceScreen;
+import android.text.TextUtils;
 import android.util.Log;
 
 import com.android.internal.widget.LockPatternUtils;
@@ -46,11 +47,10 @@
         Preference.OnPreferenceChangeListener, LifecycleObserver, OnResume, OnPause {
 
     private static final String TAG = "LockScreenNotifPref";
-    private static final String KEY_LOCK_SCREEN_NOTIFICATIONS = "lock_screen_notifications";
-    private static final String KEY_LOCK_SCREEN_PROFILE_HEADER =
-            "lock_screen_notifications_profile_header";
-    private static final String KEY_LOCK_SCREEN_PROFILE_NOTIFICATIONS =
-            "lock_screen_notifications_profile";
+
+    private final String mSettingKey;
+    private final String mWorkSettingCategoryKey;
+    private final String mWorkSettingKey;
 
     private RestrictedDropDownPreference mLockscreen;
     private RestrictedDropDownPreference mLockscreenProfile;
@@ -64,7 +64,16 @@
     private int mLockscreenSelectedValueProfile;
 
     public LockScreenNotificationPreferenceController(Context context) {
+        this(context, null, null, null);
+    }
+
+    public LockScreenNotificationPreferenceController(Context context,
+            String settingKey, String workSettingCategoryKey, String workSettingKey) {
         super(context);
+        mSettingKey = settingKey;
+        mWorkSettingCategoryKey = workSettingCategoryKey;
+        mWorkSettingKey = workSettingKey;
+
         mProfileChallengeUserId = Utils.getManagedProfileId(
                 UserManager.get(context), UserHandle.myUserId());
         final LockPatternUtils utils = new LockPatternUtils(context);
@@ -79,17 +88,17 @@
     public void displayPreference(PreferenceScreen screen) {
         super.displayPreference(screen);
         mLockscreen =
-                (RestrictedDropDownPreference) screen.findPreference(KEY_LOCK_SCREEN_NOTIFICATIONS);
+                (RestrictedDropDownPreference) screen.findPreference(mSettingKey);
         if (mLockscreen == null) {
-            Log.i(TAG, "Preference not found: " + KEY_LOCK_SCREEN_NOTIFICATIONS);
+            Log.i(TAG, "Preference not found: " + mSettingKey);
             return;
         }
         if (mProfileChallengeUserId != UserHandle.USER_NULL) {
             mLockscreenProfile = (RestrictedDropDownPreference) screen.findPreference(
-                    KEY_LOCK_SCREEN_PROFILE_NOTIFICATIONS);
+                    mWorkSettingKey);
         } else {
-            removePreference(screen, KEY_LOCK_SCREEN_PROFILE_NOTIFICATIONS);
-            removePreference(screen, KEY_LOCK_SCREEN_PROFILE_HEADER);
+            removePreference(screen, mWorkSettingKey);
+            removePreference(screen, mWorkSettingCategoryKey);
         }
         mSettingObserver = new SettingObserver();
         initLockScreenNotificationPrefDisplay();
@@ -136,7 +145,7 @@
 
     private void initLockscreenNotificationPrefForProfile() {
         if (mLockscreenProfile == null) {
-            Log.i(TAG, "Preference not found: " + KEY_LOCK_SCREEN_PROFILE_NOTIFICATIONS);
+            Log.i(TAG, "Preference not found: " + mWorkSettingKey);
             return;
         }
         ArrayList<CharSequence> entries = new ArrayList<>();
@@ -205,8 +214,8 @@
 
     @Override
     public boolean onPreferenceChange(Preference preference, Object newValue) {
-        switch (preference.getKey()) {
-            case KEY_LOCK_SCREEN_PROFILE_NOTIFICATIONS: {
+        final String key = preference.getKey();
+        if (TextUtils.equals(mWorkSettingKey, key)) {
                 final int val = Integer.parseInt((String) newValue);
                 if (val == mLockscreenSelectedValueProfile) {
                     return false;
@@ -223,8 +232,7 @@
                         enabled ? 1 : 0, mProfileChallengeUserId);
                 mLockscreenSelectedValueProfile = val;
                 return true;
-            }
-            case KEY_LOCK_SCREEN_NOTIFICATIONS: {
+        } else if (TextUtils.equals(mSettingKey, key)) {
                 final int val = Integer.parseInt((String) newValue);
                 if (val == mLockscreenSelectedValue) {
                     return false;
@@ -238,10 +246,8 @@
                         Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, enabled ? 1 : 0);
                 mLockscreenSelectedValue = val;
                 return true;
-            }
-            default:
-                return false;
         }
+        return false;
     }
 
     private void setRestrictedIfNotificationFeaturesDisabled(CharSequence entry,
@@ -295,6 +301,7 @@
         final boolean enabled = getLockscreenNotificationsEnabled(mProfileChallengeUserId);
         final boolean allowPrivate = !mSecureProfile
                 || getLockscreenAllowPrivateNotifications(mProfileChallengeUserId);
+        mLockscreenProfile.setSummary("%s");
         mLockscreenSelectedValueProfile = !enabled
                 ? R.string.lock_screen_notifications_summary_disable_profile
                 : (allowPrivate ? R.string.lock_screen_notifications_summary_show_profile
diff --git a/src/com/android/settings/notification/NotificationSettingsBase.java b/src/com/android/settings/notification/NotificationSettingsBase.java
index e055133..fe426e7 100644
--- a/src/com/android/settings/notification/NotificationSettingsBase.java
+++ b/src/com/android/settings/notification/NotificationSettingsBase.java
@@ -443,4 +443,12 @@
 
         return lockscreenSecure;
     }
+
+    protected boolean isChannelBlockable(boolean systemApp, NotificationChannel channel) {
+        if (!mAppRow.systemApp) {
+            return true;
+        }
+        return channel.isBlockableSystem()
+                || channel.getImportance() == NotificationManager.IMPORTANCE_NONE;
+    }
 }
diff --git a/src/com/android/settings/password/ChooseLockPassword.java b/src/com/android/settings/password/ChooseLockPassword.java
index df0621e..5f1c949 100644
--- a/src/com/android/settings/password/ChooseLockPassword.java
+++ b/src/com/android/settings/password/ChooseLockPassword.java
@@ -185,8 +185,8 @@
         private ChooseLockSettingsHelper mChooseLockSettingsHelper;
         private Stage mUiStage = Stage.Introduction;
         private PasswordRequirementAdapter mPasswordRequirementAdapter;
+        private GlifLayout mLayout;
 
-        private TextView mHeaderText;
         private String mFirstPin;
         private RecyclerView mPasswordRestrictionView;
         protected boolean mIsAlphaMode;
@@ -292,6 +292,8 @@
         public void onViewCreated(View view, Bundle savedInstanceState) {
             super.onViewCreated(view, savedInstanceState);
 
+            mLayout = (GlifLayout) view;
+
             // Make the password container consume the optical insets so the edit text is aligned
             // with the sides of the parent visually.
             ViewGroup container = view.findViewById(R.id.password_container);
@@ -316,7 +318,6 @@
             mPasswordEntryInputDisabler = new TextViewInputDisabler(mPasswordEntry);
 
             final Activity activity = getActivity();
-            mHeaderText = (TextView) view.findViewById(R.id.headerText);
 
             int currentType = mPasswordEntry.getInputType();
             mPasswordEntry.setInputType(mIsAlphaMode ? currentType
@@ -360,7 +361,7 @@
                         : R.string.lockpassword_choose_your_pin_header;
                 CharSequence title = getText(id);
                 sa.setTitle(title);
-                ((GlifLayout) view).setHeaderText(title);
+                mLayout.setHeaderText(title);
             }
         }
 
@@ -479,7 +480,7 @@
             // If the stage changed, announce the header for accessibility. This
             // is a no-op when accessibility is disabled.
             if (previousStage != stage) {
-                mHeaderText.announceForAccessibility(mHeaderText.getText());
+                mLayout.announceForAccessibility(mLayout.getHeaderText());
             }
         }
 
@@ -788,11 +789,11 @@
 
         private void setHeaderText(String text) {
             // Only set the text if it is different than the existing one to avoid announcing again.
-            if (!TextUtils.isEmpty(mHeaderText.getText())
-                    && mHeaderText.getText().toString().equals(text)) {
+            if (!TextUtils.isEmpty(mLayout.getHeaderText())
+                    && mLayout.getHeaderText().toString().equals(text)) {
                 return;
             }
-            mHeaderText.setText(text);
+            mLayout.setHeaderText(text);
         }
 
         public void afterTextChanged(Editable s) {
diff --git a/src/com/android/settings/password/ChooseLockSettingsHelper.java b/src/com/android/settings/password/ChooseLockSettingsHelper.java
index 8c73355..95f5a54 100644
--- a/src/com/android/settings/password/ChooseLockSettingsHelper.java
+++ b/src/com/android/settings/password/ChooseLockSettingsHelper.java
@@ -19,10 +19,13 @@
 import android.annotation.Nullable;
 import android.app.Activity;
 import android.app.Fragment;
+import android.app.KeyguardManager;
 import android.app.admin.DevicePolicyManager;
+import android.content.Context;
 import android.content.Intent;
 import android.content.IntentSender;
 import android.os.UserManager;
+import android.provider.Settings;
 
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.widget.LockPatternUtils;
@@ -202,6 +205,21 @@
             @Nullable CharSequence header, @Nullable CharSequence description,
             boolean returnCredentials, boolean external, boolean hasChallenge,
             long challenge, int userId) {
+        return launchConfirmationActivity(request, title, header, description, returnCredentials,
+                external, hasChallenge, challenge, userId, null /* alternateButton */);
+    }
+
+    public boolean launchFrpConfirmationActivity(int request, @Nullable CharSequence header,
+            @Nullable CharSequence description, @Nullable CharSequence alternateButton) {
+        return launchConfirmationActivity(request, null /* title */, header, description,
+                false /* returnCredentials */, true /* external */, false /* hasChallenge */,
+                0 /* challenge */, LockPatternUtils.USER_FRP, alternateButton);
+    }
+
+    private boolean launchConfirmationActivity(int request, @Nullable CharSequence title,
+            @Nullable CharSequence header, @Nullable CharSequence description,
+            boolean returnCredentials, boolean external, boolean hasChallenge,
+            long challenge, int userId, @Nullable CharSequence alternateButton) {
         final int effectiveUserId = UserManager.get(mActivity).getCredentialOwnerProfile(userId);
         boolean launched = false;
 
@@ -211,7 +229,7 @@
                         returnCredentials || hasChallenge
                                 ? ConfirmLockPattern.InternalActivity.class
                                 : ConfirmLockPattern.class, returnCredentials, external,
-                                hasChallenge, challenge, userId);
+                                hasChallenge, challenge, userId, alternateButton);
                 break;
             case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
             case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
@@ -223,7 +241,7 @@
                         returnCredentials || hasChallenge
                                 ? ConfirmLockPassword.InternalActivity.class
                                 : ConfirmLockPassword.class, returnCredentials, external,
-                                hasChallenge, challenge, userId);
+                                hasChallenge, challenge, userId, alternateButton);
                 break;
         }
         return launched;
@@ -232,7 +250,7 @@
     private boolean launchConfirmationActivity(int request, CharSequence title, CharSequence header,
             CharSequence message, Class<?> activityClass, boolean returnCredentials,
             boolean external, boolean hasChallenge, long challenge,
-            int userId) {
+            int userId, @Nullable CharSequence alternateButton) {
         final Intent intent = new Intent();
         intent.putExtra(ConfirmDeviceCredentialBaseFragment.TITLE_TEXT, title);
         intent.putExtra(ConfirmDeviceCredentialBaseFragment.HEADER_TEXT, header);
@@ -247,6 +265,7 @@
         // we should never have a drawer when confirming device credentials.
         intent.putExtra(SettingsActivity.EXTRA_HIDE_DRAWER, true);
         intent.putExtra(Intent.EXTRA_USER_ID, userId);
+        intent.putExtra(KeyguardManager.EXTRA_ALTERNATE_BUTTON_LABEL, alternateButton);
         intent.setClassName(ConfirmDeviceCredentialBaseFragment.PACKAGE, activityClass.getName());
         if (external) {
             intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
diff --git a/src/com/android/settings/password/ChooseLockTypeDialogFragment.java b/src/com/android/settings/password/ChooseLockTypeDialogFragment.java
index 2581483..ba69e64 100644
--- a/src/com/android/settings/password/ChooseLockTypeDialogFragment.java
+++ b/src/com/android/settings/password/ChooseLockTypeDialogFragment.java
@@ -16,6 +16,7 @@
 
 package com.android.settings.password;
 
+import android.app.AlertDialog;
 import android.app.AlertDialog.Builder;
 import android.app.Dialog;
 import android.app.Fragment;
@@ -23,6 +24,7 @@
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.DialogInterface.OnClickListener;
+import android.graphics.drawable.Drawable;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -31,6 +33,7 @@
 import android.widget.TextView;
 
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.settings.R;
 import com.android.settings.core.instrumentation.InstrumentedDialogFragment;
 
 import java.util.List;
@@ -99,7 +102,9 @@
         }
         mAdapter = new ScreenLockAdapter(context, locks, mController);
         builder.setAdapter(mAdapter, this);
-        return builder.create();
+        builder.setTitle(R.string.setup_lock_settings_options_dialog_title);
+        AlertDialog alertDialog = builder.create();
+        return alertDialog;
     }
 
     @Override
@@ -115,18 +120,39 @@
                 Context context,
                 List<ScreenLockType> locks,
                 ChooseLockGenericController controller) {
-            super(context, android.R.layout.simple_list_item_1, locks);
+            super(context, R.layout.choose_lock_dialog_item, locks);
             mController = controller;
         }
 
         @Override
         public View getView(int position, View view, ViewGroup parent) {
+            Context context = parent.getContext();
             if (view == null) {
-                view = LayoutInflater.from(parent.getContext())
-                        .inflate(android.R.layout.simple_list_item_1, parent, false);
+                view = LayoutInflater.from(context)
+                        .inflate(R.layout.choose_lock_dialog_item, parent, false);
             }
-            ((TextView) view).setText(mController.getTitle(getItem(position)));
+            ScreenLockType lock = getItem(position);
+            TextView textView = (TextView) view;
+            textView.setText(mController.getTitle(lock));
+            textView.setCompoundDrawablesRelativeWithIntrinsicBounds(
+                    getIconForScreenLock(context, lock), null, null, null);
             return view;
         }
+
+        private static Drawable getIconForScreenLock(Context context, ScreenLockType lock) {
+            switch (lock) {
+                case PATTERN:
+                    return context.getDrawable(R.drawable.ic_pattern);
+                case PIN:
+                    return context.getDrawable(R.drawable.ic_pin);
+                case PASSWORD:
+                    return context.getDrawable(R.drawable.ic_password);
+                case NONE:
+                case SWIPE:
+                case MANAGED:
+                default:
+                        return null;
+            }
+        }
     }
 }
diff --git a/src/com/android/settings/password/ConfirmDeviceCredentialActivity.java b/src/com/android/settings/password/ConfirmDeviceCredentialActivity.java
index 38b38fc..65d72f1 100644
--- a/src/com/android/settings/password/ConfirmDeviceCredentialActivity.java
+++ b/src/com/android/settings/password/ConfirmDeviceCredentialActivity.java
@@ -66,6 +66,10 @@
         Intent intent = getIntent();
         String title = intent.getStringExtra(KeyguardManager.EXTRA_TITLE);
         String details = intent.getStringExtra(KeyguardManager.EXTRA_DESCRIPTION);
+        String alternateButton = intent.getStringExtra(
+                KeyguardManager.EXTRA_ALTERNATE_BUTTON_LABEL);
+        boolean frp = KeyguardManager.ACTION_CONFIRM_FRP_CREDENTIAL.equals(intent.getAction());
+
         int userId = Utils.getCredentialOwnerUserId(this);
         if (isInternalActivity()) {
             try {
@@ -86,7 +90,9 @@
         // If the target is a managed user and user key not unlocked yet, we will force unlock
         // tied profile so it will enable work mode and unlock managed profile, when personal
         // challenge is unlocked.
-        if (isManagedProfile && isInternalActivity()
+        if (frp) {
+            launched = helper.launchFrpConfirmationActivity(0, title, details, alternateButton);
+        } else if (isManagedProfile && isInternalActivity()
                 && !lockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
             // We set the challenge as 0L, so it will force to unlock managed profile when it
             // unlocks primary profile screen lock, by calling verifyTiedProfileChallenge()
diff --git a/src/com/android/settings/password/ConfirmDeviceCredentialBaseFragment.java b/src/com/android/settings/password/ConfirmDeviceCredentialBaseFragment.java
index ae2dd42..64f3a6f 100644
--- a/src/com/android/settings/password/ConfirmDeviceCredentialBaseFragment.java
+++ b/src/com/android/settings/password/ConfirmDeviceCredentialBaseFragment.java
@@ -25,12 +25,14 @@
 import android.app.DialogFragment;
 import android.app.FragmentManager;
 import android.app.IActivityManager;
+import android.app.KeyguardManager;
 import android.app.admin.DevicePolicyManager;
 import android.app.trust.TrustManager;
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.IntentSender;
+import android.content.pm.UserInfo;
 import android.graphics.Point;
 import android.graphics.PorterDuff;
 import android.graphics.drawable.ColorDrawable;
@@ -39,6 +41,7 @@
 import android.os.Handler;
 import android.os.RemoteException;
 import android.os.UserManager;
+import android.text.TextUtils;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.Button;
@@ -70,6 +73,10 @@
     public static final String SHOW_WHEN_LOCKED =
             PACKAGE + ".ConfirmCredentials.showWhenLocked";
 
+    protected static final int USER_TYPE_PRIMARY = 1;
+    protected static final int USER_TYPE_MANAGED_PROFILE = 2;
+    protected static final int USER_TYPE_SECONDARY = 3;
+
     private FingerprintUiHelper mFingerprintHelper;
     protected boolean mReturnCredentials = false;
     protected Button mCancelButton;
@@ -78,20 +85,28 @@
     protected int mUserId;
     protected UserManager mUserManager;
     protected LockPatternUtils mLockPatternUtils;
+    protected DevicePolicyManager mDevicePolicyManager;
     protected TextView mErrorTextView;
     protected final Handler mHandler = new Handler();
+    protected boolean mFrp;
+    private CharSequence mFrpAlternateButtonText;
 
     @Override
     public void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
+        mFrpAlternateButtonText = getActivity().getIntent().getCharSequenceExtra(
+                KeyguardManager.EXTRA_ALTERNATE_BUTTON_LABEL);
         mReturnCredentials = getActivity().getIntent().getBooleanExtra(
                 ChooseLockSettingsHelper.EXTRA_KEY_RETURN_CREDENTIALS, false);
         // Only take this argument into account if it belongs to the current profile.
         Intent intent = getActivity().getIntent();
         mUserId = Utils.getUserIdFromBundle(getActivity(), intent.getExtras());
+        mFrp = (mUserId == LockPatternUtils.USER_FRP);
         mUserManager = UserManager.get(getActivity());
         mEffectiveUserId = mUserManager.getCredentialOwnerProfile(mUserId);
         mLockPatternUtils = new LockPatternUtils(getActivity());
+        mDevicePolicyManager = (DevicePolicyManager) getActivity().getSystemService(
+                Context.DEVICE_POLICY_SERVICE);
     }
 
     @Override
@@ -104,10 +119,18 @@
                 (TextView) view.findViewById(R.id.errorText), this, mEffectiveUserId);
         boolean showCancelButton = getActivity().getIntent().getBooleanExtra(
                 SHOW_CANCEL_BUTTON, false);
-        mCancelButton.setVisibility(showCancelButton ? View.VISIBLE : View.GONE);
+        boolean hasAlternateButton = mFrp && !TextUtils.isEmpty(mFrpAlternateButtonText);
+        mCancelButton.setVisibility(showCancelButton || hasAlternateButton
+                ? View.VISIBLE : View.GONE);
+        if (hasAlternateButton) {
+            mCancelButton.setText(mFrpAlternateButtonText);
+        }
         mCancelButton.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
+                if (hasAlternateButton) {
+                    getActivity().setResult(KeyguardManager.RESULT_ALTERNATE);
+                }
                 getActivity().finish();
             }
         });
@@ -122,9 +145,8 @@
     }
 
     private boolean isFingerprintDisabledByAdmin() {
-        DevicePolicyManager dpm = (DevicePolicyManager) getActivity().getSystemService(
-                Context.DEVICE_POLICY_SERVICE);
-        final int disabledFeatures = dpm.getKeyguardDisabledFeatures(null, mEffectiveUserId);
+        final int disabledFeatures =
+                mDevicePolicyManager.getKeyguardDisabledFeatures(null, mEffectiveUserId);
         return (disabledFeatures & DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT) != 0;
     }
 
@@ -132,15 +154,16 @@
     // credential. Otherwise, fingerprint can't unlock fbe/keystore through
     // verifyTiedProfileChallenge. In such case, we also wanna show the user message that
     // fingerprint is disabled due to device restart.
-    protected boolean isFingerprintDisallowedByStrongAuth() {
-        return !(mLockPatternUtils.isFingerprintAllowedForUser(mEffectiveUserId)
-                && mUserManager.isUserUnlocked(mUserId));
+    protected boolean isStrongAuthRequired() {
+        return mFrp
+                || !mLockPatternUtils.isFingerprintAllowedForUser(mEffectiveUserId)
+                || !mUserManager.isUserUnlocked(mUserId);
     }
 
     private boolean isFingerprintAllowed() {
         return !mReturnCredentials
                 && getActivity().getIntent().getBooleanExtra(ALLOW_FP_AUTHENTICATION, false)
-                && !isFingerprintDisallowedByStrongAuth()
+                && !isStrongAuthRequired()
                 && !isFingerprintDisabledByAdmin();
     }
 
@@ -158,10 +181,7 @@
                 mFingerprintHelper.stopListening();
             }
         }
-        if (isProfileChallenge()) {
-            updateErrorMessage(mLockPatternUtils.getCurrentFailedPasswordAttempts(
-                    mEffectiveUserId));
-        }
+        updateErrorMessage(mLockPatternUtils.getCurrentFailedPasswordAttempts(mEffectiveUserId));
     }
 
     protected void setAccessibilityTitle(CharSequence supplementalText) {
@@ -245,9 +265,8 @@
             mainContent.setPadding(0, 0, 0, 0);
         }
 
-        DevicePolicyManager dpm = (DevicePolicyManager) getActivity().getSystemService(
-                Context.DEVICE_POLICY_SERVICE);
-        baseView.setBackground(new ColorDrawable(dpm.getOrganizationColorForUser(userId)));
+        baseView.setBackground(
+                new ColorDrawable(mDevicePolicyManager.getOrganizationColorForUser(userId)));
         ImageView imageView = (ImageView) baseView.findViewById(R.id.background_image);
         if (imageView != null) {
             Drawable image = getResources().getDrawable(R.drawable.work_challenge_background);
@@ -263,13 +282,9 @@
         }
     }
 
-    protected boolean isProfileChallenge() {
-        return mUserManager.isManagedProfile(mEffectiveUserId);
-    }
-
-    protected void reportSuccessfullAttempt() {
-        if (isProfileChallenge()) {
-            mLockPatternUtils.reportSuccessfulPasswordAttempt(mEffectiveUserId);
+    protected void reportSuccessfulAttempt() {
+        mLockPatternUtils.reportSuccessfulPasswordAttempt(mEffectiveUserId);
+        if (mUserManager.isManagedProfile(mEffectiveUserId)) {
             // Keyguard is responsible to disable StrongAuth for primary user. Disable StrongAuth
             // for work challenge only here.
             mLockPatternUtils.userPresent(mEffectiveUserId);
@@ -277,40 +292,73 @@
     }
 
     protected void reportFailedAttempt() {
-        if (isProfileChallenge()) {
-            // + 1 for this attempt.
-            updateErrorMessage(
-                    mLockPatternUtils.getCurrentFailedPasswordAttempts(mEffectiveUserId) + 1);
-            mLockPatternUtils.reportFailedPasswordAttempt(mEffectiveUserId);
-        }
+        updateErrorMessage(
+                mLockPatternUtils.getCurrentFailedPasswordAttempts(mEffectiveUserId) + 1);
+        mLockPatternUtils.reportFailedPasswordAttempt(mEffectiveUserId);
     }
 
     protected void updateErrorMessage(int numAttempts) {
         final int maxAttempts =
                 mLockPatternUtils.getMaximumFailedPasswordsForWipe(mEffectiveUserId);
-        if (maxAttempts > 0 && numAttempts > 0) {
-            int remainingAttempts = maxAttempts - numAttempts;
-            if (remainingAttempts == 1) {
-                // Last try
-                final String title = getActivity().getString(
-                        R.string.lock_profile_wipe_warning_title);
-                LastTryDialog.show(getFragmentManager(), title, getLastTryErrorMessage(),
-                        android.R.string.ok, false /* dismiss */);
-            } else if (remainingAttempts <= 0) {
-                // Profile is wiped
-                LastTryDialog.show(getFragmentManager(), null /* title */,
-                        R.string.lock_profile_wipe_content, R.string.lock_profile_wipe_dismiss,
-                        true /* dismiss */);
-            }
-            if (mErrorTextView != null) {
-                final String message = getActivity().getString(R.string.lock_profile_wipe_attempts,
-                        numAttempts, maxAttempts);
-                showError(message, 0);
-            }
+        if (maxAttempts <= 0 || numAttempts <= 0) {
+            return;
+        }
+
+        // Update the on-screen error string
+        if (mErrorTextView != null) {
+            final String message = getActivity().getString(
+                    R.string.lock_failed_attempts_before_wipe, numAttempts, maxAttempts);
+            showError(message, 0);
+        }
+
+        // Only show popup dialog before the last attempt and before wipe
+        final int remainingAttempts = maxAttempts - numAttempts;
+        if (remainingAttempts > 1) {
+            return;
+        }
+        final FragmentManager fragmentManager = getChildFragmentManager();
+        final int userType = getUserTypeForWipe();
+        if (remainingAttempts == 1) {
+            // Last try
+            final String title = getActivity().getString(
+                    R.string.lock_last_attempt_before_wipe_warning_title);
+            final int messageId = getLastTryErrorMessage(userType);
+            LastTryDialog.show(fragmentManager, title, messageId,
+                    android.R.string.ok, false /* dismiss */);
+        } else {
+            // Device, profile, or secondary user is wiped
+            final int messageId = getWipeMessage(userType);
+            LastTryDialog.show(fragmentManager, null /* title */, messageId,
+                    R.string.lock_failed_attempts_now_wiping_dialog_dismiss, true /* dismiss */);
         }
     }
 
-    protected abstract int getLastTryErrorMessage();
+    private int getUserTypeForWipe() {
+        final UserInfo userToBeWiped = mUserManager.getUserInfo(
+                mDevicePolicyManager.getProfileWithMinimumFailedPasswordsForWipe(mEffectiveUserId));
+        if (userToBeWiped == null || userToBeWiped.isPrimary()) {
+            return USER_TYPE_PRIMARY;
+        } else if (userToBeWiped.isManagedProfile()) {
+            return USER_TYPE_MANAGED_PROFILE;
+        } else {
+            return USER_TYPE_SECONDARY;
+        }
+    }
+
+    protected abstract int getLastTryErrorMessage(int userType);
+
+    private int getWipeMessage(int userType) {
+        switch (userType) {
+            case USER_TYPE_PRIMARY:
+                return R.string.lock_failed_attempts_now_wiping_device;
+            case USER_TYPE_MANAGED_PROFILE:
+                return R.string.lock_failed_attempts_now_wiping_profile;
+            case USER_TYPE_SECONDARY:
+                return R.string.lock_failed_attempts_now_wiping_user;
+            default:
+                throw new IllegalArgumentException("Unrecognized user type:" + userType);
+        }
+    }
 
     private final Runnable mResetErrorRunnable = new Runnable() {
         @Override
@@ -357,6 +405,7 @@
             DialogFragment dialog = new LastTryDialog();
             dialog.setArguments(args);
             dialog.show(from, TAG);
+            from.executePendingTransactions();
             return true;
         }
 
diff --git a/src/com/android/settings/password/ConfirmLockPassword.java b/src/com/android/settings/password/ConfirmLockPassword.java
index ef11521..0acdcd8 100644
--- a/src/com/android/settings/password/ConfirmLockPassword.java
+++ b/src/com/android/settings/password/ConfirmLockPassword.java
@@ -16,7 +16,6 @@
 
 package com.android.settings.password;
 
-import android.app.Activity;
 import android.app.Fragment;
 import android.app.admin.DevicePolicyManager;
 import android.content.Context;
@@ -45,7 +44,6 @@
 import com.android.internal.widget.LockPatternUtils;
 import com.android.internal.widget.TextViewInputDisabler;
 import com.android.settings.R;
-import com.android.settings.SettingsActivity;
 import com.android.settingslib.animation.AppearAnimationUtils;
 import com.android.settingslib.animation.DisappearAnimationUtils;
 
@@ -197,7 +195,7 @@
         }
 
         private int getDefaultDetails() {
-            boolean isStrongAuthRequired = isFingerprintDisallowedByStrongAuth();
+            boolean isStrongAuthRequired = isStrongAuthRequired();
             boolean isProfile = UserManager.get(getActivity()).isManagedProfile(mEffectiveUserId);
             // Map boolean flags to an index by isStrongAuth << 2 + isProfile << 1 + isAlpha.
             int index = ((isStrongAuthRequired ? 1 : 0) << 2) + ((isProfile ? 1 : 0) << 1)
@@ -211,9 +209,20 @@
         }
 
         @Override
-        protected int getLastTryErrorMessage() {
-            return mIsAlpha ? R.string.lock_profile_wipe_warning_content_password
-                    : R.string.lock_profile_wipe_warning_content_pin;
+        protected int getLastTryErrorMessage(int userType) {
+            switch (userType) {
+                case USER_TYPE_PRIMARY:
+                    return mIsAlpha ? R.string.lock_last_password_attempt_before_wipe_device
+                            : R.string.lock_last_pin_attempt_before_wipe_device;
+                case USER_TYPE_MANAGED_PROFILE:
+                    return mIsAlpha ? R.string.lock_last_password_attempt_before_wipe_profile
+                            : R.string.lock_last_pin_attempt_before_wipe_profile;
+                case USER_TYPE_SECONDARY:
+                    return mIsAlpha ? R.string.lock_last_password_attempt_before_wipe_user
+                            : R.string.lock_last_pin_attempt_before_wipe_user;
+                default:
+                    throw new IllegalArgumentException("Unrecognized user type:" + userType);
+            }
         }
 
         @Override
@@ -278,10 +287,8 @@
             } else {
                 resetState();
                 mErrorTextView.setText("");
-                if (isProfileChallenge()) {
-                    updateErrorMessage(mLockPatternUtils.getCurrentFailedPasswordAttempts(
-                            mEffectiveUserId));
-                }
+                updateErrorMessage(
+                        mLockPatternUtils.getCurrentFailedPasswordAttempts(mEffectiveUserId));
             }
             mCredentialCheckResultTracker.setListener(this);
         }
@@ -444,7 +451,7 @@
             mPasswordEntryInputDisabler.setInputEnabled(true);
             if (matched) {
                 if (newResult) {
-                    reportSuccessfullAttempt();
+                    reportSuccessfulAttempt();
                 }
                 startDisappearAnimation(intent);
                 checkForPendingIntent();
@@ -493,10 +500,8 @@
                 public void onFinish() {
                     resetState();
                     mErrorTextView.setText("");
-                    if (isProfileChallenge()) {
-                        updateErrorMessage(mLockPatternUtils.getCurrentFailedPasswordAttempts(
-                                mEffectiveUserId));
-                    }
+                    updateErrorMessage(
+                            mLockPatternUtils.getCurrentFailedPasswordAttempts(mEffectiveUserId));
                 }
             }.start();
         }
diff --git a/src/com/android/settings/password/ConfirmLockPattern.java b/src/com/android/settings/password/ConfirmLockPattern.java
index b66edfe..2931596 100644
--- a/src/com/android/settings/password/ConfirmLockPattern.java
+++ b/src/com/android/settings/password/ConfirmLockPattern.java
@@ -38,7 +38,6 @@
 import com.android.internal.widget.LockPatternView;
 import com.android.internal.widget.LockPatternView.Cell;
 import com.android.settings.R;
-import com.android.settings.SettingsActivity;
 import com.android.settingslib.animation.AppearAnimationCreator;
 import com.android.settingslib.animation.AppearAnimationUtils;
 import com.android.settingslib.animation.DisappearAnimationUtils;
@@ -155,7 +154,13 @@
                 // on first launch, if no lock pattern is set, then finish with
                 // success (don't want user to get stuck confirming something that
                 // doesn't exist).
-                if (!mLockPatternUtils.isLockPatternEnabled(mEffectiveUserId)) {
+                // Don't do this check for FRP though, because the pattern is not stored
+                // in a way that isLockPatternEnabled is aware of for that case.
+                // TODO(roosa): This block should no longer be needed since we removed the
+                //              ability to disable the pattern in L. Remove this block after
+                //              ensuring it's safe to do so. (Note that ConfirmLockPassword
+                //              doesn't have this).
+                if (!mFrp && !mLockPatternUtils.isLockPatternEnabled(mEffectiveUserId)) {
                     getActivity().setResult(Activity.RESULT_OK);
                     getActivity().finish();
                 }
@@ -238,7 +243,7 @@
         }
 
         private int getDefaultDetails() {
-            boolean isStrongAuthRequired = isFingerprintDisallowedByStrongAuth();
+            boolean isStrongAuthRequired = isStrongAuthRequired();
             if (UserManager.get(getActivity()).isManagedProfile(mEffectiveUserId)) {
                 return isStrongAuthRequired
                         ? R.string.lockpassword_strong_auth_required_reason_restart_work_pattern
@@ -299,10 +304,8 @@
                         mDetailsTextView.setText(getDefaultDetails());
                     }
                     mErrorTextView.setText("");
-                    if (isProfileChallenge()) {
-                        updateErrorMessage(mLockPatternUtils.getCurrentFailedPasswordAttempts(
-                                mEffectiveUserId));
-                    }
+                    updateErrorMessage(
+                            mLockPatternUtils.getCurrentFailedPasswordAttempts(mEffectiveUserId));
 
                     mLockPatternView.setEnabled(true);
                     mLockPatternView.enableInput();
@@ -497,7 +500,7 @@
             mLockPatternView.setEnabled(true);
             if (matched) {
                 if (newResult) {
-                    reportSuccessfullAttempt();
+                    reportSuccessfulAttempt();
                 }
                 startDisappearAnimation(intent);
                 checkForPendingIntent();
@@ -524,8 +527,17 @@
         }
 
         @Override
-        protected int getLastTryErrorMessage() {
-            return R.string.lock_profile_wipe_warning_content_pattern;
+        protected int getLastTryErrorMessage(int userType) {
+            switch (userType) {
+                case USER_TYPE_PRIMARY:
+                    return R.string.lock_last_pattern_attempt_before_wipe_device;
+                case USER_TYPE_MANAGED_PROFILE:
+                    return R.string.lock_last_pattern_attempt_before_wipe_profile;
+                case USER_TYPE_SECONDARY:
+                    return R.string.lock_last_pattern_attempt_before_wipe_user;
+                default:
+                    throw new IllegalArgumentException("Unrecognized user type:" + userType);
+            }
         }
 
         private void handleAttemptLockout(long elapsedRealtimeDeadline) {
diff --git a/src/com/android/settings/print/PrintSettingsFragment.java b/src/com/android/settings/print/PrintSettingsFragment.java
index a1c1660..26e760c 100644
--- a/src/com/android/settings/print/PrintSettingsFragment.java
+++ b/src/com/android/settings/print/PrintSettingsFragment.java
@@ -164,8 +164,7 @@
     /**
      * Adds preferences for all print services to the {@value PRINT_SERVICES_CATEGORY} cathegory.
      */
-    private final class PrintServicesController implements
-           LoaderCallbacks<List<PrintServiceInfo>> {
+    private final class PrintServicesController implements LoaderCallbacks<List<PrintServiceInfo>> {
         @Override
         public Loader<List<PrintServiceInfo>> onCreateLoader(int id, Bundle args) {
             PrintManager printManager =
@@ -290,7 +289,7 @@
         }
     }
 
-     private final class PrintJobsController implements LoaderCallbacks<List<PrintJobInfo>> {
+    private final class PrintJobsController implements LoaderCallbacks<List<PrintJobInfo>> {
 
         @Override
         public Loader<List<PrintJobInfo>> onCreateLoader(int id, Bundle args) {
@@ -326,7 +325,7 @@
 
                     switch (printJob.getState()) {
                         case PrintJobInfo.STATE_QUEUED:
-                        case PrintJobInfo.STATE_STARTED: {
+                        case PrintJobInfo.STATE_STARTED:
                             if (!printJob.isCancelling()) {
                                 preference.setTitle(getString(
                                         R.string.print_printing_state_title_template,
@@ -336,15 +335,13 @@
                                         R.string.print_cancelling_state_title_template,
                                         printJob.getLabel()));
                             }
-                        } break;
-
-                        case PrintJobInfo.STATE_FAILED: {
+                            break;
+                        case PrintJobInfo.STATE_FAILED:
                             preference.setTitle(getString(
                                     R.string.print_failed_state_title_template,
                                     printJob.getLabel()));
-                        } break;
-
-                        case PrintJobInfo.STATE_BLOCKED: {
+                            break;
+                        case PrintJobInfo.STATE_BLOCKED:
                             if (!printJob.isCancelling()) {
                                 preference.setTitle(getString(
                                         R.string.print_blocked_state_title_template,
@@ -354,7 +351,7 @@
                                         R.string.print_cancelling_state_title_template,
                                         printJob.getLabel()));
                             }
-                        } break;
+                            break;
                     }
 
                     preference.setSummary(getString(R.string.print_job_summary,
@@ -364,14 +361,13 @@
 
                     switch (printJob.getState()) {
                         case PrintJobInfo.STATE_QUEUED:
-                        case PrintJobInfo.STATE_STARTED: {
+                        case PrintJobInfo.STATE_STARTED:
                             preference.setIcon(R.drawable.ic_print);
-                        } break;
-
+                            break;
                         case PrintJobInfo.STATE_FAILED:
-                        case PrintJobInfo.STATE_BLOCKED: {
+                        case PrintJobInfo.STATE_BLOCKED:
                             preference.setIcon(R.drawable.ic_print_error);
-                        } break;
+                            break;
                     }
 
                     Bundle extras = preference.getExtras();
@@ -475,7 +471,7 @@
                 PrintJobInfo printJob = printJobs.get(i).getInfo();
                 if (shouldShowToUser(printJob)) {
                     if (printJobInfos == null) {
-                        printJobInfos = new ArrayList<PrintJobInfo>();
+                        printJobInfos = new ArrayList<>();
                     }
                     printJobInfos.add(printJob);
                 }
@@ -505,8 +501,9 @@
     /**
      * Provider for the print settings summary
      */
-    @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
-    static class PrintSummaryProvider implements SummaryLoader.SummaryProvider {
+    @VisibleForTesting
+    static class PrintSummaryProvider
+            implements SummaryLoader.SummaryProvider, PrintJobStateChangeListener {
         private final Context mContext;
         private final PrintManagerWrapper mPrintManager;
         private final SummaryLoader mSummaryLoader;
@@ -528,19 +525,43 @@
         public void setListening(boolean isListening) {
             if (mPrintManager != null) {
                 if (isListening) {
-                    List<PrintServiceInfo> services =
-                            mPrintManager.getPrintServices(PrintManager.ENABLED_SERVICES);
-                    if (services == null || services.isEmpty()) {
-                        mSummaryLoader.setSummary(this,
-                                mContext.getString(R.string.print_settings_summary_no_service));
-                    } else {
-                        final int count = services.size();
-                        mSummaryLoader.setSummary(this,
-                                mContext.getResources().getQuantityString(
-                                        R.plurals.print_settings_summary, count, count));
+                    mPrintManager.addPrintJobStateChanegListner(this);
+                    onPrintJobStateChanged(null);
+                } else {
+                    mPrintManager.removePrintJobStateChangeListener(this);
+                }
+            }
+        }
+
+        @Override
+        public void onPrintJobStateChanged(PrintJobId printJobId) {
+            final List<PrintJob> printJobs = mPrintManager.getPrintJobs();
+
+            int numActivePrintJobs = 0;
+            if (printJobs != null) {
+                for (PrintJob job : printJobs) {
+                    if (shouldShowToUser(job.getInfo())) {
+                        numActivePrintJobs++;
                     }
                 }
             }
+
+            if (numActivePrintJobs > 0) {
+                mSummaryLoader.setSummary(this, mContext.getResources().getQuantityString(
+                        R.plurals.print_jobs_summary, numActivePrintJobs, numActivePrintJobs));
+            } else {
+                List<PrintServiceInfo> services =
+                        mPrintManager.getPrintServices(PrintManager.ENABLED_SERVICES);
+                if (services == null || services.isEmpty()) {
+                    mSummaryLoader.setSummary(this,
+                            mContext.getString(R.string.print_settings_summary_no_service));
+                } else {
+                    final int count = services.size();
+                    mSummaryLoader.setSummary(this,
+                            mContext.getResources().getQuantityString(
+                                    R.plurals.print_settings_summary, count, count));
+                }
+            }
         }
 
         static class PrintManagerWrapper {
@@ -555,6 +576,18 @@
             public List<PrintServiceInfo> getPrintServices(int selectionFlags) {
                 return mPrintManager.getPrintServices(selectionFlags);
             }
+
+            public void addPrintJobStateChanegListner(PrintJobStateChangeListener listener) {
+                mPrintManager.addPrintJobStateChangeListener(listener);
+            }
+
+            public void removePrintJobStateChangeListener(PrintJobStateChangeListener listener) {
+                mPrintManager.removePrintJobStateChangeListener(listener);
+            }
+
+            public List<PrintJob> getPrintJobs() {
+                return mPrintManager.getPrintJobs();
+            }
         }
     }
 
diff --git a/src/com/android/settings/search/DatabaseResultLoader.java b/src/com/android/settings/search/DatabaseResultLoader.java
index 03f5cb4..26bfd52 100644
--- a/src/com/android/settings/search/DatabaseResultLoader.java
+++ b/src/com/android/settings/search/DatabaseResultLoader.java
@@ -25,10 +25,7 @@
 import com.android.settings.dashboard.SiteMapManager;
 import com.android.settings.utils.AsyncLoader;
 
-import java.util.ArrayList;
-import java.util.Collections;
 import java.util.HashSet;
-import java.util.List;
 import java.util.Set;
 
 import static com.android.settings.search.IndexDatabaseHelper.IndexColumns;
@@ -37,7 +34,7 @@
 /**
  * AsyncTask to retrieve Settings, First party app and any intent based results.
  */
-public class DatabaseResultLoader extends AsyncLoader<List<? extends SearchResult>> {
+public class DatabaseResultLoader extends AsyncLoader<Set<? extends SearchResult>> {
     private static final String LOG = "DatabaseResultLoader";
 
     /* These indices are used to match the columns of the this loader's SELECT statement.
@@ -114,25 +111,22 @@
     }
 
     @Override
-    protected void onDiscardResult(List<? extends SearchResult> result) {
+    protected void onDiscardResult(Set<? extends SearchResult> result) {
         // TODO Search
     }
 
     @Override
-    public List<? extends SearchResult> loadInBackground() {
+    public Set<? extends SearchResult> loadInBackground() {
         if (mQueryText == null || mQueryText.isEmpty()) {
             return null;
         }
 
-        final Set<SearchResult> resultSet = new HashSet<>();
+        final Set<SearchResult> results = new HashSet<>();
 
-        resultSet.addAll(firstWordQuery(MATCH_COLUMNS_PRIMARY, BASE_RANKS[0]));
-        resultSet.addAll(secondaryWordQuery(MATCH_COLUMNS_PRIMARY, BASE_RANKS[1]));
-        resultSet.addAll(anyWordQuery(MATCH_COLUMNS_SECONDARY, BASE_RANKS[2]));
-        resultSet.addAll(anyWordQuery(MATCH_COLUMNS_TERTIARY, BASE_RANKS[3]));
-
-        final List<SearchResult> results = new ArrayList<>(resultSet);
-        Collections.sort(results);
+        results.addAll(firstWordQuery(MATCH_COLUMNS_PRIMARY, BASE_RANKS[0]));
+        results.addAll(secondaryWordQuery(MATCH_COLUMNS_PRIMARY, BASE_RANKS[1]));
+        results.addAll(anyWordQuery(MATCH_COLUMNS_SECONDARY, BASE_RANKS[2]));
+        results.addAll(anyWordQuery(MATCH_COLUMNS_TERTIARY, BASE_RANKS[3]));
         return results;
     }
 
@@ -159,7 +153,7 @@
      *
      * @param matchColumns The columns to match on
      * @param baseRank The highest rank achievable by these results
-     * @return A list of the matching results.
+     * @return A set of the matching results.
      */
     private Set<SearchResult> firstWordQuery(String[] matchColumns, int baseRank) {
         final String whereClause = buildSingleWordWhereClause(matchColumns);
@@ -175,7 +169,7 @@
      *
      * @param matchColumns The columns to match on
      * @param baseRank The highest rank achievable by these results
-     * @return A list of the matching results.
+     * @return A set of the matching results.
      */
     private Set<SearchResult> secondaryWordQuery(String[] matchColumns, int baseRank) {
         final String whereClause = buildSingleWordWhereClause(matchColumns);
@@ -190,7 +184,7 @@
      *
      * @param matchColumns The columns to match on
      * @param baseRank The highest rank achievable by these results
-     * @return A list of the matching results.
+     * @return A set of the matching results.
      */
     private Set<SearchResult> anyWordQuery(String[] matchColumns, int baseRank) {
         final String whereClause = buildTwoWordWhereClause(matchColumns);
@@ -205,7 +199,7 @@
      * @param whereClause Where clause for the SQL query which uses bindings.
      * @param selection List of the transformed query to match each bind in the whereClause
      * @param baseRank The highest rank achievable by these results.
-     * @return A list of the matching results.
+     * @return A set of the matching results.
      */
     private Set<SearchResult> query(String whereClause, String[] selection, int baseRank) {
         SQLiteDatabase database = IndexDatabaseHelper.getInstance(mContext).getReadableDatabase();
diff --git a/src/com/android/settings/search/InlineSwitchViewHolder.java b/src/com/android/settings/search/InlineSwitchViewHolder.java
index 2b3642f..82d33d8 100644
--- a/src/com/android/settings/search/InlineSwitchViewHolder.java
+++ b/src/com/android/settings/search/InlineSwitchViewHolder.java
@@ -41,6 +41,11 @@
     }
 
     @Override
+    public int getClickActionMetricName() {
+        return MetricsEvent.ACTION_CLICK_SETTINGS_SEARCH_INLINE_RESULT;
+    }
+
+    @Override
     public void onBind(SearchFragment fragment, SearchResult result) {
         super.onBind(fragment, result);
         if (mContext == null) {
@@ -49,19 +54,10 @@
         final InlineSwitchPayload payload = (InlineSwitchPayload) result.payload;
         switchView.setChecked(payload.getSwitchValue(mContext));
         switchView.setOnCheckedChangeListener((buttonView, isChecked) -> {
-            final Pair<Integer, Object> name = Pair.create(
-                    MetricsEvent.FIELD_SETTINGS_SEARCH_INLINE_RESULT_NAME, payload.settingsUri);
             final Pair<Integer, Object> value = Pair.create(
                     MetricsEvent.FIELD_SETTINGS_SEARCH_INLINE_RESULT_VALUE, isChecked
-                            ? "checked"
-                            : "not-checked");
-            final Pair<Integer, Object> rank = Pair.create(
-                    MetricsEvent.FIELD_SETTINGS_SERACH_RESULT_RANK, getAdapterPosition());
-            mMetricsFeatureProvider.action(mContext,
-                    MetricsEvent.ACTION_CLICK_SETTINGS_SEARCH_INLINE_RESULT,
-                    name, value, rank);
-
-            fragment.onSearchResultClicked();
+                            ? 1L : 0L);
+            fragment.onSearchResultClicked(this, payload.settingsUri, value);
             payload.setSwitchValue(mContext, isChecked);
         });
     }
diff --git a/src/com/android/settings/search/InstalledAppResultLoader.java b/src/com/android/settings/search/InstalledAppResultLoader.java
index 76f3a00..25a3e89 100644
--- a/src/com/android/settings/search/InstalledAppResultLoader.java
+++ b/src/com/android/settings/search/InstalledAppResultLoader.java
@@ -37,14 +37,14 @@
 import com.android.settings.dashboard.SiteMapManager;
 import com.android.settings.utils.AsyncLoader;
 
-import java.util.ArrayList;
-import java.util.Collections;
+import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
 
 /**
  * Search loader for installed apps.
  */
-public class InstalledAppResultLoader extends AsyncLoader<List<? extends SearchResult>> {
+public class InstalledAppResultLoader extends AsyncLoader<Set<? extends SearchResult>> {
 
     private static final int NAME_NO_MATCH = -1;
     private static final Intent LAUNCHER_PROBE = new Intent(Intent.ACTION_MAIN)
@@ -67,8 +67,8 @@
     }
 
     @Override
-    public List<? extends SearchResult> loadInBackground() {
-        final List<AppSearchResult> results = new ArrayList<>();
+    public Set<? extends SearchResult> loadInBackground() {
+        final Set<AppSearchResult> results = new HashSet<>();
         final PackageManager pm = mPackageManager.getPackageManager();
 
         for (UserInfo user : getUsersToCount()) {
@@ -103,7 +103,6 @@
                 results.add(builder.build());
             }
         }
-        Collections.sort(results);
         return results;
     }
 
@@ -124,7 +123,7 @@
     }
 
     @Override
-    protected void onDiscardResult(List<? extends SearchResult> result) {
+    protected void onDiscardResult(Set<? extends SearchResult> result) {
 
     }
 
diff --git a/src/com/android/settings/search/IntentSearchViewHolder.java b/src/com/android/settings/search/IntentSearchViewHolder.java
index 68129b6..17ff981 100644
--- a/src/com/android/settings/search/IntentSearchViewHolder.java
+++ b/src/com/android/settings/search/IntentSearchViewHolder.java
@@ -19,7 +19,6 @@
 import android.content.ComponentName;
 import android.content.Intent;
 import android.text.TextUtils;
-import android.util.Pair;
 import android.view.View;
 
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
@@ -36,23 +35,22 @@
     }
 
     @Override
+    public int getClickActionMetricName() {
+        return MetricsEvent.ACTION_CLICK_SETTINGS_SEARCH_RESULT;
+    }
+
+    @Override
     public void onBind(final SearchFragment fragment, final SearchResult result) {
         super.onBind(fragment, result);
 
         itemView.setOnClickListener(v -> {
-            fragment.onSearchResultClicked();
             final Intent intent = result.payload.getIntent();
             final ComponentName cn = intent.getComponent();
-            final Pair<Integer, Object> rank = Pair.create(
-                    MetricsEvent.FIELD_SETTINGS_SERACH_RESULT_RANK, getAdapterPosition());
             String resultName = intent.getStringExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT);
             if (TextUtils.isEmpty(resultName) && cn != null) {
                 resultName = cn.flattenToString();
             }
-            mMetricsFeatureProvider.action(v.getContext(),
-                    MetricsEvent.ACTION_CLICK_SETTINGS_SEARCH_RESULT,
-                    resultName, rank);
-            mSearchFeatureProvider.searchResultClicked(fragment.mQuery, result);
+            fragment.onSearchResultClicked(this, resultName);
             fragment.startActivity(intent);
         });
     }
diff --git a/src/com/android/settings/search/SavedQueryViewHolder.java b/src/com/android/settings/search/SavedQueryViewHolder.java
index 158f698..14509b6 100644
--- a/src/com/android/settings/search/SavedQueryViewHolder.java
+++ b/src/com/android/settings/search/SavedQueryViewHolder.java
@@ -20,6 +20,8 @@
 import android.view.View;
 import android.widget.TextView;
 
+import com.android.internal.logging.nano.MetricsProto;
+
 public class SavedQueryViewHolder extends SearchViewHolder {
 
     public final TextView titleView;
@@ -32,6 +34,11 @@
     }
 
     @Override
+    public int getClickActionMetricName() {
+        return MetricsProto.MetricsEvent.ACTION_CLICK_SETTINGS_SEARCH_SAVED_QUERY;
+    }
+
+    @Override
     public void onBind(SearchFragment fragment, SearchResult result) {
         titleView.setText(result.title);
         titleView.setOnClickListener(v -> fragment.onSavedQueryClicked(result.title));
diff --git a/src/com/android/settings/search/SearchFeatureProvider.java b/src/com/android/settings/search/SearchFeatureProvider.java
index 8e30826..67d4ef1 100644
--- a/src/com/android/settings/search/SearchFeatureProvider.java
+++ b/src/com/android/settings/search/SearchFeatureProvider.java
@@ -19,8 +19,8 @@
 import android.app.Activity;
 import android.content.Context;
 import android.view.Menu;
-
 import android.view.View;
+
 import com.android.settings.dashboard.SiteMapManager;
 
 import java.util.List;
diff --git a/src/com/android/settings/search/SearchFragment.java b/src/com/android/settings/search/SearchFragment.java
index e50558b..1271900 100644
--- a/src/com/android/settings/search/SearchFragment.java
+++ b/src/com/android/settings/search/SearchFragment.java
@@ -28,6 +28,7 @@
 import android.support.v7.widget.RecyclerView;
 import android.text.TextUtils;
 import android.util.Log;
+import android.util.Pair;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
@@ -36,14 +37,17 @@
 import android.widget.LinearLayout.LayoutParams;
 import android.widget.SearchView;
 
-import com.android.internal.logging.nano.MetricsProto;
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.settings.R;
 import com.android.settings.Utils;
 import com.android.settings.core.InstrumentedFragment;
 import com.android.settings.core.instrumentation.MetricsFeatureProvider;
 import com.android.settings.overlay.FeatureFactory;
 
+import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
+import java.util.Set;
 import java.util.concurrent.atomic.AtomicInteger;
 
 /**
@@ -57,7 +61,7 @@
  * the query if the user has entered text.
  */
 public class SearchFragment extends InstrumentedFragment implements SearchView.OnQueryTextListener,
-        LoaderManager.LoaderCallbacks<List<? extends SearchResult>>, IndexingCallback {
+        LoaderManager.LoaderCallbacks<Set<? extends SearchResult>>, IndexingCallback {
     private static final String TAG = "SearchFragment";
 
     @VisibleForTesting
@@ -118,7 +122,7 @@
 
     @Override
     public int getMetricsCategory() {
-        return MetricsProto.MetricsEvent.DASHBOARD_SEARCH_RESULTS;
+        return MetricsEvent.DASHBOARD_SEARCH_RESULTS;
     }
 
     @Override
@@ -191,7 +195,7 @@
             mMetricsFeatureProvider.histogram(activity, RESULT_CLICK_COUNT, mResultClickCount);
             if (mNeverEnteredQuery) {
                 mMetricsFeatureProvider.action(activity,
-                        MetricsProto.MetricsEvent.ACTION_LEAVE_SEARCH_RESULT_WITHOUT_QUERY);
+                        MetricsEvent.ACTION_LEAVE_SEARCH_RESULT_WITHOUT_QUERY);
             }
         }
     }
@@ -251,7 +255,7 @@
     }
 
     @Override
-    public Loader<List<? extends SearchResult>> onCreateLoader(int id, Bundle args) {
+    public Loader<Set<? extends SearchResult>> onCreateLoader(int id, Bundle args) {
         final Activity activity = getActivity();
 
         switch (id) {
@@ -265,8 +269,8 @@
     }
 
     @Override
-    public void onLoadFinished(Loader<List<? extends SearchResult>> loader,
-            List<? extends SearchResult> data) {
+    public void onLoadFinished(Loader<Set<? extends SearchResult>> loader,
+            Set<? extends SearchResult> data) {
         mSearchAdapter.addSearchResults(data, loader.getClass().getName());
         if (mUnfinishedLoadersCount.decrementAndGet() != 0) {
             return;
@@ -284,7 +288,7 @@
     }
 
     @Override
-    public void onLoaderReset(Loader<List<? extends SearchResult>> loader) {
+    public void onLoaderReset(Loader<Set<? extends SearchResult>> loader) {
     }
 
     /**
@@ -306,7 +310,26 @@
         requery();
     }
 
-    public void onSearchResultClicked() {
+    public void onSearchResultClicked(SearchViewHolder result, String settingName,
+            Pair<Integer, Object>... logTaggedData) {
+        final List<Pair<Integer, Object>> taggedData = new ArrayList<>();
+        if (logTaggedData != null) {
+            taggedData.addAll(Arrays.asList(logTaggedData));
+        }
+        taggedData.add(Pair.create(
+                MetricsEvent.FIELD_SETTINGS_SERACH_RESULT_COUNT,
+                mSearchAdapter.getItemCount()));
+        taggedData.add(Pair.create(
+                MetricsEvent.FIELD_SETTINGS_SERACH_RESULT_RANK,
+                result.getAdapterPosition()));
+        taggedData.add(Pair.create(
+                MetricsEvent.FIELD_SETTINGS_SERACH_QUERY_LENGTH,
+                TextUtils.isEmpty(mQuery) ? 0 : mQuery.length()));
+
+        mMetricsFeatureProvider.action(getContext(),
+                MetricsEvent.ACTION_CLICK_SETTINGS_SEARCH_RESULT,
+                settingName,
+                taggedData.toArray(new Pair[0]));
         mSavedQueryController.saveQuery(mQuery);
         mResultClickCount++;
     }
@@ -314,7 +337,7 @@
     public void onSavedQueryClicked(CharSequence query) {
         final String queryString = query.toString();
         mMetricsFeatureProvider.action(getContext(),
-                MetricsProto.MetricsEvent.ACTION_CLICK_SETTINGS_SEARCH_SAVED_QUERY);
+                MetricsEvent.ACTION_CLICK_SETTINGS_SEARCH_SAVED_QUERY);
         mSearchView.setQuery(queryString, false /* submit */);
         onQueryTextChange(queryString);
     }
diff --git a/src/com/android/settings/search/SearchIndexableResources.java b/src/com/android/settings/search/SearchIndexableResources.java
index ab1af49..963aff4 100644
--- a/src/com/android/settings/search/SearchIndexableResources.java
+++ b/src/com/android/settings/search/SearchIndexableResources.java
@@ -47,6 +47,7 @@
 import com.android.settings.development.DevelopmentSettings;
 import com.android.settings.deviceinfo.StorageDashboardFragment;
 import com.android.settings.deviceinfo.StorageSettings;
+import com.android.settings.display.AmbientDisplaySettings;
 import com.android.settings.display.ScreenZoomSettings;
 import com.android.settings.dream.DreamSettings;
 import com.android.settings.enterprise.EnterprisePrivacySettings;
@@ -117,6 +118,7 @@
         addIndex(DataUsageMeteredSettings.class, NO_DATA_RES_ID, R.drawable.ic_settings_data_usage);
         addIndex(ScreenZoomSettings.class, NO_DATA_RES_ID, R.drawable.ic_settings_display);
         addIndex(DisplaySettings.class, NO_DATA_RES_ID, R.drawable.ic_settings_display);
+        addIndex(AmbientDisplaySettings.class, NO_DATA_RES_ID, R.drawable.ic_settings_display);
         addIndex(WallpaperTypeSettings.class, NO_DATA_RES_ID, R.drawable.ic_settings_display);
         addIndex(ConfigureNotificationSettings.class,
                 R.xml.configure_notification_settings, R.drawable.ic_settings_notifications);
diff --git a/src/com/android/settings/search/SearchResultsAdapter.java b/src/com/android/settings/search/SearchResultsAdapter.java
index 7861b08..31e0793 100644
--- a/src/com/android/settings/search/SearchResultsAdapter.java
+++ b/src/com/android/settings/search/SearchResultsAdapter.java
@@ -30,15 +30,17 @@
 import com.android.settings.R;
 
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 public class SearchResultsAdapter extends RecyclerView.Adapter<SearchViewHolder> {
 
     private final SearchFragment mFragment;
 
     private List<SearchResult> mSearchResults;
-    private Map<String, List<? extends SearchResult>> mResultsMap;
+    private Map<String, Set<? extends SearchResult>> mResultsMap;
     private final SearchFeatureProvider mSearchFeatureProvider;
 
     public SearchResultsAdapter(SearchFragment fragment,
@@ -98,7 +100,7 @@
      * @param loaderClassName class name of the loader.
      */
     @MainThread
-    public void addSearchResults(List<? extends SearchResult> results, String loaderClassName) {
+    public void addSearchResults(Set<? extends SearchResult> results, String loaderClassName) {
         if (results == null) {
             return;
         }
@@ -125,12 +127,22 @@
      * @return Number of matched results
      */
     public int displaySearchResults(String query) {
-        final List<? extends SearchResult> databaseResults = mResultsMap
-                .get(DatabaseResultLoader.class.getName());
-        final List<? extends SearchResult> installedAppResults = mResultsMap
-                .get(InstalledAppResultLoader.class.getName());
-        final int dbSize = (databaseResults != null) ? databaseResults.size() : 0;
-        final int appSize = (installedAppResults != null) ? installedAppResults.size() : 0;
+        List<? extends SearchResult> databaseResults = null;
+        List<? extends SearchResult> installedAppResults = null;
+        final String dbLoaderKey = DatabaseResultLoader.class.getName();
+        final String appLoaderKey = InstalledAppResultLoader.class.getName();
+        int dbSize = 0;
+        int appSize = 0;
+        if (mResultsMap.containsKey(dbLoaderKey)) {
+            databaseResults = new ArrayList<>(mResultsMap.get(dbLoaderKey));
+            dbSize = databaseResults.size();
+            Collections.sort(databaseResults);
+        }
+        if (mResultsMap.containsKey(appLoaderKey)) {
+            installedAppResults = new ArrayList<>(mResultsMap.get(appLoaderKey));
+            appSize = installedAppResults.size();
+            Collections.sort(installedAppResults);
+        }
         final List<SearchResult> newResults = new ArrayList<>(dbSize + appSize);
 
         int dbIndex = 0;
diff --git a/src/com/android/settings/search/SearchViewHolder.java b/src/com/android/settings/search/SearchViewHolder.java
index 93409ee..55fd594 100644
--- a/src/com/android/settings/search/SearchViewHolder.java
+++ b/src/com/android/settings/search/SearchViewHolder.java
@@ -59,6 +59,8 @@
         mPlaceholderSummary = view.getContext().getString(R.string.summary_placeholder);
     }
 
+    public abstract int getClickActionMetricName();
+
     public void onBind(SearchFragment fragment, SearchResult result) {
         titleView.setText(result.title);
         if (TextUtils.isEmpty(result.summary)
diff --git a/src/com/android/settings/security/LockscreenDashboardFragment.java b/src/com/android/settings/security/LockscreenDashboardFragment.java
index f3b18f2..92142a9 100644
--- a/src/com/android/settings/security/LockscreenDashboardFragment.java
+++ b/src/com/android/settings/security/LockscreenDashboardFragment.java
@@ -18,6 +18,8 @@
 
 import android.content.Context;
 import android.provider.SearchIndexableResource;
+import android.support.annotation.VisibleForTesting;
+
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.settings.R;
 import com.android.settings.accounts.AddUserWhenLockedPreferenceController;
@@ -26,6 +28,7 @@
 import com.android.settings.notification.LockScreenNotificationPreferenceController;
 import com.android.settings.search.BaseSearchIndexProvider;
 import com.android.settingslib.core.lifecycle.Lifecycle;
+
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
@@ -38,6 +41,15 @@
 
     private static final String TAG = "LockscreenDashboardFragment";
 
+    @VisibleForTesting
+    static final String KEY_LOCK_SCREEN_NOTIFICATON = "security_setting_lock_screen_notif";
+    @VisibleForTesting
+    static final String KEY_LOCK_SCREEN_NOTIFICATON_WORK_PROFILE_HEADER =
+            "security_setting_lock_screen_notif_work_header";
+    @VisibleForTesting
+    static final String KEY_LOCK_SCREEN_NOTIFICATON_WORK_PROFILE =
+            "security_setting_lock_screen_notif_work";
+
     private OwnerInfoPreferenceController mOwnerInfoPreferenceController;
 
     @Override
@@ -60,7 +72,10 @@
         final List<PreferenceController> controllers = new ArrayList<>();
         final Lifecycle lifecycle = getLifecycle();
         final LockScreenNotificationPreferenceController notificationController =
-            new LockScreenNotificationPreferenceController(context);
+            new LockScreenNotificationPreferenceController(context,
+                    KEY_LOCK_SCREEN_NOTIFICATON,
+                    KEY_LOCK_SCREEN_NOTIFICATON_WORK_PROFILE_HEADER,
+                    KEY_LOCK_SCREEN_NOTIFICATON_WORK_PROFILE);
         lifecycle.addObserver(notificationController);
         controllers.add(notificationController);
         final AddUserWhenLockedPreferenceController addUserWhenLockedController =
diff --git a/src/com/android/settings/security/SecurityFeatureProviderImpl.java b/src/com/android/settings/security/SecurityFeatureProviderImpl.java
index 5a2ff2e..8c6d343 100644
--- a/src/com/android/settings/security/SecurityFeatureProviderImpl.java
+++ b/src/com/android/settings/security/SecurityFeatureProviderImpl.java
@@ -24,6 +24,7 @@
 import android.graphics.drawable.Drawable;
 import android.os.Handler;
 import android.os.Looper;
+import com.android.settings.R;
 import com.android.settings.trustagent.TrustAgentManager;
 import com.android.settings.trustagent.TrustAgentManagerImpl;
 import com.android.settingslib.drawer.DashboardCategory;
@@ -49,8 +50,6 @@
 
     @VisibleForTesting
     static final Drawable DEFAULT_ICON = null;
-    @VisibleForTesting
-    static final String DEFAULT_SUMMARY = " ";
 
     @VisibleForTesting
     static Map<String, Pair<String, Integer>> sIconCache = new TreeMap<>();
@@ -118,7 +117,7 @@
             // from shifting when the final summary is injected.
             final String summaryUri =
                     tile.metaData.getString(TileUtils.META_DATA_PREFERENCE_SUMMARY_URI, null);
-            String summary = DEFAULT_SUMMARY;
+            String summary = context.getString(R.string.summary_placeholder);
             if ((summaryUri != null) && sSummaryCache.containsKey(summaryUri)) {
                 summary = sSummaryCache.get(summaryUri);
             }
diff --git a/src/com/android/settings/widget/EntityHeaderController.java b/src/com/android/settings/widget/EntityHeaderController.java
index 70d3ce5..c9e0805 100644
--- a/src/com/android/settings/widget/EntityHeaderController.java
+++ b/src/com/android/settings/widget/EntityHeaderController.java
@@ -78,6 +78,7 @@
     private Lifecycle mLifecycle;
     private RecyclerView mRecyclerView;
     private Drawable mIcon;
+    private String mIconContentDescription;
     private CharSequence mLabel;
     private CharSequence mSummary;
     private String mPackageName;
@@ -122,6 +123,10 @@
         return this;
     }
 
+    /**
+     * Set the icon in the header. Callers should also consider calling setIconContentDescription
+     * to provide a description of this icon for accessibility purposes.
+     */
     public EntityHeaderController setIcon(Drawable icon) {
         if (icon != null) {
             mIcon = icon.getConstantState().newDrawable(mAppContext.getResources());
@@ -129,6 +134,11 @@
         return this;
     }
 
+    /**
+     * Convenience method to set the header icon from an ApplicationsState.AppEntry. Callers should
+     * also consider calling setIconContentDescription to provide a description of this icon for
+     * accessibility purposes.
+     */
     public EntityHeaderController setIcon(ApplicationsState.AppEntry appEntry) {
         if (appEntry.icon != null) {
             mIcon = appEntry.icon.getConstantState().newDrawable(mAppContext.getResources());
@@ -136,6 +146,11 @@
         return this;
     }
 
+    public EntityHeaderController setIconContentDescription(String contentDescription) {
+        mIconContentDescription = contentDescription;
+        return this;
+    }
+
     public EntityHeaderController setLabel(CharSequence label) {
         mLabel = label;
         return this;
@@ -204,6 +219,7 @@
         ImageView iconView = mHeader.findViewById(R.id.entity_header_icon);
         if (iconView != null) {
             iconView.setImageDrawable(mIcon);
+            iconView.setContentDescription(mIconContentDescription);
         }
         setText(R.id.entity_header_title, mLabel);
         setText(R.id.entity_header_summary, mSummary);
diff --git a/src/com/android/settings/widget/SingleLineSummaryPreference.java b/src/com/android/settings/widget/FixedLineSummaryPreference.java
similarity index 61%
rename from src/com/android/settings/widget/SingleLineSummaryPreference.java
rename to src/com/android/settings/widget/FixedLineSummaryPreference.java
index 36d9e80..c83dff4 100644
--- a/src/com/android/settings/widget/SingleLineSummaryPreference.java
+++ b/src/com/android/settings/widget/FixedLineSummaryPreference.java
@@ -15,19 +15,36 @@
 package com.android.settings.widget;
 
 import android.content.Context;
+import android.content.res.TypedArray;
 import android.support.v7.preference.Preference;
 import android.support.v7.preference.PreferenceViewHolder;
 import android.text.TextUtils.TruncateAt;
 import android.util.AttributeSet;
 import android.widget.TextView;
 
+import com.android.settings.R;
+
 /**
  * A preference whose summary text will only span one single line.
  */
-public class SingleLineSummaryPreference extends Preference {
+public class FixedLineSummaryPreference extends Preference {
 
-    public SingleLineSummaryPreference(Context context, AttributeSet attrs) {
+    private int mSummaryLineCount;
+
+    public FixedLineSummaryPreference(Context context, AttributeSet attrs) {
         super(context, attrs);
+        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FixedLineSummaryPreference,
+                0, 0);
+        if (a.hasValue(R.styleable.FixedLineSummaryPreference_summaryLineCount)) {
+            mSummaryLineCount = a.getInteger(
+                    R.styleable.FixedLineSummaryPreference_summaryLineCount, 1);
+        } else {
+            mSummaryLineCount = 1;
+        }
+    }
+
+    public void setSummaryLineCount(int count) {
+        mSummaryLineCount = count;
     }
 
     @Override
@@ -35,7 +52,8 @@
         super.onBindViewHolder(holder);
         TextView summary = (TextView) holder.findViewById(android.R.id.summary);
         if (summary != null) {
-            summary.setSingleLine();
+            summary.setMinLines(mSummaryLineCount);
+            summary.setMaxLines(mSummaryLineCount);
             summary.setEllipsize(TruncateAt.END);
         }
     }
diff --git a/src/com/android/settings/widget/SettingsAppWidgetProvider.java b/src/com/android/settings/widget/SettingsAppWidgetProvider.java
index 38fed94..7dacaf5 100644
--- a/src/com/android/settings/widget/SettingsAppWidgetProvider.java
+++ b/src/com/android/settings/widget/SettingsAppWidgetProvider.java
@@ -395,7 +395,10 @@
                     int wifiApState = wifiManager.getWifiApState();
                     if (desiredState && ((wifiApState == WifiManager.WIFI_AP_STATE_ENABLING) ||
                                          (wifiApState == WifiManager.WIFI_AP_STATE_ENABLED))) {
-                        wifiManager.setWifiApEnabled(null, false);
+                        final ConnectivityManager connectivityManager =
+                                (ConnectivityManager) context.getSystemService(
+                                        Context.CONNECTIVITY_SERVICE);
+                        connectivityManager.stopTethering(ConnectivityManager.TETHERING_WIFI);
                     }
 
                     wifiManager.setWifiEnabled(desiredState);
diff --git a/src/com/android/settings/wifi/details/WifiDetailPreferenceController.java b/src/com/android/settings/wifi/details/WifiDetailPreferenceController.java
index 39d90e1..d1f6c80 100644
--- a/src/com/android/settings/wifi/details/WifiDetailPreferenceController.java
+++ b/src/com/android/settings/wifi/details/WifiDetailPreferenceController.java
@@ -224,7 +224,7 @@
         mConnectionDetailPref = screen.findPreference(KEY_CONNECTION_DETAIL_PREF);
 
         mButtonsPref = (LayoutPreference) screen.findPreference(KEY_BUTTONS_PREF);
-        mSignInButton = (Button) mButtonsPref.findViewById(R.id.right_button);
+        mSignInButton = (Button) mButtonsPref.findViewById(R.id.signin_button);
         mSignInButton.setText(R.string.support_sign_in_button_text);
         mSignInButton.setOnClickListener(
             view -> mConnectivityManagerWrapper.startCaptivePortalApp(mNetwork));
@@ -245,7 +245,7 @@
                 (PreferenceCategory) screen.findPreference(KEY_IPV6_ADDRESS_CATEGORY);
 
         mSecurityPref.setDetailText(mAccessPoint.getSecurityString(false /* concise */));
-        mForgetButton = (Button) mButtonsPref.findViewById(R.id.left_button);
+        mForgetButton = (Button) mButtonsPref.findViewById(R.id.forget_button);
         mForgetButton.setText(R.string.forget);
         mForgetButton.setOnClickListener(view -> forgetNetwork());
         updateInfo();
diff --git a/tests/robotests/Android.mk b/tests/robotests/Android.mk
index b448433..ae0102f 100644
--- a/tests/robotests/Android.mk
+++ b/tests/robotests/Android.mk
@@ -8,7 +8,7 @@
 
 # Include the testing libraries (JUnit4 + Robolectric libs).
 LOCAL_STATIC_JAVA_LIBRARIES := \
-    platform-system-robolectric \
+    mockito-robolectric-prebuilt \
     truth-prebuilt
 
 LOCAL_JAVA_LIBRARIES := \
diff --git a/tests/robotests/assets/grandfather_not_sharing_pref_controllers_with_search_provider b/tests/robotests/assets/grandfather_not_sharing_pref_controllers_with_search_provider
index 1712f19..b329072 100644
--- a/tests/robotests/assets/grandfather_not_sharing_pref_controllers_with_search_provider
+++ b/tests/robotests/assets/grandfather_not_sharing_pref_controllers_with_search_provider
@@ -1,2 +1 @@
-com.android.settings.applications.AdvancedAppSettings
 com.android.settings.fuelgauge.PowerUsageSummary
diff --git a/tests/robotests/assets/whitelist_duplicate_index_key b/tests/robotests/assets/whitelist_duplicate_index_key
index 0b8d675..a761f35 100644
--- a/tests/robotests/assets/whitelist_duplicate_index_key
+++ b/tests/robotests/assets/whitelist_duplicate_index_key
@@ -1,6 +1,5 @@
 add_users_when_locked
 additional_system_update_settings
-screen_zoom
 dashboard_tile_placeholder
-lock_screen_notifications
-usage_access
\ No newline at end of file
+screen_zoom
+usage_access
diff --git a/tests/robotests/res/layout-mcc999/fingerprint_enroll_find_sensor.xml b/tests/robotests/res/layout-mcc999/fingerprint_enroll_find_sensor.xml
new file mode 100644
index 0000000..04489de
--- /dev/null
+++ b/tests/robotests/res/layout-mcc999/fingerprint_enroll_find_sensor.xml
@@ -0,0 +1,78 @@
+<?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.
+-->
+
+<com.android.setupwizardlib.GlifLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/setup_wizard_layout"
+    style="?attr/fingerprint_layout_theme"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent">
+
+    <FrameLayout
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:orientation="vertical"
+        android:clipToPadding="false"
+        android:clipChildren="false">
+
+        <FrameLayout
+            android:layout_width="@dimen/fingerprint_find_sensor_graphic_size"
+            android:layout_height="@dimen/fingerprint_find_sensor_graphic_size"
+            android:layout_gravity="center_horizontal|bottom">
+
+            <ImageView
+                android:id="@+id/fingerprint_sensor_location_animation"
+                android:layout_width="match_parent"
+                android:layout_height="match_parent"
+                android:contentDescription="@string/security_settings_fingerprint_enroll_find_sensor_content_description"
+                android:src="@drawable/fingerprint_sensor_location"
+                android:scaleType="centerInside"/>
+
+        </FrameLayout>
+
+        <LinearLayout
+            style="@style/SuwContentFrame"
+            android:layout_width="match_parent"
+            android:layout_height="match_parent"
+            android:orientation="vertical"
+            android:clipToPadding="false"
+            android:clipChildren="false">
+
+            <TextView
+                style="@style/SuwDescription.Glif"
+                android:layout_width="match_parent"
+                android:layout_height="wrap_content"
+                android:layout_marginTop="@dimen/suw_description_glif_margin_top"
+                android:text="@string/security_settings_fingerprint_enroll_find_sensor_message"/>
+
+            <View
+                android:layout_height="0dp"
+                android:layout_width="match_parent"
+                android:layout_weight="1"/>
+
+            <Button
+                style="@style/SuwGlifButton.Primary"
+                android:id="@+id/next_button"
+                android:layout_width="wrap_content"
+                android:layout_height="wrap_content"
+                android:layout_marginBottom="4dp"
+                android:layout_gravity="end"
+                android:text="@string/fingerprint_enroll_button_next" />
+
+        </LinearLayout>
+    </FrameLayout>
+</com.android.setupwizardlib.GlifLayout>
diff --git a/tests/robotests/src/com/android/internal/hardware/AmbientDisplayConfiguration.java b/tests/robotests/src/com/android/internal/hardware/AmbientDisplayConfiguration.java
index 9ac077d..7e3cd84 100644
--- a/tests/robotests/src/com/android/internal/hardware/AmbientDisplayConfiguration.java
+++ b/tests/robotests/src/com/android/internal/hardware/AmbientDisplayConfiguration.java
@@ -57,4 +57,12 @@
     public boolean alwaysOnAvailable() {
         return true;
     }
+
+    public boolean available() {
+        return true;
+    }
+
+    public boolean enabled(int user) {
+        return true;
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/MasterClearTest.java b/tests/robotests/src/com/android/settings/MasterClearTest.java
index 98b33d3..9af2b5f 100644
--- a/tests/robotests/src/com/android/settings/MasterClearTest.java
+++ b/tests/robotests/src/com/android/settings/MasterClearTest.java
@@ -17,13 +17,18 @@
 package com.android.settings;
 
 import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.when;
 import static org.robolectric.Shadows.shadowOf;
 
 import android.app.Activity;
 import android.app.Fragment;
+import android.content.ContentResolver;
 import android.os.Bundle;
+import android.provider.Settings;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.widget.CheckBox;
@@ -83,6 +88,60 @@
     }
 
     @Test
+    public void testShowWipeEuicc_euiccDisabled() {
+        prepareEuiccState(
+                false /* isEuiccEnabled */, true /* isEuiccProvisioned */,
+                true /* isDevelopmentSettingsEnabled */);
+        assertThat(mMasterClear.showWipeEuicc()).isFalse();
+    }
+
+    @Test
+    public void testShowWipeEuicc_euiccEnabled_unprovisioned() {
+        prepareEuiccState(
+                true /* isEuiccEnabled */, false /* isEuiccProvisioned */,
+                false /* isDevelopmentSettingsEnabled */);
+        assertThat(mMasterClear.showWipeEuicc()).isFalse();
+    }
+
+    @Test
+    public void testShowWipeEuicc_euiccEnabled_provisioned() {
+        prepareEuiccState(
+                true /* isEuiccEnabled */, true /* isEuiccProvisioned */,
+                false /* isDevelopmentSettingsEnabled */);
+        assertThat(mMasterClear.showWipeEuicc()).isTrue();
+    }
+
+    @Test
+    public void testShowWipeEuicc_euiccEnabled_developmentSettingsEnabled() {
+        prepareEuiccState(
+                true /* isEuiccEnabled */, false /* isEuiccProvisioned */,
+                true /* isDevelopmentSettingsEnabled */);
+        assertThat(mMasterClear.showWipeEuicc()).isTrue();
+    }
+
+    @Test
+    public void testShowWipeEuicc_euiccEnabled_provisioned_developmentSettingsEnabled() {
+        prepareEuiccState(
+                true /* isEuiccEnabled */, true /* isEuiccProvisioned */,
+                true /* isDevelopmentSettingsEnabled */);
+        assertThat(mMasterClear.showWipeEuicc()).isTrue();
+    }
+
+    private void prepareEuiccState(
+            boolean isEuiccEnabled,
+            boolean isEuiccProvisioned,
+            boolean isDevelopmentSettingsEnabled) {
+        doReturn(mActivity).when(mMasterClear).getContext();
+        doReturn(isEuiccEnabled).when(mMasterClear).isEuiccEnabled(any());
+        ContentResolver cr = mActivity.getContentResolver();
+        Settings.Global.putInt(
+                cr, android.provider.Settings.Global.EUICC_PROVISIONED, isEuiccProvisioned ? 1 : 0);
+        Settings.Global.putInt(
+                cr, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED,
+                isDevelopmentSettingsEnabled ? 1 : 0);
+    }
+
+    @Test
     public void testShowFinalConfirmation_EraseEsimChecked() {
         ActivityForTest testActivity = new ActivityForTest();
         when(mMasterClear.getActivity()).thenReturn(testActivity);
diff --git a/tests/robotests/src/com/android/settings/SettingsActivityTest.java b/tests/robotests/src/com/android/settings/SettingsActivityTest.java
index 65e9708..2250090 100644
--- a/tests/robotests/src/com/android/settings/SettingsActivityTest.java
+++ b/tests/robotests/src/com/android/settings/SettingsActivityTest.java
@@ -16,6 +16,16 @@
 
 package com.android.settings;
 
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import android.app.Activity;
 import android.app.ActivityManager;
 import android.app.FragmentManager;
@@ -23,10 +33,11 @@
 import android.content.Context;
 import android.content.Intent;
 import android.graphics.Bitmap;
-
 import android.os.Bundle;
 import android.view.Menu;
+
 import com.android.settings.testutils.FakeFeatureFactory;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -37,15 +48,6 @@
 import org.robolectric.annotation.Config;
 import org.robolectric.util.ReflectionHelpers;
 
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class SettingsActivityTest {
@@ -89,7 +91,7 @@
     public void testSetTaskDescription_IconChanged() {
         mActivity.setTaskDescription(mTaskDescription);
 
-        verify(mTaskDescription).setIcon(any());
+        verify(mTaskDescription).setIcon(nullable(Bitmap.class));
     }
 
     @Test
@@ -99,8 +101,8 @@
         mActivity.mDisplaySearch = true;
         mActivity.onCreateOptionsMenu(null);
 
-        verify(mFeatureFactory.getSearchFeatureProvider()).setUpSearchMenu(any(Menu.class),
-                any(Activity.class));
+        verify(mFeatureFactory.getSearchFeatureProvider()).setUpSearchMenu(nullable(Menu.class),
+                nullable(Activity.class));
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/SettingsPreferenceFragmentTest.java b/tests/robotests/src/com/android/settings/SettingsPreferenceFragmentTest.java
new file mode 100644
index 0000000..cd48da3
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/SettingsPreferenceFragmentTest.java
@@ -0,0 +1,112 @@
+/*
+ * 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 android.content.Context;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceCategory;
+import android.support.v7.preference.PreferenceManager;
+import android.support.v7.preference.PreferenceScreen;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class SettingsPreferenceFragmentTest {
+
+    @Mock
+    private PreferenceManager mPreferenceManager;
+    private Context mContext;
+    private TestFragment mFragment;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mContext = RuntimeEnvironment.application;
+        mFragment = new TestFragment();
+    }
+
+    @Test
+    public void removePreference_nested_shouldRemove() {
+        final String key = "test_key";
+        final PreferenceScreen mScreen = spy(new PreferenceScreen(mContext, null));
+        when(mScreen.getPreferenceManager()).thenReturn(mock(PreferenceManager.class));
+
+        final PreferenceCategory nestedCategory = new ProgressCategory(mContext);
+        final Preference preference = new Preference(mContext);
+        preference.setKey(key);
+        preference.setPersistent(false);
+
+        mScreen.addPreference(nestedCategory);
+        nestedCategory.addPreference(preference);
+
+        assertThat(mFragment.removePreference(mScreen, key)).isTrue();
+        assertThat(nestedCategory.getPreferenceCount()).isEqualTo(0);
+    }
+
+    @Test
+    public void removePreference_flat_shouldRemove() {
+        final String key = "test_key";
+        final PreferenceScreen mScreen = spy(new PreferenceScreen(mContext, null));
+        when(mScreen.getPreferenceManager()).thenReturn(mock(PreferenceManager.class));
+
+        final Preference preference = mock(Preference.class);
+        when(preference.getKey()).thenReturn(key);
+
+        mScreen.addPreference(preference);
+
+        assertThat(mFragment.removePreference(mScreen, key)).isTrue();
+        assertThat(mScreen.getPreferenceCount()).isEqualTo(0);
+    }
+
+    @Test
+    public void removePreference_doNotExist_shouldNotRemove() {
+        final String key = "test_key";
+        final PreferenceScreen mScreen = spy(new PreferenceScreen(mContext, null));
+        when(mScreen.getPreferenceManager()).thenReturn(mock(PreferenceManager.class));
+
+        final Preference preference = mock(Preference.class);
+        when(preference.getKey()).thenReturn(key);
+
+        mScreen.addPreference(preference);
+
+        assertThat(mFragment.removePreference(mScreen, "not" + key)).isFalse();
+        assertThat(mScreen.getPreferenceCount()).isEqualTo(1);
+    }
+
+    public static final class TestFragment extends SettingsPreferenceFragment {
+
+        @Override
+        public int getMetricsCategory() {
+            return 0;
+        }
+    }
+
+
+}
diff --git a/tests/robotests/src/com/android/settings/accounts/AccountPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/accounts/AccountPreferenceControllerTest.java
index f1ad142..79ea4da 100644
--- a/tests/robotests/src/com/android/settings/accounts/AccountPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/accounts/AccountPreferenceControllerTest.java
@@ -20,6 +20,8 @@
 import android.accounts.AuthenticatorDescription;
 import android.content.Context;
 import android.content.pm.UserInfo;
+import android.graphics.drawable.ColorDrawable;
+import android.graphics.drawable.Drawable;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.support.v7.preference.Preference;
@@ -36,6 +38,7 @@
 import com.android.settings.search.SearchIndexableRaw;
 import com.android.settings.testutils.shadow.ShadowAccountManager;
 import com.android.settings.testutils.shadow.ShadowContentResolver;
+import com.android.settingslib.accounts.AuthenticatorHelper;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -44,6 +47,8 @@
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 import org.robolectric.annotation.Config;
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
 import org.robolectric.shadows.ShadowApplication;
 
 import java.util.ArrayList;
@@ -211,12 +216,12 @@
         when(mUserManager.getProfiles(anyInt())).thenReturn(infos);
         AccessiblePreferenceCategory preferenceGroup = mock(AccessiblePreferenceCategory.class);
         when(mAccountHelper.createAccessiblePreferenceCategory(any(Context.class))).thenReturn(
-            preferenceGroup);
+                preferenceGroup);
 
         mController.onResume();
 
         verify(preferenceGroup).setTitle(
-            mContext.getString(R.string.account_for_section_header, "user 1"));
+                mContext.getString(R.string.account_for_section_header, "user 1"));
 
     }
 
@@ -309,7 +314,7 @@
         when(mUserManager.getProfiles(anyInt())).thenReturn(infos);
         when(mAccountHelper.hasBaseUserRestriction(
                 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE), anyInt()))
-            .thenReturn(true);
+                .thenReturn(true);
 
         mController.updateRawDataToIndex(data);
 
@@ -324,7 +329,7 @@
         when(mUserManager.isManagedProfile()).thenReturn(false);
         when(mUserManager.getProfiles(anyInt())).thenReturn(infos);
         when(mAccountHelper.hasBaseUserRestriction(
-            eq(UserManager.DISALLOW_MODIFY_ACCOUNTS), anyInt())).thenReturn(true);
+                eq(UserManager.DISALLOW_MODIFY_ACCOUNTS), anyInt())).thenReturn(true);
 
         mController.updateRawDataToIndex(data);
 
@@ -346,18 +351,18 @@
         accountType1[0] = new Account("Account11", "com.acct1");
         accountType1[1] = new Account("Account12", "com.acct1");
         when(mAccountManager.getAccountsByTypeAsUser(eq("com.acct1"), any(UserHandle.class)))
-            .thenReturn(accountType1);
+                .thenReturn(accountType1);
 
         AuthenticatorDescription[] authDescs = {
-            new AuthenticatorDescription("com.acct1", "com.android.settings",
-                R.string.account_settings_title, 0, 0, 0, false)
+                new AuthenticatorDescription("com.acct1", "com.android.settings",
+                        R.string.account_settings_title, 0, 0, 0, false)
         };
         when(mAccountManager.getAuthenticatorTypesAsUser(anyInt())).thenReturn(authDescs);
 
         AccessiblePreferenceCategory preferenceGroup = mock(AccessiblePreferenceCategory.class);
         when(preferenceGroup.getPreferenceManager()).thenReturn(mock(PreferenceManager.class));
         when(mAccountHelper.createAccessiblePreferenceCategory(any(Context.class))).thenReturn(
-            preferenceGroup);
+                preferenceGroup);
 
         mController.onResume();
 
@@ -366,7 +371,8 @@
     }
 
     @Test
-    @Config(shadows = {ShadowAccountManager.class, ShadowContentResolver.class})
+    @Config(shadows = {ShadowAccountManager.class, ShadowContentResolver.class,
+            ShadowAuthenticatorHelper.class})
     public void onResume_twoAccountsOfSameName_shouldAddFivePreferences() {
         final List<UserInfo> infos = new ArrayList<>();
         infos.add(new UserInfo(1, "user 1", 0));
@@ -425,25 +431,25 @@
         accountType1[0] = new Account("Acct11", "com.acct1");
         accountType1[1] = new Account("Acct12", "com.acct1");
         when(mAccountManager.getAccountsByTypeAsUser(eq("com.acct1"), any(UserHandle.class)))
-            .thenReturn(accountType1);
+                .thenReturn(accountType1);
 
         AuthenticatorDescription[] authDescs = {
-            new AuthenticatorDescription("com.acct1", "com.android.settings",
-                R.string.account_settings_title, 0, 0, 0, false)
+                new AuthenticatorDescription("com.acct1", "com.android.settings",
+                        R.string.account_settings_title, 0, 0, 0, false)
         };
         when(mAccountManager.getAuthenticatorTypesAsUser(anyInt())).thenReturn(authDescs);
 
         AccessiblePreferenceCategory preferenceGroup = mock(AccessiblePreferenceCategory.class);
         when(preferenceGroup.getPreferenceManager()).thenReturn(mock(PreferenceManager.class));
         when(mAccountHelper.createAccessiblePreferenceCategory(any(Context.class))).thenReturn(
-            preferenceGroup);
+                preferenceGroup);
         mController.onResume();
 
         mController.onResume();
 
         // each account should be added only once
-        verify(preferenceGroup).addPreference(argThat(new PreferenceMatcher("Acct11")));
-        verify(preferenceGroup).addPreference(argThat(new PreferenceMatcher("Acct12")));
+        verify(preferenceGroup).addPreference(argThat(titleMatches("Acct11")));
+        verify(preferenceGroup).addPreference(argThat(titleMatches("Acct12")));
     }
 
     @Test
@@ -460,18 +466,18 @@
         accountType1[0] = new Account("Acct11", "com.acct1");
         accountType1[1] = new Account("Acct12", "com.acct1");
         when(mAccountManager.getAccountsByTypeAsUser(eq("com.acct1"), any(UserHandle.class)))
-            .thenReturn(accountType1);
+                .thenReturn(accountType1);
 
         AuthenticatorDescription[] authDescs = {
-            new AuthenticatorDescription("com.acct1", "com.android.settings",
-                R.string.account_settings_title, 0, 0, 0, false)
+                new AuthenticatorDescription("com.acct1", "com.android.settings",
+                        R.string.account_settings_title, 0, 0, 0, false)
         };
         when(mAccountManager.getAuthenticatorTypesAsUser(anyInt())).thenReturn(authDescs);
 
         AccessiblePreferenceCategory preferenceGroup = mock(AccessiblePreferenceCategory.class);
         when(preferenceGroup.getPreferenceManager()).thenReturn(mock(PreferenceManager.class));
         when(mAccountHelper.createAccessiblePreferenceCategory(any(Context.class))).thenReturn(
-            preferenceGroup);
+                preferenceGroup);
 
         mController.onResume();
 
@@ -481,14 +487,14 @@
         accountType1[1] = new Account("Acct12", "com.acct1");
         accountType1[2] = new Account("Acct13", "com.acct1");
         when(mAccountManager.getAccountsByTypeAsUser(eq("com.acct1"), any(UserHandle.class)))
-            .thenReturn(accountType1);
+                .thenReturn(accountType1);
 
         mController.onResume();
 
         // each account should be added only once
-        verify(preferenceGroup, times(1)).addPreference(argThat(new PreferenceMatcher("Acct11")));
-        verify(preferenceGroup, times(1)).addPreference(argThat(new PreferenceMatcher("Acct12")));
-        verify(preferenceGroup, times(1)).addPreference(argThat(new PreferenceMatcher("Acct13")));
+        verify(preferenceGroup, times(1)).addPreference(argThat(titleMatches("Acct11")));
+        verify(preferenceGroup, times(1)).addPreference(argThat(titleMatches("Acct12")));
+        verify(preferenceGroup, times(1)).addPreference(argThat(titleMatches("Acct13")));
     }
 
     @Test
@@ -504,7 +510,7 @@
         AccessiblePreferenceCategory preferenceGroup = mock(AccessiblePreferenceCategory.class);
         when(preferenceGroup.getPreferenceManager()).thenReturn(mock(PreferenceManager.class));
         when(mAccountHelper.createAccessiblePreferenceCategory(any(Context.class))).thenReturn(
-            preferenceGroup);
+                preferenceGroup);
 
         // First time resume will build the UI with no account
         mController.onResume();
@@ -513,18 +519,18 @@
         Account[] accounts = {new Account("Acct1", "com.acct1")};
         when(mAccountManager.getAccountsAsUser(2)).thenReturn(accounts);
         when(mAccountManager.getAccountsByTypeAsUser(eq("com.acct1"), any(UserHandle.class)))
-            .thenReturn(accounts);
+                .thenReturn(accounts);
 
         AuthenticatorDescription[] authDescs = {
-            new AuthenticatorDescription("com.acct1", "com.android.settings",
-                R.string.account_settings_title, 0, 0, 0, false)
+                new AuthenticatorDescription("com.acct1", "com.android.settings",
+                        R.string.account_settings_title, 0, 0, 0, false)
         };
         when(mAccountManager.getAuthenticatorTypesAsUser(anyInt())).thenReturn(authDescs);
 
         // Resume should show the newly added account
         mController.onResume();
 
-        verify(preferenceGroup).addPreference(argThat(new PreferenceMatcher("Acct1")));
+        verify(preferenceGroup).addPreference(argThat(titleMatches("Acct1")));
     }
 
     @Test
@@ -542,18 +548,18 @@
         accountType1[0] = new Account("Acct11", "com.acct1");
         accountType1[1] = new Account("Acct12", "com.acct1");
         when(mAccountManager.getAccountsByTypeAsUser(eq("com.acct1"), any(UserHandle.class)))
-            .thenReturn(accountType1);
+                .thenReturn(accountType1);
 
         AuthenticatorDescription[] authDescs = {
-            new AuthenticatorDescription("com.acct1", "com.android.settings",
-                R.string.account_settings_title, 0, 0, 0, false)
+                new AuthenticatorDescription("com.acct1", "com.android.settings",
+                        R.string.account_settings_title, 0, 0, 0, false)
         };
         when(mAccountManager.getAuthenticatorTypesAsUser(anyInt())).thenReturn(authDescs);
 
         AccessiblePreferenceCategory preferenceGroup = mock(AccessiblePreferenceCategory.class);
         when(preferenceGroup.getPreferenceManager()).thenReturn(mock(PreferenceManager.class));
         when(mAccountHelper.createAccessiblePreferenceCategory(any(Context.class))).thenReturn(
-            preferenceGroup);
+                preferenceGroup);
 
         mController.onResume();
 
@@ -561,29 +567,24 @@
         accountType1 = new Account[1];
         accountType1[0] = new Account("Acct11", "com.acct1");
         when(mAccountManager.getAccountsByTypeAsUser(eq("com.acct1"), any(UserHandle.class)))
-            .thenReturn(accountType1);
+                .thenReturn(accountType1);
 
         mController.onResume();
 
-        verify(preferenceGroup, times(1)).addPreference(argThat(new PreferenceMatcher("Acct11")));
-        verify(preferenceGroup, times(1)).addPreference(argThat(new PreferenceMatcher("Acct12")));
-        verify(preferenceGroup, times(1)).removePreference(
-            argThat(new PreferenceMatcher("Acct12")));
+        verify(preferenceGroup, times(1)).addPreference(argThat(titleMatches("Acct11")));
+        verify(preferenceGroup, times(1)).addPreference(argThat(titleMatches("Acct12")));
+        verify(preferenceGroup, times(1)).removePreference(argThat(titleMatches("Acct12")));
     }
 
-    private static class PreferenceMatcher extends ArgumentMatcher<Preference> {
-
-        private final String mExpectedTitle;
-
-        public PreferenceMatcher(String title) {
-            mExpectedTitle = title;
-        }
-
-        @Override
-        public boolean matches(Object arg) {
-            final Preference preference = (Preference) arg;
-            return TextUtils.equals(mExpectedTitle, preference.getTitle());
-        }
+    private static ArgumentMatcher<Preference> titleMatches(String expected) {
+        return preference -> TextUtils.equals(expected, preference.getTitle());
     }
 
+    @Implements(AuthenticatorHelper.class)
+    public static class ShadowAuthenticatorHelper {
+        @Implementation
+        public Drawable getDrawableForType(Context context, final String accountType) {
+            return new ColorDrawable();
+        }
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/accounts/RemoveAccountPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/accounts/RemoveAccountPreferenceControllerTest.java
index 033465b..76c560c 100644
--- a/tests/robotests/src/com/android/settings/accounts/RemoveAccountPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/accounts/RemoveAccountPreferenceControllerTest.java
@@ -15,6 +15,16 @@
  */
 package com.android.settings.accounts;
 
+import static org.mockito.Answers.RETURNS_DEEP_STUBS;
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import android.accounts.Account;
 import android.accounts.AccountManager;
 import android.accounts.AccountManagerCallback;
@@ -26,17 +36,14 @@
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.UserHandle;
-import android.support.v7.preference.PreferenceScreen;
 import android.support.v14.preference.PreferenceFragment;
+import android.support.v7.preference.PreferenceScreen;
 import android.widget.Button;
 
-import com.android.settings.AccessiblePreferenceCategory;
 import com.android.settings.R;
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
 import com.android.settings.applications.LayoutPreference;
-import com.android.settings.search.SearchIndexableRaw;
-import com.android.settings.testutils.FakeFeatureFactory;
 import com.android.settings.testutils.shadow.ShadowAccountManager;
 import com.android.settings.testutils.shadow.ShadowContentResolver;
 
@@ -48,16 +55,6 @@
 import org.robolectric.annotation.Config;
 import org.robolectric.shadows.ShadowApplication;
 
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Answers.RETURNS_DEEP_STUBS;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class RemoveAccountPreferenceControllerTest {
@@ -134,7 +131,7 @@
                     mFragment, account, userHandle);
         dialog.onCreate(new Bundle());
         dialog.onClick(null, 0);
-        verify(mAccountManager).removeAccountAsUser(eq(account), any(Activity.class),
-            any(AccountManagerCallback.class), any(Handler.class), eq(userHandle));
+        verify(mAccountManager).removeAccountAsUser(eq(account), nullable(Activity.class),
+            nullable(AccountManagerCallback.class), nullable(Handler.class), eq(userHandle));
     }
 }
\ No newline at end of file
diff --git a/tests/robotests/src/com/android/settings/applications/AdvancedAppSettingsTest.java b/tests/robotests/src/com/android/settings/applications/AdvancedAppSettingsTest.java
index 0c3c160..6960575 100644
--- a/tests/robotests/src/com/android/settings/applications/AdvancedAppSettingsTest.java
+++ b/tests/robotests/src/com/android/settings/applications/AdvancedAppSettingsTest.java
@@ -17,16 +17,19 @@
 package com.android.settings.applications;
 
 import android.content.Context;
+import android.content.pm.PackageManager;
+import android.os.UserManager;
+import android.telephony.TelephonyManager;
 
 import com.android.settings.R;
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
-
 import com.android.settings.applications.defaultapps.DefaultBrowserPreferenceController;
 import com.android.settings.applications.defaultapps.DefaultPhonePreferenceController;
 import com.android.settings.applications.defaultapps.DefaultSmsPreferenceController;
 import com.android.settings.dashboard.SummaryLoader;
 import com.android.settings.testutils.XmlTestUtils;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -38,8 +41,10 @@
 import java.util.List;
 
 import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.anyString;
 import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.spy;
@@ -73,18 +78,18 @@
     public void setListening_shouldUpdateSummary() {
         final SummaryLoader summaryLoader = mock(SummaryLoader.class);
         final AdvancedAppSettings.SummaryProvider summaryProvider =
-            new AdvancedAppSettings.SummaryProvider(mContext, summaryLoader);
+                new AdvancedAppSettings.SummaryProvider(mContext, summaryLoader);
         final DefaultSmsPreferenceController defaultSms =
-            mock(DefaultSmsPreferenceController.class);
+                mock(DefaultSmsPreferenceController.class);
         final DefaultBrowserPreferenceController defaultBrowser =
-            mock(DefaultBrowserPreferenceController.class);
+                mock(DefaultBrowserPreferenceController.class);
         final DefaultPhonePreferenceController defaultPhone =
-            mock(DefaultPhonePreferenceController.class);
+                mock(DefaultPhonePreferenceController.class);
         ReflectionHelpers.setField(summaryProvider, "mDefaultSmsPreferenceController", defaultSms);
         ReflectionHelpers.setField(
-            summaryProvider, "mDefaultBrowserPreferenceController", defaultBrowser);
+                summaryProvider, "mDefaultBrowserPreferenceController", defaultBrowser);
         ReflectionHelpers.setField(
-            summaryProvider, "mDefaultPhonePreferenceController", defaultPhone);
+                summaryProvider, "mDefaultPhonePreferenceController", defaultPhone);
 
         // all available
         when(defaultSms.getDefaultAppLabel()).thenReturn("Sms1");
@@ -140,12 +145,23 @@
 
     }
 
-
     @Test
     public void testNonIndexableKeys_existInXmlLayout() {
         final Context context = spy(RuntimeEnvironment.application);
+        final Context mockContext = mock(Context.class);
+        final UserManager userManager = mock(UserManager.class, RETURNS_DEEP_STUBS);
+
+        when(mockContext.getSystemService(Context.USER_SERVICE))
+                .thenReturn(userManager);
+        when(userManager.getUserInfo(anyInt()).isRestricted()).thenReturn(true);
+
+        when(mockContext.getSystemService(Context.TELEPHONY_SERVICE))
+                .thenReturn(mock(TelephonyManager.class));
+        when(mockContext.getPackageManager())
+                .thenReturn(mock(PackageManager.class));
         final List<String> niks = AdvancedAppSettings.SEARCH_INDEX_DATA_PROVIDER
-                .getNonIndexableKeys(context);
+                .getNonIndexableKeys(mockContext);
+
         final int xmlId = (new AdvancedAppSettings()).getPreferenceScreenResId();
 
         final List<String> keys = XmlTestUtils.getKeysFromPreferenceXml(context, xmlId);
diff --git a/tests/robotests/src/com/android/settings/applications/DrawOverlayDetailsTest.java b/tests/robotests/src/com/android/settings/applications/DrawOverlayDetailsTest.java
index ef6351a..409a600 100644
--- a/tests/robotests/src/com/android/settings/applications/DrawOverlayDetailsTest.java
+++ b/tests/robotests/src/com/android/settings/applications/DrawOverlayDetailsTest.java
@@ -16,6 +16,10 @@
 
 package com.android.settings.applications;
 
+import static org.mockito.Matchers.eq;
+import static org.mockito.Matchers.nullable;
+import static org.mockito.Mockito.verify;
+
 import android.content.Context;
 
 import com.android.internal.logging.nano.MetricsProto;
@@ -35,10 +39,6 @@
 import org.robolectric.shadows.ShadowApplication;
 import org.robolectric.util.ReflectionHelpers;
 
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.verify;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class DrawOverlayDetailsTest {
@@ -66,11 +66,11 @@
     public void logSpecialPermissionChange() {
         mFragment.onAttach(ShadowApplication.getInstance().getApplicationContext());
         mFragment.logSpecialPermissionChange(true, "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_APPDRAW_ALLOW), eq("app"));
 
         mFragment.logSpecialPermissionChange(false, "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_APPDRAW_DENY), eq("app"));
     }
 
diff --git a/tests/robotests/src/com/android/settings/applications/FetchPackageStorageAsyncLoaderTest.java b/tests/robotests/src/com/android/settings/applications/FetchPackageStorageAsyncLoaderTest.java
index 36116c0..a69ee6c 100644
--- a/tests/robotests/src/com/android/settings/applications/FetchPackageStorageAsyncLoaderTest.java
+++ b/tests/robotests/src/com/android/settings/applications/FetchPackageStorageAsyncLoaderTest.java
@@ -18,6 +18,7 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.mock;
@@ -63,7 +64,8 @@
         when(stats.getCodeBytes()).thenReturn(1L);
         when(stats.getDataBytes()).thenReturn(2L);
         when(stats.getCacheBytes()).thenReturn(3L);
-        when(mSource.getStatsForPackage(anyString(), anyString(), any(UserHandle.class)))
+        when(mSource.getStatsForPackage(nullable(String.class), nullable(String.class),
+                any(UserHandle.class)))
                 .thenReturn(stats);
         ApplicationInfo info = new ApplicationInfo();
         info.packageName = PACKAGE_NAME;
diff --git a/tests/robotests/src/com/android/settings/applications/InstalledAppCounterTest.java b/tests/robotests/src/com/android/settings/applications/InstalledAppCounterTest.java
index 37fa9d7..159d693 100644
--- a/tests/robotests/src/com/android/settings/applications/InstalledAppCounterTest.java
+++ b/tests/robotests/src/com/android/settings/applications/InstalledAppCounterTest.java
@@ -16,13 +16,25 @@
 
 package com.android.settings.applications;
 
+import static com.android.settings.testutils.ApplicationTestUtils.buildInfo;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.content.pm.UserInfo;
-import android.os.Build;
 import android.os.UserHandle;
 import android.os.UserManager;
 
@@ -41,20 +53,9 @@
 
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.List;
+import java.util.Collections;
 import java.util.Set;
 
-import static com.android.settings.testutils.ApplicationTestUtils.buildInfo;
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.argThat;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.atLeast;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
-
 /**
  * Tests for {@link InstalledAppCounter}.
  */
@@ -113,11 +114,12 @@
 
     private void expectQueryIntentActivities(int userId, String packageName, boolean launchable) {
         when(mPackageManager.queryIntentActivitiesAsUser(
-                argThat(new IsLaunchIntentFor(packageName)),
+                argThat(isLaunchIntentFor(packageName)),
                 eq(PackageManager.GET_DISABLED_COMPONENTS | PackageManager.MATCH_DIRECT_BOOT_AWARE
                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE),
-                eq(userId))).thenReturn(launchable ? Arrays.asList(new ResolveInfo())
-                : new ArrayList<ResolveInfo>());
+                eq(userId))).thenReturn(launchable
+                        ? Collections.singletonList(new ResolveInfo())
+                        : new ArrayList<>());
     }
 
     private void testCountInstalledAppsAcrossAllUsers(boolean async) {
@@ -136,7 +138,7 @@
         verify(mPackageManager).getInstalledApplicationsAsUser(anyInt(), eq(MAIN_USER_ID));
         verify(mPackageManager).getInstalledApplicationsAsUser(anyInt(),
                 eq(MANAGED_PROFILE_ID));
-        verify(mPackageManager, atLeast(0)).queryIntentActivitiesAsUser(anyObject(), anyInt(),
+        verify(mPackageManager, atLeast(0)).queryIntentActivitiesAsUser(any(Intent.class), anyInt(),
                 anyInt());
         verifyNoMoreInteractions(mPackageManager);
 
@@ -251,16 +253,8 @@
         }
     }
 
-    private static class IsLaunchIntentFor extends ArgumentMatcher<Intent> {
-        private final String mPackageName;
-
-        IsLaunchIntentFor(String packageName) {
-            mPackageName = packageName;
-        }
-
-        @Override
-        public boolean matches(Object i) {
-            final Intent intent = (Intent) i;
+    private ArgumentMatcher<Intent> isLaunchIntentFor(String packageName) {
+        return intent -> {
             if (intent == null) {
                 return false;
             }
@@ -272,10 +266,10 @@
                     !categories.contains(Intent.CATEGORY_LAUNCHER)) {
                 return false;
             }
-            if (!mPackageName.equals(intent.getPackage())) {
+            if (!packageName.equals(intent.getPackage())) {
                 return false;
             }
             return true;
-        }
+        };
     }
 }
diff --git a/tests/robotests/src/com/android/settings/applications/InstalledAppDetailsTest.java b/tests/robotests/src/com/android/settings/applications/InstalledAppDetailsTest.java
index f602236..f57bfe3 100644
--- a/tests/robotests/src/com/android/settings/applications/InstalledAppDetailsTest.java
+++ b/tests/robotests/src/com/android/settings/applications/InstalledAppDetailsTest.java
@@ -19,10 +19,9 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
-import static org.mockito.Matchers.any;
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.anyDouble;
 import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
@@ -32,6 +31,7 @@
 import static org.mockito.Mockito.when;
 
 import android.app.AlertDialog;
+import android.app.Fragment;
 import android.app.admin.DevicePolicyManager;
 import android.content.Context;
 import android.content.Intent;
@@ -53,6 +53,7 @@
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
 import com.android.settings.applications.instantapps.InstantAppButtonsController;
+import com.android.settings.applications.instantapps.InstantAppButtonsController.ShowDialogDelegate;
 import com.android.settings.fuelgauge.BatteryUtils;
 import com.android.settings.testutils.FakeFeatureFactory;
 import com.android.settingslib.applications.AppUtils;
@@ -137,7 +138,7 @@
 
     @Test
     public void shouldShowUninstallForAll_installForOneOtherUserOnly_shouldReturnTrue() {
-        when(mDevicePolicyManager.packageHasActiveAdmins(anyString())).thenReturn(false);
+        when(mDevicePolicyManager.packageHasActiveAdmins(nullable(String.class))).thenReturn(false);
         when(mUserManager.getUsers().size()).thenReturn(2);
         ReflectionHelpers.setField(mAppDetail, "mDpm", mDevicePolicyManager);
         ReflectionHelpers.setField(mAppDetail, "mUserManager", mUserManager);
@@ -153,7 +154,7 @@
 
     @Test
     public void shouldShowUninstallForAll_installForSelfOnly_shouldReturnFalse() {
-        when(mDevicePolicyManager.packageHasActiveAdmins(anyString())).thenReturn(false);
+        when(mDevicePolicyManager.packageHasActiveAdmins(nullable(String.class))).thenReturn(false);
         when(mUserManager.getUsers().size()).thenReturn(2);
         ReflectionHelpers.setField(mAppDetail, "mDpm", mDevicePolicyManager);
         ReflectionHelpers.setField(mAppDetail, "mUserManager", mUserManager);
@@ -239,7 +240,7 @@
         // Make this app appear to be instant.
         ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
                 (InstantAppDataProvider) (i -> true));
-        when(mDevicePolicyManager.packageHasActiveAdmins(anyString())).thenReturn(false);
+        when(mDevicePolicyManager.packageHasActiveAdmins(nullable(String.class))).thenReturn(false);
         when(mUserManager.getUsers().size()).thenReturn(2);
 
         final ApplicationInfo info = new ApplicationInfo();
@@ -349,16 +350,18 @@
 
         final InstantAppButtonsController buttonsController =
                 mock(InstantAppButtonsController.class);
-        when(buttonsController.setPackageName(anyString())).thenReturn(buttonsController);
+        when(buttonsController.setPackageName(nullable(String.class)))
+                .thenReturn(buttonsController);
 
         FakeFeatureFactory.setupForTest(mContext);
         FakeFeatureFactory factory =
                 (FakeFeatureFactory) FakeFeatureFactory.getFactory(mContext);
         when(factory.applicationFeatureProvider.newInstantAppButtonsController(
-                any(), any(), any())).thenReturn(buttonsController);
+                nullable(Fragment.class), nullable(View.class), nullable(ShowDialogDelegate.class)))
+                .thenReturn(buttonsController);
 
         fragment.maybeAddInstantAppButtons();
-        verify(buttonsController).setPackageName(anyString());
+        verify(buttonsController).setPackageName(nullable(String.class));
         verify(buttonsController).show();
     }
 
diff --git a/tests/robotests/src/com/android/settings/applications/InstalledAppListerTest.java b/tests/robotests/src/com/android/settings/applications/InstalledAppListerTest.java
index 76421c2..6baa8c9 100644
--- a/tests/robotests/src/com/android/settings/applications/InstalledAppListerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/InstalledAppListerTest.java
@@ -87,11 +87,12 @@
 
     private void expectQueryIntentActivities(int userId, String packageName, boolean launchable) {
         when(mPackageManager.queryIntentActivitiesAsUser(
-                argThat(new IsLaunchIntentFor(packageName)),
+                argThat(isLaunchIntentFor(packageName)),
                 eq(PackageManager.GET_DISABLED_COMPONENTS | PackageManager.MATCH_DIRECT_BOOT_AWARE
                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE),
-                eq(userId))).thenReturn(launchable ? Arrays.asList(new ResolveInfo())
-                        : new ArrayList<ResolveInfo>());
+                eq(userId))).thenReturn(launchable
+                        ? Collections.singletonList(new ResolveInfo())
+                        : Collections.emptyList());
     }
 
     @Test
@@ -203,16 +204,8 @@
         }
     }
 
-    private static class IsLaunchIntentFor extends ArgumentMatcher<Intent> {
-        private final String mPackageName;
-
-        IsLaunchIntentFor(String packageName) {
-            mPackageName = packageName;
-        }
-
-        @Override
-        public boolean matches(Object i) {
-            final Intent intent = (Intent) i;
+    private static ArgumentMatcher<Intent> isLaunchIntentFor(String packageName) {
+        return intent -> {
             if (intent == null) {
                 return false;
             }
@@ -224,10 +217,10 @@
                     !categories.contains(Intent.CATEGORY_LAUNCHER)) {
                 return false;
             }
-            if (!mPackageName.equals(intent.getPackage())) {
+            if (!packageName.equals(intent.getPackage())) {
                 return false;
             }
             return true;
-        }
+        };
     }
 }
diff --git a/tests/robotests/src/com/android/settings/applications/MusicViewHolderControllerTest.java b/tests/robotests/src/com/android/settings/applications/MusicViewHolderControllerTest.java
index 6440141..9143365 100644
--- a/tests/robotests/src/com/android/settings/applications/MusicViewHolderControllerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/MusicViewHolderControllerTest.java
@@ -18,7 +18,7 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
-import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.nullable;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
@@ -32,8 +32,8 @@
 
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
-import com.android.settingslib.deviceinfo.StorageVolumeProvider;
 import com.android.settingslib.applications.StorageStatsSource;
+import com.android.settingslib.deviceinfo.StorageVolumeProvider;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -82,7 +82,7 @@
 
     @Test
     public void storageShouldRepresentStorageStatsQuery() throws Exception {
-        when(mSource.getExternalStorageStats(any(String.class), any(UserHandle.class))).thenReturn(
+        when(mSource.getExternalStorageStats(nullable(String.class), nullable(UserHandle.class))).thenReturn(
                 new StorageStatsSource.ExternalStorageStats(1, 1, 0, 0));
 
         mController.queryStats();
diff --git a/tests/robotests/src/com/android/settings/applications/PictureInPictureDetailsTest.java b/tests/robotests/src/com/android/settings/applications/PictureInPictureDetailsTest.java
index 96a10f1..3c2589d 100644
--- a/tests/robotests/src/com/android/settings/applications/PictureInPictureDetailsTest.java
+++ b/tests/robotests/src/com/android/settings/applications/PictureInPictureDetailsTest.java
@@ -16,6 +16,12 @@
 
 package com.android.settings.applications;
 
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.verify;
+
 import android.content.Context;
 
 import com.android.internal.logging.nano.MetricsProto;
@@ -30,12 +36,6 @@
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 import org.robolectric.annotation.Config;
-import org.robolectric.util.ReflectionHelpers;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.verify;
 
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
@@ -83,11 +83,11 @@
     @Test
     public void logSpecialPermissionChange() {
         mFragment.logSpecialPermissionChange(true, "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_PICTURE_IN_PICTURE_ALLOW), eq("app"));
 
         mFragment.logSpecialPermissionChange(false, "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_PICTURE_IN_PICTURE_DENY), eq("app"));
     }
 
diff --git a/tests/robotests/src/com/android/settings/applications/PremiumSmsAccessTest.java b/tests/robotests/src/com/android/settings/applications/PremiumSmsAccessTest.java
index d9c88ff..6474e09 100644
--- a/tests/robotests/src/com/android/settings/applications/PremiumSmsAccessTest.java
+++ b/tests/robotests/src/com/android/settings/applications/PremiumSmsAccessTest.java
@@ -16,6 +16,10 @@
 
 package com.android.settings.applications;
 
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.verify;
+
 import android.content.Context;
 
 import com.android.internal.logging.nano.MetricsProto;
@@ -33,10 +37,6 @@
 import org.robolectric.annotation.Config;
 import org.robolectric.shadows.ShadowApplication;
 
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.verify;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class PremiumSmsAccessTest {
@@ -60,17 +60,17 @@
     public void logSpecialPermissionChange() {
         mFragment.logSpecialPermissionChange(SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ASK_USER,
                 "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_PREMIUM_SMS_ASK), eq("app"));
 
         mFragment.logSpecialPermissionChange(SmsUsageMonitor.PREMIUM_SMS_PERMISSION_NEVER_ALLOW,
                 "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_PREMIUM_SMS_DENY), eq("app"));
 
         mFragment.logSpecialPermissionChange(SmsUsageMonitor.PREMIUM_SMS_PERMISSION_ALWAYS_ALLOW,
                 "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_PREMIUM_SMS_ALWAYS_ALLOW),
                 eq("app"));
     }
diff --git a/tests/robotests/src/com/android/settings/applications/RecentAppsPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/applications/RecentAppsPreferenceControllerTest.java
index c28eed0..4ddea13 100644
--- a/tests/robotests/src/com/android/settings/applications/RecentAppsPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/RecentAppsPreferenceControllerTest.java
@@ -178,7 +178,7 @@
         // it's invalid app.
         verify(mCategory, times(1)).addPreference(any(Preference.class));
 
-        verify(mSeeAllPref).setTitle(R.string.see_all_apps_title);
+        verify(mSeeAllPref).setSummary(null);
         verify(mSeeAllPref).setIcon(R.drawable.ic_chevron_right_24dp);
     }
 
diff --git a/tests/robotests/src/com/android/settings/applications/UsageAccessDetailsTest.java b/tests/robotests/src/com/android/settings/applications/UsageAccessDetailsTest.java
index 532a923..5b381fc 100644
--- a/tests/robotests/src/com/android/settings/applications/UsageAccessDetailsTest.java
+++ b/tests/robotests/src/com/android/settings/applications/UsageAccessDetailsTest.java
@@ -16,6 +16,10 @@
 
 package com.android.settings.applications;
 
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.verify;
+
 import android.content.Context;
 
 import com.android.internal.logging.nano.MetricsProto;
@@ -32,10 +36,6 @@
 import org.robolectric.annotation.Config;
 import org.robolectric.shadows.ShadowApplication;
 
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.verify;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class UsageAccessDetailsTest {
@@ -58,11 +58,11 @@
     @Test
     public void logSpecialPermissionChange() {
         mFragment.logSpecialPermissionChange(true, "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_USAGE_VIEW_ALLOW), eq("app"));
 
         mFragment.logSpecialPermissionChange(false, "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_USAGE_VIEW_DENY), eq("app"));
     }
 }
diff --git a/tests/robotests/src/com/android/settings/applications/VrListenerSettingsTest.java b/tests/robotests/src/com/android/settings/applications/VrListenerSettingsTest.java
index 3abe3f4..f1655d5 100644
--- a/tests/robotests/src/com/android/settings/applications/VrListenerSettingsTest.java
+++ b/tests/robotests/src/com/android/settings/applications/VrListenerSettingsTest.java
@@ -16,6 +16,10 @@
 
 package com.android.settings.applications;
 
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.verify;
+
 import android.content.Context;
 
 import com.android.internal.logging.nano.MetricsProto;
@@ -31,10 +35,6 @@
 import org.mockito.MockitoAnnotations;
 import org.robolectric.annotation.Config;
 
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.verify;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class VrListenerSettingsTest {
@@ -56,11 +56,11 @@
     @Test
     public void logSpecialPermissionChange() {
         mFragment.logSpecialPermissionChange(true, "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_VRHELPER_ALLOW), eq("app"));
 
         mFragment.logSpecialPermissionChange(false, "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_VRHELPER_DENY), eq("app"));
     }
 }
diff --git a/tests/robotests/src/com/android/settings/applications/WriteSettingsDetailsTest.java b/tests/robotests/src/com/android/settings/applications/WriteSettingsDetailsTest.java
index a632118..3297dbf 100644
--- a/tests/robotests/src/com/android/settings/applications/WriteSettingsDetailsTest.java
+++ b/tests/robotests/src/com/android/settings/applications/WriteSettingsDetailsTest.java
@@ -16,6 +16,10 @@
 
 package com.android.settings.applications;
 
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.verify;
+
 import android.content.Context;
 
 import com.android.internal.logging.nano.MetricsProto;
@@ -31,10 +35,6 @@
 import org.mockito.MockitoAnnotations;
 import org.robolectric.annotation.Config;
 
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.verify;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class WriteSettingsDetailsTest {
@@ -56,12 +56,12 @@
     @Test
     public void logSpecialPermissionChange() {
         mFragment.logSpecialPermissionChange(true, "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_SETTINGS_CHANGE_ALLOW),
                 eq("app"));
 
         mFragment.logSpecialPermissionChange(false, "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_SETTINGS_CHANGE_DENY),
                 eq("app"));
     }
diff --git a/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultAppPickerFragmentTest.java b/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultAppPickerFragmentTest.java
index 2d9ae9b..c138070 100644
--- a/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultAppPickerFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultAppPickerFragmentTest.java
@@ -17,18 +17,16 @@
 package com.android.settings.applications.defaultapps;
 
 
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
 import android.app.Activity;
 import android.content.Context;
 import android.os.UserManager;
 import android.support.v7.preference.PreferenceScreen;
+import android.util.Pair;
 
+import com.android.internal.logging.nano.MetricsProto;
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
+import com.android.settings.testutils.FakeFeatureFactory;
 import com.android.settings.widget.RadioButtonPreference;
 
 import org.junit.Before;
@@ -43,6 +41,13 @@
 import java.util.ArrayList;
 import java.util.List;
 
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class DefaultAppPickerFragmentTest {
@@ -54,11 +59,13 @@
     @Mock
     private UserManager mUserManager;
 
+    private FakeFeatureFactory mFeatureFactory;
     private TestFragment mFragment;
 
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
+        mFeatureFactory = FakeFeatureFactory.setupForTest(mActivity);
         mFragment = spy(new TestFragment());
 
         when(mActivity.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
@@ -68,6 +75,7 @@
 
     @Test
     public void clickPreference_hasConfirmation_shouldShowConfirmation() {
+        mFragment.onAttach((Context) mActivity);
         final RadioButtonPreference pref =
                 new RadioButtonPreference(RuntimeEnvironment.application);
         pref.setKey("TEST");
@@ -78,6 +86,17 @@
         mFragment.onRadioButtonClicked(pref);
     }
 
+    @Test
+    public void onRadioButtonConfirmed_shouldLog() {
+        mFragment.onAttach((Context) mActivity);
+        mFragment.onRadioButtonConfirmed("test_pkg");
+
+        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+                eq(MetricsProto.MetricsEvent.ACTION_SETTINGS_UPDATE_DEFAULT_APP),
+                eq("test_pkg"),
+                any(Pair.class));
+    }
+
     public static class TestFragment extends DefaultAppPickerFragment {
 
         boolean setDefaultAppKeyCalled;
diff --git a/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultHomePickerTest.java b/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultHomePickerTest.java
index 38104a9..f425d2f 100644
--- a/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultHomePickerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultHomePickerTest.java
@@ -16,11 +16,17 @@
 
 package com.android.settings.applications.defaultapps;
 
-
 import android.app.Activity;
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.IntentFilter;
+import android.content.pm.ActivityInfo;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.pm.ResolveInfo;
+import android.content.pm.UserInfo;
+import android.os.Build;
 import android.os.UserManager;
 
 import com.android.settings.SettingsRobolectricTestRunner;
@@ -33,14 +39,22 @@
 import org.mockito.Answers;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
 import org.robolectric.annotation.Config;
 import org.robolectric.util.ReflectionHelpers;
 
+import java.util.ArrayList;
+import java.util.List;
+
 import static com.google.common.truth.Truth.assertThat;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.anyList;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
@@ -55,7 +69,9 @@
     @Mock
     private UserManager mUserManager;
     @Mock
-    private PackageManagerWrapper mPackageManager;
+    private PackageManagerWrapper mPackageManagerWrapper;
+    @Mock
+    private PackageManager mPackageManager;
 
     private DefaultHomePicker mPicker;
 
@@ -63,28 +79,89 @@
     public void setUp() {
         MockitoAnnotations.initMocks(this);
         when(mActivity.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
+        when(mPackageManagerWrapper.getPackageManager()).thenReturn(mPackageManager);
 
-        mPicker = new DefaultHomePicker();
+        mPicker = spy(new DefaultHomePicker());
         mPicker.onAttach((Context) mActivity);
 
-        ReflectionHelpers.setField(mPicker, "mPm", mPackageManager);
+        ReflectionHelpers.setField(mPicker, "mPm", mPackageManagerWrapper);
+        doReturn(RuntimeEnvironment.application).when(mPicker).getContext();
     }
 
     @Test
     public void setDefaultAppKey_shouldUpdateDefault() {
         assertThat(mPicker.setDefaultKey(TEST_APP_KEY)).isTrue();
 
-        verify(mPackageManager).replacePreferredActivity(any(IntentFilter.class),
+        verify(mPackageManagerWrapper).replacePreferredActivity(any(IntentFilter.class),
                 anyInt(), any(ComponentName[].class), any(ComponentName.class));
     }
 
     @Test
     public void getDefaultAppKey_shouldReturnDefault() {
         final ComponentName cn = mock(ComponentName.class);
-        when(mPackageManager.getHomeActivities(anyList()))
+        when(mPackageManagerWrapper.getHomeActivities(anyList()))
                 .thenReturn(cn);
         mPicker.getDefaultKey();
         verify(cn).flattenToString();
     }
 
+    @Test
+    public void getCandidates_allLaunchersAvailableIfNoManagedProfile()
+            throws NameNotFoundException {
+        addLaunchers();
+        List<DefaultAppInfo> candidates = mPicker.getCandidates();
+        assertThat(candidates.size()).isEqualTo(2);
+        assertThat(candidates.get(0).summary).isNull();
+        assertThat(candidates.get(0).enabled).isTrue();
+        assertThat(candidates.get(1).summary).isNull();
+        assertThat(candidates.get(1).enabled).isTrue();
+    }
+
+    @Test
+    public void getCandidates_onlyLollipopPlusLaunchersAvailableIfManagedProfile()
+            throws NameNotFoundException {
+        createManagedProfile();
+        addLaunchers();
+        List<DefaultAppInfo> candidates = mPicker.getCandidates();
+        assertThat(candidates.size()).isEqualTo(2);
+        DefaultAppInfo lollipopPlusLauncher = candidates.get(0);
+        assertThat(lollipopPlusLauncher.summary).isNull();
+        assertThat(lollipopPlusLauncher.enabled).isTrue();
+
+        DefaultAppInfo preLollipopLauncher = candidates.get(1);
+        assertThat(preLollipopLauncher.summary).isNotNull();
+        assertThat(preLollipopLauncher.enabled).isFalse();
+    }
+
+    private void createManagedProfile() {
+        ArrayList<UserInfo> profiles = new ArrayList<UserInfo>();
+        profiles.add(new UserInfo(/*id=*/ 10, "TestUserName", UserInfo.FLAG_MANAGED_PROFILE));
+        when(mUserManager.getProfiles(anyInt())).thenReturn(profiles);
+    }
+
+    private ResolveInfo createLauncher(
+            String packageName, String className, int targetSdk) throws NameNotFoundException {
+        ResolveInfo launcher = new ResolveInfo();
+        launcher.activityInfo = new ActivityInfo();
+        launcher.activityInfo.packageName = packageName;
+        launcher.activityInfo.name = className;
+        ApplicationInfo launcherAppInfo = new ApplicationInfo();
+        launcherAppInfo.targetSdkVersion = targetSdk;
+        when(mPackageManager.getApplicationInfo(eq(launcher.activityInfo.packageName), anyInt()))
+                .thenReturn(launcherAppInfo);
+        return launcher;
+    }
+
+    private void addLaunchers() throws NameNotFoundException {
+        doAnswer(invocation -> {
+                // The result of this method is stored in the first parameter...
+                List<ResolveInfo> parameter = (List<ResolveInfo>) invocation.getArguments()[0];
+                parameter.add(createLauncher(
+                        "package.1", "LollipopPlusLauncher", Build.VERSION_CODES.LOLLIPOP));
+                parameter.add(createLauncher(
+                        "package.2", "PreLollipopLauncher", Build.VERSION_CODES.KITKAT));
+                return null;
+                })
+                .when(mPackageManagerWrapper).getHomeActivities(anyList());
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/core/instrumentation/SharedPreferenceLoggerTest.java b/tests/robotests/src/com/android/settings/core/instrumentation/SharedPreferenceLoggerTest.java
index 3e24fcf..216026a 100644
--- a/tests/robotests/src/com/android/settings/core/instrumentation/SharedPreferenceLoggerTest.java
+++ b/tests/robotests/src/com/android/settings/core/instrumentation/SharedPreferenceLoggerTest.java
@@ -35,6 +35,8 @@
 import org.robolectric.annotation.Config;
 
 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent
+        .ACTION_SETTINGS_PREFERENCE_CHANGE;
+import static com.android.internal.logging.nano.MetricsProto.MetricsEvent
         .FIELD_SETTINGS_PREFERENCE_CHANGE_FLOAT_VALUE;
 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent
         .FIELD_SETTINGS_PREFERENCE_CHANGE_LONG_VALUE;
@@ -43,6 +45,7 @@
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.argThat;
+import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 
@@ -56,7 +59,7 @@
     @Mock(answer = Answers.RETURNS_DEEP_STUBS)
     private Context mContext;
 
-    private PairMatcher mNamePairMatcher;
+    private ArgumentMatcher<Pair<Integer, Object>> mNamePairMatcher;
     private FakeFeatureFactory mFactory;
     private MetricsFeatureProvider mMetricsFeature;
     private SharedPreferencesLogger mSharedPrefLogger;
@@ -69,7 +72,7 @@
         mMetricsFeature = mFactory.metricsFeatureProvider;
 
         mSharedPrefLogger = new SharedPreferencesLogger(mContext, TEST_TAG);
-        mNamePairMatcher = new PairMatcher(FIELD_SETTINGS_PREFERENCE_CHANGE_NAME, String.class);
+        mNamePairMatcher = pairMatches(FIELD_SETTINGS_PREFERENCE_CHANGE_NAME, String.class);
     }
 
     @Test
@@ -83,11 +86,9 @@
         editor.putInt(TEST_KEY, 2);
         editor.putInt(TEST_KEY, 2);
 
-        final PairMatcher longMatcher =
-                new PairMatcher(FIELD_SETTINGS_PREFERENCE_CHANGE_LONG_VALUE, Long.class);
-
         verify(mMetricsFeature, times(6)).action(any(Context.class), anyInt(),
-                argThat(mNamePairMatcher), argThat(longMatcher));
+                argThat(mNamePairMatcher),
+                argThat(pairMatches(FIELD_SETTINGS_PREFERENCE_CHANGE_LONG_VALUE, Long.class)));
     }
 
     @Test
@@ -100,15 +101,12 @@
         editor.putBoolean(TEST_KEY, false);
 
 
-        final PairMatcher trueMatcher =
-                new PairMatcher(FIELD_SETTINGS_PREFERENCE_CHANGE_LONG_VALUE, true);
-        final PairMatcher falseMatcher =
-                new PairMatcher(FIELD_SETTINGS_PREFERENCE_CHANGE_LONG_VALUE, false);
-
         verify(mMetricsFeature).action(any(Context.class), anyInt(),
-                argThat(mNamePairMatcher), argThat(trueMatcher));
+                argThat(mNamePairMatcher),
+                argThat(pairMatches(FIELD_SETTINGS_PREFERENCE_CHANGE_LONG_VALUE, true)));
         verify(mMetricsFeature, times(3)).action(any(Context.class), anyInt(),
-                argThat(mNamePairMatcher), argThat(falseMatcher));
+                argThat(mNamePairMatcher),
+                argThat(pairMatches(FIELD_SETTINGS_PREFERENCE_CHANGE_LONG_VALUE, false)));
     }
 
     @Test
@@ -120,11 +118,9 @@
         editor.putLong(TEST_KEY, 1);
         editor.putLong(TEST_KEY, 2);
 
-        final PairMatcher longMatcher =
-                new PairMatcher(FIELD_SETTINGS_PREFERENCE_CHANGE_LONG_VALUE, Long.class);
-
         verify(mMetricsFeature, times(4)).action(any(Context.class), anyInt(),
-                argThat(mNamePairMatcher), argThat(longMatcher));
+                argThat(mNamePairMatcher),
+                argThat(pairMatches(FIELD_SETTINGS_PREFERENCE_CHANGE_LONG_VALUE, Long.class)));
     }
 
     @Test
@@ -136,40 +132,27 @@
         editor.putFloat(TEST_KEY, 1);
         editor.putFloat(TEST_KEY, 2);
 
-        final PairMatcher floatMatcher =
-                new PairMatcher(FIELD_SETTINGS_PREFERENCE_CHANGE_FLOAT_VALUE, Float.class);
-
         verify(mMetricsFeature, times(4)).action(any(Context.class), anyInt(),
-                argThat(mNamePairMatcher), argThat(floatMatcher));
+                argThat(mNamePairMatcher),
+                argThat(pairMatches(FIELD_SETTINGS_PREFERENCE_CHANGE_FLOAT_VALUE, Float.class)));
     }
 
-    private static class PairMatcher extends ArgumentMatcher<Pair<Integer, Object>> {
+    @Test
+    public void logPackage_shouldUseLogPackageApi() {
+        mSharedPrefLogger.logPackageName("key", "com.android.settings");
+        verify(mMetricsFeature).action(any(Context.class),
+                eq(ACTION_SETTINGS_PREFERENCE_CHANGE),
+                eq("com.android.settings"),
+                any(Pair.class));
+    }
 
-        private final int mExpectedTag;
-        private final Class mExpectedClass;
-        private final Long mExpectedBoolean;
+    private ArgumentMatcher<Pair<Integer, Object>> pairMatches(int tag, Class clazz) {
+        return pair -> pair.first == tag && Platform.isInstanceOfType(pair.second, clazz);
+    }
 
-
-        public PairMatcher(int tag, Class clazz) {
-            mExpectedTag = tag;
-            mExpectedClass = clazz;
-            mExpectedBoolean = null;
-        }
-
-        public PairMatcher(int tag, boolean bool) {
-            mExpectedTag = tag;
-            mExpectedClass = Long.class;
-            mExpectedBoolean = bool ? 1L : 0L;
-        }
-
-        @Override
-        public boolean matches(Object arg) {
-            final Pair<Integer, Object> pair = (Pair) arg;
-            boolean booleanMatch = mExpectedBoolean == null
-                    || mExpectedBoolean == pair.second;
-            return pair.first == mExpectedTag
-                    && Platform.isInstanceOfType(pair.second, mExpectedClass)
-                    && booleanMatch;
-        }
+    private ArgumentMatcher<Pair<Integer, Object>> pairMatches(int tag, boolean bool) {
+        return pair -> pair.first == tag
+                && Platform.isInstanceOfType(pair.second, Long.class)
+                && pair.second.equals((bool ? 1L : 0L));
     }
 }
diff --git a/tests/robotests/src/com/android/settings/core/instrumentation/VisibilityLoggerMixinTest.java b/tests/robotests/src/com/android/settings/core/instrumentation/VisibilityLoggerMixinTest.java
index 8a555a8..06b1d06 100644
--- a/tests/robotests/src/com/android/settings/core/instrumentation/VisibilityLoggerMixinTest.java
+++ b/tests/robotests/src/com/android/settings/core/instrumentation/VisibilityLoggerMixinTest.java
@@ -15,6 +15,17 @@
  */
 package com.android.settings.core.instrumentation;
 
+import static com.android.settings.core.instrumentation.Instrumentable.METRICS_CATEGORY_UNKNOWN;
+
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import android.app.Activity;
 import android.content.Context;
 import android.content.Intent;
@@ -31,16 +42,6 @@
 import org.mockito.MockitoAnnotations;
 import org.robolectric.annotation.Config;
 
-import static com.android.settings.core.instrumentation.Instrumentable.METRICS_CATEGORY_UNKNOWN;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
@@ -62,7 +63,7 @@
         mMixin.onResume();
 
         verify(mMetricsFeature, times(1))
-                .visible(any(Context.class), eq(MetricsProto.MetricsEvent.VIEW_UNKNOWN),
+                .visible(nullable(Context.class), eq(MetricsProto.MetricsEvent.VIEW_UNKNOWN),
                         eq(TestInstrumentable.TEST_METRIC));
     }
 
@@ -77,7 +78,7 @@
         mMixin.onResume();
 
         verify(mMetricsFeature, times(1))
-                .visible(any(Context.class), eq(MetricsProto.MetricsEvent.SETTINGS_GESTURES),
+                .visible(nullable(Context.class), eq(MetricsProto.MetricsEvent.SETTINGS_GESTURES),
                         eq(TestInstrumentable.TEST_METRIC));
     }
 
@@ -86,7 +87,7 @@
         mMixin.onPause();
 
         verify(mMetricsFeature, times(1))
-                .hidden(any(Context.class), eq(TestInstrumentable.TEST_METRIC));
+                .hidden(nullable(Context.class), eq(TestInstrumentable.TEST_METRIC));
     }
 
     @Test
@@ -96,7 +97,7 @@
         mMixin.onPause();
 
         verify(mMetricsFeature, never())
-                .hidden(any(Context.class), anyInt());
+                .hidden(nullable(Context.class), anyInt());
     }
 
     @Test
@@ -107,7 +108,7 @@
         mMixin.onPause();
 
         verify(mMetricsFeature, never())
-                .hidden(any(Context.class), anyInt());
+                .hidden(nullable(Context.class), anyInt());
     }
 
     private final class TestInstrumentable implements Instrumentable {
diff --git a/tests/robotests/src/com/android/settings/dashboard/DashboardFragmentTest.java b/tests/robotests/src/com/android/settings/dashboard/DashboardFragmentTest.java
index e35fa33..c981d2d 100644
--- a/tests/robotests/src/com/android/settings/dashboard/DashboardFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/dashboard/DashboardFragmentTest.java
@@ -15,6 +15,15 @@
  */
 package com.android.settings.dashboard;
 
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import android.content.Context;
 import android.os.Bundle;
 import android.support.v7.preference.Preference;
@@ -43,15 +52,6 @@
 import java.util.ArrayList;
 import java.util.List;
 
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class DashboardFragmentTest {
@@ -75,9 +75,10 @@
         mDashboardCategory.tiles.add(new Tile());
         mTestFragment = new TestFragment(ShadowApplication.getInstance().getApplicationContext());
         when(mFakeFeatureFactory.dashboardFeatureProvider.getProgressiveDisclosureMixin(
-                any(Context.class), eq(mTestFragment), any(Bundle.class)))
+                nullable(Context.class), eq(mTestFragment), nullable(Bundle.class)))
                 .thenReturn(mDisclosureMixin);
-        when(mFakeFeatureFactory.dashboardFeatureProvider.getTilesForCategory(anyString()))
+        when(mFakeFeatureFactory.dashboardFeatureProvider
+                .getTilesForCategory(nullable(String.class)))
                 .thenReturn(mDashboardCategory);
         mTestFragment.onAttach(ShadowApplication.getInstance().getApplicationContext());
         when(mContext.getPackageName()).thenReturn("TestPackage");
@@ -96,21 +97,23 @@
 
     @Test
     public void displayTilesAsPreference_shouldAddTilesWithIntent() {
-        when(mFakeFeatureFactory.dashboardFeatureProvider.getTilesForCategory(anyString()))
+        when(mFakeFeatureFactory.dashboardFeatureProvider
+                .getTilesForCategory(nullable(String.class)))
                 .thenReturn(mDashboardCategory);
-        when(mFakeFeatureFactory.dashboardFeatureProvider.getDashboardKeyForTile(any(Tile.class)))
+        when(mFakeFeatureFactory.dashboardFeatureProvider
+                .getDashboardKeyForTile(nullable(Tile.class)))
                 .thenReturn("test_key");
         mTestFragment.onCreatePreferences(new Bundle(), "rootKey");
 
-        verify(mDisclosureMixin).addPreference(any(PreferenceScreen.class),
-                any(Preference.class));
+        verify(mDisclosureMixin).addPreference(nullable(PreferenceScreen.class),
+                nullable(Preference.class));
     }
 
     @Test
     public void displayTilesAsPreference_shouldNotAddTilesWithoutIntent() {
         mTestFragment.onCreatePreferences(new Bundle(), "rootKey");
 
-        verify(mTestFragment.mScreen, never()).addPreference(any(Preference.class));
+        verify(mTestFragment.mScreen, never()).addPreference(nullable(Preference.class));
     }
 
     @Test
@@ -118,7 +121,7 @@
         mDashboardCategory.tiles = null;
         mTestFragment.onCreatePreferences(new Bundle(), "rootKey");
 
-        verify(mTestFragment.mScreen, never()).addPreference(any(Preference.class));
+        verify(mTestFragment.mScreen, never()).addPreference(nullable(Preference.class));
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/dashboard/ProgressiveDisclosureTest.java b/tests/robotests/src/com/android/settings/dashboard/ProgressiveDisclosureTest.java
index a3b9bf8..55c275b 100644
--- a/tests/robotests/src/com/android/settings/dashboard/ProgressiveDisclosureTest.java
+++ b/tests/robotests/src/com/android/settings/dashboard/ProgressiveDisclosureTest.java
@@ -40,6 +40,8 @@
 import java.util.List;
 
 import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.anyString;
@@ -118,7 +120,7 @@
 
     @Test
     public void findPreference_prefInCollapsedList_shouldFindIt() {
-        when(mScreen.findPreference(anyString())).thenReturn(null);
+        when(mScreen.findPreference(nullable(String.class))).thenReturn(null);
         mMixin.addToCollapsedList(mPreference);
 
         Preference pref = mMixin.findPreference(mScreen, mPreference.getKey());
@@ -139,7 +141,7 @@
 
     @Test
     public void findPreference_prefNotInCollapsedListOrScreen_shouldNotFindIt() {
-        when(mScreen.findPreference(anyString())).thenReturn(null);
+        when(mScreen.findPreference(nullable(String.class))).thenReturn(null);
         Preference pref = mMixin.findPreference(mScreen, mPreference.getKey());
 
         assertThat(pref).isNull();
@@ -147,7 +149,7 @@
 
     @Test
     public void findPreference_prefRemovedFromCollapsedList_shouldNotFindIt() {
-        when(mScreen.findPreference(anyString())).thenReturn(null);
+        when(mScreen.findPreference(nullable(String.class))).thenReturn(null);
         mMixin.addToCollapsedList(mPreference);
         mMixin.removePreference(mPreferenceFragment.getPreferenceScreen(), mPreference.getKey());
 
@@ -158,7 +160,7 @@
 
     @Test
     public void findPreference_nestedPrefInCollapsedList_shouldFindIt() {
-        when(mScreen.findPreference(anyString())).thenReturn(null);
+        when(mScreen.findPreference(nullable(String.class))).thenReturn(null);
         final PreferenceScreen prefGroup = spy(new PreferenceScreen(mAppContext, null));
         when(prefGroup.getPreferenceManager()).thenReturn(mock(PreferenceManager.class));
         final Preference preference = mock(Preference.class);
@@ -183,7 +185,7 @@
 
     @Test
     public void removeLastPreference_shouldRemoveExpandButtonToo() {
-        when(mScreen.findPreference(anyString())).thenReturn(null);
+        when(mScreen.findPreference(nullable(String.class))).thenReturn(null);
         mMixin.addToCollapsedList(mPreference);
         // Collapsed
         assertThat(mMixin.isCollapsed()).isTrue();
@@ -204,7 +206,7 @@
 
         mMixin.collapse(screen);
         assertThat(mMixin.isCollapsed()).isFalse();
-        verify(mExpandButton, never()).setSummary(anyString());
+        verify(mExpandButton, never()).setSummary(nullable(String.class));
         verify(screen, never()).addPreference(any(Preference.class));
         verify(screen, never()).removePreference(any(Preference.class));
     }
@@ -219,7 +221,7 @@
         mMixin.collapse(screen);
 
         assertThat(mMixin.isCollapsed()).isTrue();
-        verify(mExpandButton, atLeastOnce()).setSummary(anyString());
+        verify(mExpandButton, atLeastOnce()).setSummary(nullable(String.class));
         verify(screen).addPreference(any(ExpandPreference.class));
         verify(screen, times(3)).removePreference(any(Preference.class));
     }
@@ -264,7 +266,7 @@
         lastPref.setOrder(100);
         // Add something to collapsed list so we are in collapsed state.
         mMixin.addToCollapsedList(new Preference(mAppContext));
-        verify(mExpandButton).setSummary(anyString());
+        verify(mExpandButton).setSummary(nullable(String.class));
         assertThat(mMixin.getCollapsedPrefs().size()).isEqualTo(1);
 
         // 3 prefs on screen, 2 are real and the last one is more button.
@@ -286,7 +288,7 @@
         lastPref.setOrder(100);
         // Add something to collapsed list so we are in collapsed state.
         mMixin.addToCollapsedList(new Preference(mAppContext));
-        verify(mExpandButton).setSummary(anyString());
+        verify(mExpandButton).setSummary(nullable(String.class));
         assertThat(mMixin.getCollapsedPrefs().size()).isEqualTo(1);
 
         // 3 prefs on screen, 2 are real and the last one is more button.
@@ -299,7 +301,7 @@
 
         verify(mScreen, never()).removePreference(any(Preference.class));
         verify(mScreen, never()).addPreference(any(Preference.class));
-        verify(mExpandButton, times(2)).setSummary(anyString());
+        verify(mExpandButton, times(2)).setSummary(nullable(String.class));
         assertThat(mMixin.getCollapsedPrefs().get(0)).isSameAs(toBeAdded);
     }
 
diff --git a/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionDismissControllerTest.java b/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionDismissControllerTest.java
index 4d9c1ec..92bc915 100644
--- a/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionDismissControllerTest.java
+++ b/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionDismissControllerTest.java
@@ -16,6 +16,15 @@
 
 package com.android.settings.dashboard.suggestions;
 
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import android.content.Context;
 import android.support.v7.widget.RecyclerView;
 import android.support.v7.widget.helper.ItemTouchHelper;
@@ -35,14 +44,6 @@
 import org.mockito.MockitoAnnotations;
 import org.robolectric.annotation.Config;
 
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class SuggestionDismissControllerTest {
@@ -110,7 +111,7 @@
         mController.onSwiped(vh, ItemTouchHelper.START);
 
         verify(mFactory.suggestionsFeatureProvider).dismissSuggestion(
-                eq(mContext), eq(mSuggestionParser), any(Tile.class));
-        verify(mCallback).onSuggestionDismissed(any(Tile.class));
+                eq(mContext), eq(mSuggestionParser), nullable(Tile.class));
+        verify(mCallback).onSuggestionDismissed(nullable(Tile.class));
     }
 }
diff --git a/tests/robotests/src/com/android/settings/datausage/AppDataUsageTest.java b/tests/robotests/src/com/android/settings/datausage/AppDataUsageTest.java
index 8cbe947..a9b4d78 100644
--- a/tests/robotests/src/com/android/settings/datausage/AppDataUsageTest.java
+++ b/tests/robotests/src/com/android/settings/datausage/AppDataUsageTest.java
@@ -18,13 +18,16 @@
 
 
 import android.content.Context;
+import android.content.pm.PackageManager;
 import android.os.Bundle;
 import android.support.v7.preference.PreferenceManager;
 import android.support.v7.preference.PreferenceScreen;
+import android.util.ArraySet;
 import android.view.View;
 
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
+import com.android.settings.applications.PackageManagerWrapper;
 import com.android.settings.testutils.FakeFeatureFactory;
 import com.android.settings.testutils.shadow.ShadowEntityHeaderController;
 import com.android.settings.widget.EntityHeaderController;
@@ -43,6 +46,8 @@
 import org.robolectric.util.ReflectionHelpers;
 
 import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
@@ -59,6 +64,8 @@
     private Context mContext;
     @Mock(answer = Answers.RETURNS_DEEP_STUBS)
     private EntityHeaderController mHeaderController;
+    @Mock
+    private PackageManagerWrapper mPackageManagerWrapper;
 
     private AppDataUsage mFragment;
 
@@ -77,6 +84,7 @@
     public void bindAppHeader_allWorkApps_shouldNotShowAppInfoLink() {
         ShadowEntityHeaderController.setUseMock(mHeaderController);
         when(mHeaderController.setRecyclerView(any(), any())).thenReturn(mHeaderController);
+        when(mHeaderController.setUid(anyInt())).thenReturn(mHeaderController);
 
         mFragment = spy(new AppDataUsage());
 
@@ -90,4 +98,38 @@
 
         verify(mHeaderController).setButtonActions(ActionType.ACTION_NONE, ActionType.ACTION_NONE);
     }
+
+    @Test
+    public void bindAppHeader_workApp_shouldSetWorkAppUid() throws
+            PackageManager.NameNotFoundException {
+        final int fakeUserId = 100;
+
+        mFragment = spy(new AppDataUsage());
+        final ArraySet<String> packages = new ArraySet<>();
+        packages.add("pkg");
+        final AppItem appItem = new AppItem(123456789);
+
+        ReflectionHelpers.setField(mFragment, "mPackageManagerWrapper", mPackageManagerWrapper);
+        ReflectionHelpers.setField(mFragment, "mAppItem", appItem);
+        ReflectionHelpers.setField(mFragment, "mPackages", packages);
+
+        when(mPackageManagerWrapper.getPackageUidAsUser(anyString(), anyInt()))
+                .thenReturn(fakeUserId);
+
+        ShadowEntityHeaderController.setUseMock(mHeaderController);
+        when(mHeaderController.setRecyclerView(any(), any())).thenReturn(mHeaderController);
+        when(mHeaderController.setUid(fakeUserId)).thenReturn(mHeaderController);
+
+        doReturn(mock(PreferenceManager.class, RETURNS_DEEP_STUBS))
+                .when(mFragment)
+                .getPreferenceManager();
+        doReturn(mock(PreferenceScreen.class)).when(mFragment).getPreferenceScreen();
+
+        mFragment.onViewCreated(new View(RuntimeEnvironment.application), new Bundle());
+
+        verify(mHeaderController)
+                .setButtonActions(ActionType.ACTION_APP_INFO, ActionType.ACTION_NONE);
+        verify(mHeaderController)
+                .setUid(fakeUserId);
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/datausage/UnrestrictedDataAccessTest.java b/tests/robotests/src/com/android/settings/datausage/UnrestrictedDataAccessTest.java
index d674c77..899894b 100644
--- a/tests/robotests/src/com/android/settings/datausage/UnrestrictedDataAccessTest.java
+++ b/tests/robotests/src/com/android/settings/datausage/UnrestrictedDataAccessTest.java
@@ -15,14 +15,22 @@
  */
 package com.android.settings.datausage;
 
-import com.android.internal.logging.nano.MetricsProto;
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.verify;
+
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.os.Process;
+
+import com.android.internal.logging.nano.MetricsProto;
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
 import com.android.settings.testutils.FakeFeatureFactory;
 import com.android.settingslib.applications.ApplicationsState;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -31,11 +39,6 @@
 import org.mockito.MockitoAnnotations;
 import org.robolectric.annotation.Config;
 
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.verify;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class UnrestrictedDataAccessTest {
@@ -75,11 +78,11 @@
     @Test
     public void logSpecialPermissionChange() {
         mFragment.logSpecialPermissionChange(true, "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_UNL_DATA_ALLOW), eq("app"));
 
         mFragment.logSpecialPermissionChange(false, "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_UNL_DATA_DENY), eq("app"));
     }
 
diff --git a/tests/robotests/src/com/android/settings/datetime/ZonePickerTest.java b/tests/robotests/src/com/android/settings/datetime/ZonePickerTest.java
index 4acac70..a964cb3 100644
--- a/tests/robotests/src/com/android/settings/datetime/ZonePickerTest.java
+++ b/tests/robotests/src/com/android/settings/datetime/ZonePickerTest.java
@@ -16,6 +16,11 @@
 
 package com.android.settings.datetime;
 
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+
 import android.app.Activity;
 import android.os.Bundle;
 import android.view.LayoutInflater;
@@ -33,11 +38,6 @@
 import org.robolectric.annotation.Config;
 import org.robolectric.util.ReflectionHelpers;
 
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class ZonePickerTest {
@@ -64,8 +64,8 @@
 
         // Should render
         verify(mZonePicker).onCreateView(
-                any(LayoutInflater.class),
-                any(ViewGroup.class),
-                any(Bundle.class));
+                nullable(LayoutInflater.class),
+                nullable(ViewGroup.class),
+                nullable(Bundle.class));
     }
 }
diff --git a/tests/robotests/src/com/android/settings/deletionhelper/AutomaticStorageManagerSwitchBarControllerTest.java b/tests/robotests/src/com/android/settings/deletionhelper/AutomaticStorageManagerSwitchBarControllerTest.java
index be04eec..1bc859f 100644
--- a/tests/robotests/src/com/android/settings/deletionhelper/AutomaticStorageManagerSwitchBarControllerTest.java
+++ b/tests/robotests/src/com/android/settings/deletionhelper/AutomaticStorageManagerSwitchBarControllerTest.java
@@ -71,6 +71,7 @@
         mSwitchBar = new SwitchBar(mContext);
 
         Context fakeContextForFakeProvider = mock(Context.class, RETURNS_DEEP_STUBS);
+        FakeFeatureFactory.setupForTest(fakeContextForFakeProvider);
         FeatureFactory featureFactory = FakeFeatureFactory.getFactory(fakeContextForFakeProvider);
         mMetricsFeatureProvider = featureFactory.getMetricsFeatureProvider();
         mPreference = new Preference(mContext);
diff --git a/tests/robotests/src/com/android/settings/deviceinfo/StorageSettingsTest.java b/tests/robotests/src/com/android/settings/deviceinfo/StorageSettingsTest.java
index 17abab1..89328e4 100644
--- a/tests/robotests/src/com/android/settings/deviceinfo/StorageSettingsTest.java
+++ b/tests/robotests/src/com/android/settings/deviceinfo/StorageSettingsTest.java
@@ -17,6 +17,12 @@
 package com.android.settings.deviceinfo;
 
 
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import android.app.Activity;
 import android.app.usage.StorageStatsManager;
 import android.icu.text.NumberFormat;
@@ -41,12 +47,6 @@
 import java.util.ArrayList;
 import java.util.List;
 
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class StorageSettingsTest {
@@ -78,10 +78,10 @@
         when(volumeInfo.isMountedReadable()).thenReturn(true);
         when(volumeInfo.getType()).thenReturn(VolumeInfo.TYPE_PRIVATE);
         when(mStorageManagerVolumeProvider.getTotalBytes(
-                        any(StorageStatsManager.class), any(VolumeInfo.class)))
+                        nullable(StorageStatsManager.class), nullable(VolumeInfo.class)))
                 .thenReturn(500L);
         when(mStorageManagerVolumeProvider.getFreeBytes(
-                        any(StorageStatsManager.class), any(VolumeInfo.class)))
+                        nullable(StorageStatsManager.class), nullable(VolumeInfo.class)))
                 .thenReturn(0L);
 
         ReflectionHelpers.setField(
diff --git a/tests/robotests/src/com/android/settings/deviceinfo/UsbBackendTest.java b/tests/robotests/src/com/android/settings/deviceinfo/UsbBackendTest.java
index 8529c5d..af05c7f 100644
--- a/tests/robotests/src/com/android/settings/deviceinfo/UsbBackendTest.java
+++ b/tests/robotests/src/com/android/settings/deviceinfo/UsbBackendTest.java
@@ -16,8 +16,13 @@
 
 package com.android.settings.deviceinfo;
 
+import static org.mockito.Answers.RETURNS_DEEP_STUBS;
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import android.content.Context;
-import android.content.IntentFilter;
 import android.content.pm.PackageManager;
 import android.hardware.usb.UsbManager;
 
@@ -27,17 +32,10 @@
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
-import org.mockito.ArgumentMatcher;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 import org.robolectric.annotation.Config;
 
-import static org.mockito.Answers.RETURNS_DEEP_STUBS;
-import static org.mockito.Matchers.argThat;
-import static org.mockito.Mockito.eq;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class UsbBackendTest {
@@ -70,13 +68,7 @@
         usbBackend.getCurrentMode();
 
         verify(mContext).registerReceiver(eq(null),
-            argThat(new ArgumentMatcher<IntentFilter>() {
-                @Override
-                public boolean matches(Object i) {
-                    final IntentFilter intentFilter = (IntentFilter) i;
-                    return intentFilter != null &&
-                        UsbManager.ACTION_USB_STATE.equals(intentFilter.getAction(0));
-                }
-            }));
+            argThat(intentFilter -> intentFilter != null &&
+                UsbManager.ACTION_USB_STATE.equals(intentFilter.getAction(0))));
     }
 }
diff --git a/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java
index e8057a6..bdbe908 100644
--- a/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java
@@ -16,11 +16,12 @@
 package com.android.settings.deviceinfo.storage;
 
 
-import static com.google.common.truth.Truth.assertThat;
 import static com.android.settings.utils.FileSizeFormatter.MEGABYTE_IN_BYTES;
 
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
@@ -28,7 +29,6 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-
 import android.app.Fragment;
 import android.content.Context;
 import android.content.Intent;
@@ -119,7 +119,7 @@
 
         final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
         verify(mFragment.getActivity()).startActivityAsUser(argumentCaptor.capture(),
-                any(UserHandle.class));
+                nullable(UserHandle.class));
 
         Intent intent = argumentCaptor.getValue();
         assertThat(intent.getType()).isEqualTo("image/*");
@@ -134,7 +134,7 @@
 
         final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
         verify(mFragment.getActivity()).startActivityAsUser(argumentCaptor.capture(),
-                any(UserHandle.class));
+                nullable(UserHandle.class));
         Intent intent = argumentCaptor.getValue();
 
         assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
@@ -161,7 +161,7 @@
 
         final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
         verify(mFragment.getActivity()).startActivityAsUser(argumentCaptor.capture(),
-                any(UserHandle.class));
+                nullable(UserHandle.class));
 
         Intent intent = argumentCaptor.getValue();
         assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
@@ -182,20 +182,20 @@
 
     @Test
     public void testClickFiles() {
-        when(mSvp.findEmulatedForPrivate(any(VolumeInfo.class))).thenReturn(mVolume);
+        when(mSvp.findEmulatedForPrivate(nullable(VolumeInfo.class))).thenReturn(mVolume);
         mPreference.setKey("pref_files");
         mController.handlePreferenceTreeClick(mPreference);
 
         final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
         verify(mFragment.getActivity()).startActivityAsUser(argumentCaptor.capture(),
-                any(UserHandle.class));
+                nullable(UserHandle.class));
 
         Intent intent = argumentCaptor.getValue();
         Intent browseIntent = mVolume.buildBrowseIntent();
         assertThat(intent.getAction()).isEqualTo(browseIntent.getAction());
         assertThat(intent.getData()).isEqualTo(browseIntent.getData());
         verify(mMetricsFeatureProvider, times(1)).action(
-                any(Context.class), eq(MetricsEvent.STORAGE_FILES));
+                nullable(Context.class), eq(MetricsEvent.STORAGE_FILES));
     }
 
     @Test
@@ -205,7 +205,7 @@
 
         final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
         verify(mFragment.getActivity()).startActivityAsUser(argumentCaptor.capture(),
-                any(UserHandle.class));
+                nullable(UserHandle.class));
 
         Intent intent = argumentCaptor.getValue();
         assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
@@ -223,7 +223,7 @@
 
         final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
         verify(mFragment.getActivity()).startActivityAsUser(argumentCaptor.capture(),
-                any(UserHandle.class));
+                nullable(UserHandle.class));
 
         Intent intent = argumentCaptor.getValue();
         assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
@@ -240,7 +240,7 @@
         assertThat(mController.handlePreferenceTreeClick(mPreference)).isTrue();
 
         verify(mFragment.getFragmentManager().beginTransaction()).add(
-                any(PrivateVolumeSettings.SystemInfoFragment.class), anyString());
+                nullable(PrivateVolumeSettings.SystemInfoFragment.class), nullable(String.class));
     }
 
     @Test
@@ -329,13 +329,13 @@
 
         mController.setUserId(new UserHandle(10));
 
-        verify(audio, times(2)).setIcon(any(Drawable.class));
-        verify(video, times(2)).setIcon(any(Drawable.class));
-        verify(image, times(2)).setIcon(any(Drawable.class));
-        verify(games, times(2)).setIcon(any(Drawable.class));
-        verify(apps, times(2)).setIcon(any(Drawable.class));
-        verify(system, times(2)).setIcon(any(Drawable.class));
-        verify(files, times(2)).setIcon(any(Drawable.class));
+        verify(audio, times(2)).setIcon(nullable(Drawable.class));
+        verify(video, times(2)).setIcon(nullable(Drawable.class));
+        verify(image, times(2)).setIcon(nullable(Drawable.class));
+        verify(games, times(2)).setIcon(nullable(Drawable.class));
+        verify(apps, times(2)).setIcon(nullable(Drawable.class));
+        verify(system, times(2)).setIcon(nullable(Drawable.class));
+        verify(files, times(2)).setIcon(nullable(Drawable.class));
     }
 
     @Test
@@ -359,7 +359,7 @@
         when(screen.findPreference(eq(StorageItemPreferenceController.FILES_KEY)))
                 .thenReturn(files);
 
-        when(mSvp.findEmulatedForPrivate(any(VolumeInfo.class))).thenReturn(mVolume);
+        when(mSvp.findEmulatedForPrivate(nullable(VolumeInfo.class))).thenReturn(mVolume);
         when(mVolume.isMountedReadable()).thenReturn(true);
 
         mController.displayPreference(screen);
@@ -388,7 +388,7 @@
         when(screen.findPreference(eq(StorageItemPreferenceController.FILES_KEY)))
                 .thenReturn(files);
 
-        when(mSvp.findEmulatedForPrivate(any(VolumeInfo.class))).thenReturn(mVolume);
+        when(mSvp.findEmulatedForPrivate(nullable(VolumeInfo.class))).thenReturn(mVolume);
         when(mVolume.isMountedReadable()).thenReturn(false);
 
         mController.displayPreference(screen);
@@ -417,7 +417,7 @@
         when(screen.findPreference(eq(StorageItemPreferenceController.FILES_KEY)))
                 .thenReturn(files);
 
-        when(mSvp.findEmulatedForPrivate(any(VolumeInfo.class))).thenReturn(null);
+        when(mSvp.findEmulatedForPrivate(nullable(VolumeInfo.class))).thenReturn(null);
 
         mController.displayPreference(screen);
 
@@ -445,11 +445,11 @@
         when(screen.findPreference(eq(StorageItemPreferenceController.FILES_KEY)))
                 .thenReturn(files);
 
-        when(mSvp.findEmulatedForPrivate(any(VolumeInfo.class))).thenReturn(mVolume);
+        when(mSvp.findEmulatedForPrivate(nullable(VolumeInfo.class))).thenReturn(mVolume);
         when(mVolume.isMountedReadable()).thenReturn(true);
 
         mController.displayPreference(screen);
-        when(mSvp.findEmulatedForPrivate(any(VolumeInfo.class))).thenReturn(null);
+        when(mSvp.findEmulatedForPrivate(nullable(VolumeInfo.class))).thenReturn(null);
         mController.setVolume(mVolume);
 
         verify(screen).removePreference(files);
@@ -480,7 +480,7 @@
         // This will hide it initially.
         mController.displayPreference(screen);
 
-        when(mSvp.findEmulatedForPrivate(any(VolumeInfo.class))).thenReturn(mVolume);
+        when(mSvp.findEmulatedForPrivate(nullable(VolumeInfo.class))).thenReturn(mVolume);
         when(mVolume.isMountedReadable()).thenReturn(true);
 
         // And we bring it back.
diff --git a/tests/robotests/src/com/android/settings/display/DozeAlwaysOnPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/display/AmbientDisplayAlwaysOnPreferenceControllerTest.java
similarity index 93%
rename from tests/robotests/src/com/android/settings/display/DozeAlwaysOnPreferenceControllerTest.java
rename to tests/robotests/src/com/android/settings/display/AmbientDisplayAlwaysOnPreferenceControllerTest.java
index fc299c0..c89e29f 100644
--- a/tests/robotests/src/com/android/settings/display/DozeAlwaysOnPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/display/AmbientDisplayAlwaysOnPreferenceControllerTest.java
@@ -41,18 +41,18 @@
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION,
         shadows = {ShadowSecureSettings.class})
-public class DozeAlwaysOnPreferenceControllerTest {
+public class AmbientDisplayAlwaysOnPreferenceControllerTest {
 
     @Mock Context mContext;
     @Mock AmbientDisplayConfiguration mConfig;
     @Mock SwitchPreference mSwitchPreference;
 
-    DozeAlwaysOnPreferenceController mController;
+    AmbientDisplayAlwaysOnPreferenceController mController;
 
     @Before
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
-        mController = new DozeAlwaysOnPreferenceController(mContext, mConfig);
+        mController = new AmbientDisplayAlwaysOnPreferenceController(mContext, mConfig);
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/display/DozePreferenceControllerTest.java b/tests/robotests/src/com/android/settings/display/AmbientDisplayNotificationsPreferenceControllerTest.java
similarity index 90%
rename from tests/robotests/src/com/android/settings/display/DozePreferenceControllerTest.java
rename to tests/robotests/src/com/android/settings/display/AmbientDisplayNotificationsPreferenceControllerTest.java
index a956945..1997198 100644
--- a/tests/robotests/src/com/android/settings/display/DozePreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/display/AmbientDisplayNotificationsPreferenceControllerTest.java
@@ -47,19 +47,20 @@
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION,
         shadows = {ShadowSecureSettings.class})
-public class DozePreferenceControllerTest {
+public class AmbientDisplayNotificationsPreferenceControllerTest {
 
     @Mock Context mContext;
     @Mock AmbientDisplayConfiguration mConfig;
     @Mock SwitchPreference mSwitchPreference;
     @Mock MetricsFeatureProvider mMetricsFeatureProvider;
 
-    DozePreferenceController mController;
+    AmbientDisplayNotificationsPreferenceController mController;
 
     @Before
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
-        mController = new DozePreferenceController(mContext, mConfig, mMetricsFeatureProvider);
+        mController = new AmbientDisplayNotificationsPreferenceController(mContext, mConfig,
+                mMetricsFeatureProvider);
     }
 
     @Test
@@ -116,7 +117,8 @@
 
     @Test
     public void handlePreferenceTreeClick_reportsEventForItsPreference() throws Exception {
-        when(mSwitchPreference.getKey()).thenReturn(DozePreferenceController.KEY_DOZE);
+        when(mSwitchPreference.getKey()).thenReturn(
+                AmbientDisplayNotificationsPreferenceController.KEY_AMBIENT_DISPLAY_NOTIFICATIONS);
 
         mController.handlePreferenceTreeClick(mSwitchPreference);
 
diff --git a/tests/robotests/src/com/android/settings/display/AmbientDisplayPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/display/AmbientDisplayPreferenceControllerTest.java
new file mode 100644
index 0000000..3ae4831
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/display/AmbientDisplayPreferenceControllerTest.java
@@ -0,0 +1,117 @@
+/*
+ * 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.display;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.support.v7.preference.Preference;
+
+import com.android.internal.hardware.AmbientDisplayConfiguration;
+import com.android.settings.R;
+import com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.shadow.ShadowSecureSettings;
+
+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,
+        shadows = {ShadowSecureSettings.class})
+public class AmbientDisplayPreferenceControllerTest {
+
+    @Mock Context mContext;
+    @Mock AmbientDisplayConfiguration mConfig;
+    @Mock Preference mPreference;
+
+    AmbientDisplayPreferenceController mController;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+        mController = new AmbientDisplayPreferenceController(mContext, mConfig, "key");
+    }
+
+    @Test
+    public void isAvailable_available() throws Exception {
+        when(mConfig.available()).thenReturn(true);
+        assertThat(mController.isAvailable()).isTrue();
+    }
+
+    @Test
+    public void isAvailable_unavailable() throws Exception {
+        when(mConfig.available()).thenReturn(false);
+        assertThat(mController.isAvailable()).isFalse();
+    }
+
+    @Test
+    public void updateState_alwaysOn() throws Exception {
+        when(mConfig.alwaysOnEnabled(anyInt())).thenReturn(true);
+
+        mController.updateState(mPreference);
+
+        verify(mPreference).setSummary(R.string.ambient_display_screen_summary_always_on);
+    }
+
+    @Test
+    public void updateState_notifications() throws Exception {
+        when(mConfig.alwaysOnEnabled(anyInt())).thenReturn(false);
+        when(mConfig.pulseOnNotificationEnabled(anyInt())).thenReturn(true);
+
+        mController.updateState(mPreference);
+
+        verify(mPreference).setSummary(R.string.ambient_display_screen_summary_notifications);
+    }
+
+    @Test
+    public void updateState_gestures() throws Exception {
+        when(mConfig.alwaysOnEnabled(anyInt())).thenReturn(false);
+        when(mConfig.pulseOnNotificationEnabled(anyInt())).thenReturn(false);
+        when(mConfig.enabled(anyInt())).thenReturn(true);
+
+        mController.updateState(mPreference);
+
+        verify(mPreference).setSummary(R.string.switch_on_text);
+    }
+
+    @Test
+    public void updateState_off() throws Exception {
+        when(mConfig.alwaysOnEnabled(anyInt())).thenReturn(false);
+        when(mConfig.pulseOnNotificationEnabled(anyInt())).thenReturn(false);
+        when(mConfig.pulseOnDoubleTapEnabled(anyInt())).thenReturn(false);
+        when(mConfig.pulseOnPickupEnabled(anyInt())).thenReturn(false);
+
+        mController.updateState(mPreference);
+
+        verify(mPreference).setSummary(R.string.switch_off_text);
+    }
+
+    @Test
+    public void getPreferenceKey() throws Exception {
+        assertThat(mController.getPreferenceKey()).isEqualTo("key");
+    }
+
+}
\ No newline at end of file
diff --git a/tests/robotests/src/com/android/settings/enterprise/EnterpriseSetDefaultAppsPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/enterprise/EnterpriseSetDefaultAppsPreferenceControllerTest.java
index 34d9b24..862116f 100644
--- a/tests/robotests/src/com/android/settings/enterprise/EnterpriseSetDefaultAppsPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/enterprise/EnterpriseSetDefaultAppsPreferenceControllerTest.java
@@ -16,6 +16,14 @@
 
 package com.android.settings.enterprise;
 
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.when;
+
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.ApplicationInfo;
@@ -43,13 +51,6 @@
 import java.util.ArrayList;
 import java.util.List;
 
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.argThat;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.anyObject;
-import static org.mockito.Mockito.when;
-
 /**
  * Tests for {@link EnterpriseSetDefaultAppsPreferenceController}.
  */
@@ -81,7 +82,7 @@
             final List<UserAppInfo> apps = new ArrayList<>(number);
             apps.add(new UserAppInfo(new UserInfo(i, "user." + i, UserInfo.FLAG_ADMIN), appInfo));
             when(mFeatureFactory.applicationFeatureProvider.findPersistentPreferredActivities(eq(i),
-                    argThat(new MatchesIntents(intents)))).thenReturn(apps);
+                    argThat(matchesIntents(intents)))).thenReturn(apps);
         }
     }
 
@@ -116,7 +117,7 @@
     @Test
     public void testIsAvailable() {
         when(mFeatureFactory.applicationFeatureProvider.findPersistentPreferredActivities(anyInt(),
-                anyObject())).thenReturn(new ArrayList<UserAppInfo>());
+                any(Intent[].class))).thenReturn(new ArrayList<>());
         assertThat(mController.isAvailable()).isFalse();
 
         setEnterpriseSetDefaultApps(EnterpriseDefaultApps.BROWSER.getIntents(), 1);
@@ -136,28 +137,20 @@
                 .isEqualTo("number_enterprise_set_default_apps");
     }
 
-    private static class MatchesIntents extends ArgumentMatcher<Intent[]> {
-        private final Intent[] mExpectedIntents;
-
-        MatchesIntents(Intent[] intents) {
-            mExpectedIntents = intents;
-        }
-
-        @Override
-        public boolean matches(Object object) {
-            final Intent[] actualIntents = (Intent[]) object;
+    private ArgumentMatcher<Intent[]> matchesIntents(Intent[] intents) {
+        return (Intent[] actualIntents) -> {
             if (actualIntents == null) {
                 return false;
             }
-            if (actualIntents.length != mExpectedIntents.length) {
+            if (actualIntents.length != intents.length) {
                 return false;
             }
-            for (int i = 0; i < mExpectedIntents.length; i++) {
-                if (!mExpectedIntents[i].filterEquals(actualIntents[i])) {
+            for (int i = 0; i < intents.length; i++) {
+                if (!intents[i].filterEquals(actualIntents[i])) {
                     return false;
                 }
             }
             return true;
-        }
+        };
     }
 }
diff --git a/tests/robotests/src/com/android/settings/fingerprint/FingerprintEnrollFindSensorTest.java b/tests/robotests/src/com/android/settings/fingerprint/FingerprintEnrollFindSensorTest.java
index 74cfc7b..7df3083 100644
--- a/tests/robotests/src/com/android/settings/fingerprint/FingerprintEnrollFindSensorTest.java
+++ b/tests/robotests/src/com/android/settings/fingerprint/FingerprintEnrollFindSensorTest.java
@@ -93,18 +93,11 @@
 
     @Test
     public void clickNextAndFingerprint_shouldNotCrash() {
-        ArgumentCaptor<EnrollmentCallback> callbackCaptor =
-                ArgumentCaptor.forClass(EnrollmentCallback.class);
-        verify(mFingerprintManager).enroll(
-                any(byte[].class),
-                any(CancellationSignal.class),
-                anyInt(),
-                anyInt(),
-                callbackCaptor.capture());
+        EnrollmentCallback enrollmentCallback = verifyAndCaptureEnrollmentCallback();
 
         Button nextButton = mActivity.findViewById(R.id.next_button);
         nextButton.performClick();
-        callbackCaptor.getValue().onEnrollmentProgress(123);
+        enrollmentCallback.onEnrollmentProgress(123);
         nextButton.performClick();
 
         ShadowActivity shadowActivity = Shadows.shadowOf(mActivity);
@@ -118,4 +111,37 @@
         assertThat(shadowActivity.getNextStartedActivityForResult()).named("Next activity 2")
                 .isNull();
     }
+
+    // Use a non-default resource qualifier to load the test layout in
+    // robotests/res/layout-mcc999/fingerprint_enroll_find_sensor. This layout is a copy of the
+    // regular find sensor layout, with the animation removed.
+    @Config(qualifiers = "mcc999")
+    @Test
+    public void layoutWithoutAnimation_shouldNotCrash() {
+        EnrollmentCallback enrollmentCallback = verifyAndCaptureEnrollmentCallback();
+        enrollmentCallback.onEnrollmentProgress(123);
+
+        Button nextButton = mActivity.findViewById(R.id.next_button);
+        nextButton.performClick();
+
+        ShadowActivity shadowActivity = Shadows.shadowOf(mActivity);
+        IntentForResult startedActivity =
+                shadowActivity.getNextStartedActivityForResult();
+        assertThat(startedActivity).named("Next activity").isNotNull();
+        assertThat(startedActivity.intent.getComponent())
+                .isEqualTo(new ComponentName(application, FingerprintEnrollEnrolling.class));
+    }
+
+    private EnrollmentCallback verifyAndCaptureEnrollmentCallback() {
+        ArgumentCaptor<EnrollmentCallback> callbackCaptor =
+                ArgumentCaptor.forClass(EnrollmentCallback.class);
+        verify(mFingerprintManager).enroll(
+                any(byte[].class),
+                any(CancellationSignal.class),
+                anyInt(),
+                anyInt(),
+                callbackCaptor.capture());
+
+        return callbackCaptor.getValue();
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetailTest.java b/tests/robotests/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetailTest.java
index 40db72c..cb91d41 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetailTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetailTest.java
@@ -18,10 +18,9 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
-import static org.mockito.Matchers.any;
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.anyLong;
-import static org.mockito.Matchers.anyString;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.doReturn;
@@ -30,6 +29,7 @@
 import static org.mockito.Mockito.verify;
 
 import android.app.Activity;
+import android.app.Fragment;
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
@@ -61,7 +61,6 @@
 import org.mockito.ArgumentCaptor;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
 import org.robolectric.RuntimeEnvironment;
 import org.robolectric.annotation.Config;
@@ -122,22 +121,26 @@
         doReturn(mContext).when(mFragment).getContext();
         doReturn(mActivity).when(mFragment).getActivity();
         doReturn(SUMMARY).when(mFragment).getString(anyInt());
-        doReturn(APP_LABEL).when(mBundle).getString(anyString());
+        doReturn(APP_LABEL).when(mBundle).getString(nullable(String.class));
         doReturn(mBundle).when(mFragment).getArguments();
 
         ShadowEntityHeaderController.setUseMock(mEntityHeaderController);
         doReturn(mEntityHeaderController).when(mEntityHeaderController)
-                .setRecyclerView(any(RecyclerView.class), any(Lifecycle.class));
+                .setRecyclerView(nullable(RecyclerView.class), nullable(Lifecycle.class));
         doReturn(mEntityHeaderController).when(mEntityHeaderController)
                 .setButtonActions(anyInt(), anyInt());
         doReturn(mEntityHeaderController).when(mEntityHeaderController)
-                .setIcon(any(Drawable.class));
-        doReturn(mEntityHeaderController).when(mEntityHeaderController).setIcon(any(
+                .setIcon(nullable(Drawable.class));
+        doReturn(mEntityHeaderController).when(mEntityHeaderController).setIcon(nullable(
                 ApplicationsState.AppEntry.class));
-        doReturn(mEntityHeaderController).when(mEntityHeaderController).setLabel(anyString());
         doReturn(mEntityHeaderController).when(mEntityHeaderController)
-                .setLabel(any(ApplicationsState.AppEntry.class));
-        doReturn(mEntityHeaderController).when(mEntityHeaderController).setSummary(anyString());
+                .setLabel(nullable(String.class));
+        doReturn(mEntityHeaderController).when(mEntityHeaderController)
+                .setLabel(nullable(String.class));
+        doReturn(mEntityHeaderController).when(mEntityHeaderController)
+                .setLabel(nullable(ApplicationsState.AppEntry.class));
+        doReturn(mEntityHeaderController).when(mEntityHeaderController)
+                .setSummary(nullable(String.class));
 
         doReturn(UID).when(mBatterySipper).getUid();
         doReturn(APP_LABEL).when(mBatteryEntry).getLabel();
@@ -160,15 +163,13 @@
 
         final ArgumentCaptor<Bundle> captor = ArgumentCaptor.forClass(Bundle.class);
 
-        Answer<Void> callable = new Answer<Void>() {
-            @Override
-            public Void answer(InvocationOnMock invocation) throws Exception {
-                mBundle = captor.getValue();
-                return null;
-            }
+        Answer<Void> callable = invocation -> {
+            mBundle = captor.getValue();
+            return null;
         };
-        doAnswer(callable).when(mTestActivity).startPreferencePanelAsUser(any(), anyString(),
-                captor.capture(), anyInt(), any(), any());
+        doAnswer(callable).when(mTestActivity).startPreferencePanelAsUser(
+                nullable(Fragment.class), nullable(String.class), captor.capture(), anyInt(),
+                nullable(CharSequence.class), nullable(UserHandle.class));
     }
 
     @After
@@ -181,7 +182,7 @@
         mFragment.mAppEntry = null;
         mFragment.initHeader();
 
-        verify(mEntityHeaderController).setIcon(any(Drawable.class));
+        verify(mEntityHeaderController).setIcon(nullable(Drawable.class));
         verify(mEntityHeaderController).setLabel(APP_LABEL);
     }
 
@@ -281,21 +282,20 @@
                 mBatteryEntry, USAGE_PERCENT);
 
         verify(mTestActivity).startPreferencePanelAsUser(
-                any(), anyString(), any(), anyInt(), any(), eq(new UserHandle(10)));
+                nullable(Fragment.class), nullable(String.class), nullable(Bundle.class), anyInt(),
+                nullable(CharSequence.class), eq(new UserHandle(10)));
     }
 
     @Test
     public void testStartBatteryDetailPage_noBatteryUsage_hasBasicData() {
         final ArgumentCaptor<Bundle> captor = ArgumentCaptor.forClass(Bundle.class);
-        Answer<Void> callable = new Answer<Void>() {
-            @Override
-            public Void answer(InvocationOnMock invocation) throws Exception {
-                mBundle = captor.getValue();
-                return null;
-            }
+        Answer<Void> callable = invocation -> {
+            mBundle = captor.getValue();
+            return null;
         };
-        doAnswer(callable).when(mTestActivity).startPreferencePanelAsUser(any(), anyString(),
-                captor.capture(), anyInt(), any(), any());
+        doAnswer(callable).when(mTestActivity).startPreferencePanelAsUser(nullable(Fragment.class),
+                nullable(String.class), captor.capture(), anyInt(), nullable(CharSequence.class),
+                nullable(UserHandle.class));
 
         AdvancedPowerUsageDetail.startBatteryDetailPage(mTestActivity, null, PACKAGE_NAME[0]);
 
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/AppButtonsPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/fuelgauge/AppButtonsPreferenceControllerTest.java
index 2008afd..92df48e 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/AppButtonsPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/AppButtonsPreferenceControllerTest.java
@@ -344,6 +344,14 @@
         assertThat(controllable).isTrue();
     }
 
+    @Test
+    public void testRefreshUi_packageNull_shouldNotCrash() {
+        mController.mPackageName = null;
+
+        // Should not crash in this method
+        assertThat(mController.refreshUi()).isFalse();
+    }
+
     /**
      * The test fragment which implements
      * {@link ButtonActionDialogFragment.AppButtonsDialogListener}
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/BatteryHistoryPreferenceTest.java b/tests/robotests/src/com/android/settings/fuelgauge/BatteryHistoryPreferenceTest.java
index 221408d..bd6ae6a 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/BatteryHistoryPreferenceTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/BatteryHistoryPreferenceTest.java
@@ -15,8 +15,13 @@
  */
 package com.android.settings.fuelgauge;
 
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import android.content.Context;
-import android.os.PowerManager;
 import android.support.v7.preference.PreferenceViewHolder;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -35,16 +40,6 @@
 import org.mockito.MockitoAnnotations;
 import org.robolectric.RuntimeEnvironment;
 import org.robolectric.annotation.Config;
-import org.robolectric.util.ReflectionHelpers;
-
-import static org.mockito.AdditionalMatchers.not;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Matchers.eq;
-
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
 
 
 @RunWith(SettingsRobolectricTestRunner.class)
@@ -84,7 +79,7 @@
         mBatteryHistoryPreference.onBindViewHolder(mViewHolder);
 
         verify(mViewHolder).findViewById(R.id.battery_usage);
-        verify(mTextView).setText(anyString());
+        verify(mTextView).setText(nullable(String.class));
         verify(mBatteryInfo).bindHistory(mUsageView);
     }
 }
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/BatteryOptimizationPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/fuelgauge/BatteryOptimizationPreferenceControllerTest.java
index b3afbb4..77e3198 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/BatteryOptimizationPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/BatteryOptimizationPreferenceControllerTest.java
@@ -18,10 +18,8 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
-import static org.mockito.Matchers.any;
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.spy;
@@ -84,9 +82,9 @@
         final boolean handled = mController.handlePreferenceTreeClick(mPreference);
 
         assertThat(handled).isTrue();
-        verify(mSettingsActivity).startPreferencePanel(any(Fragment.class),
-                anyString(), any(Bundle.class), anyInt(), any(CharSequence.class),
-                any(Fragment.class), anyInt());
+        verify(mSettingsActivity).startPreferencePanel(nullable(Fragment.class),
+                nullable(String.class), nullable(Bundle.class), anyInt(),
+                nullable(CharSequence.class), nullable(Fragment.class), anyInt());
     }
 
     @Test
@@ -96,9 +94,9 @@
         final boolean handled = mController.handlePreferenceTreeClick(mPreference);
 
         assertThat(handled).isFalse();
-        verify(mSettingsActivity, never()).startPreferencePanel(any(Fragment.class),
-                anyString(), any(Bundle.class), anyInt(), any(CharSequence.class),
-                any(Fragment.class), anyInt());
+        verify(mSettingsActivity, never()).startPreferencePanel(nullable(Fragment.class),
+                nullable(String.class), nullable(Bundle.class), anyInt(),
+                nullable(CharSequence.class), nullable(Fragment.class), anyInt());
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/BatteryUtilsTest.java b/tests/robotests/src/com/android/settings/fuelgauge/BatteryUtilsTest.java
index 395d36d..45836ad 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/BatteryUtilsTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/BatteryUtilsTest.java
@@ -292,6 +292,19 @@
                 BatteryStats.STATS_SINCE_CHARGED)).isEqualTo(TIME_SINCE_LAST_FULL_CHARGE_MS);
     }
 
+    @Test
+    public void testSortUsageList() {
+        final List<BatterySipper> sippers = new ArrayList<>();
+        sippers.add(mNormalBatterySipper);
+        sippers.add(mScreenBatterySipper);
+        sippers.add(mSystemBatterySipper);
+
+        mBatteryUtils.sortUsageList(sippers);
+
+        assertThat(sippers).containsExactly(mNormalBatterySipper, mSystemBatterySipper,
+                mScreenBatterySipper);
+    }
+
     private BatterySipper createTestSmearBatterySipper(long activityTime, double totalPowerMah,
             int uidCode, boolean isUidNull) {
         final BatterySipper sipper = mock(BatterySipper.class);
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/PowerUsageFeatureProviderImplTest.java b/tests/robotests/src/com/android/settings/fuelgauge/PowerUsageFeatureProviderImplTest.java
index f32ea7a..8e9febe 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/PowerUsageFeatureProviderImplTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/PowerUsageFeatureProviderImplTest.java
@@ -125,4 +125,14 @@
 
         assertThat(mPowerFeatureProvider.isTypeSystem(mBatterySipper)).isFalse();
     }
+
+    @Test
+    public void testIsAdvancedUiEnabled_returnTrue() {
+        assertThat(mPowerFeatureProvider.isAdvancedUiEnabled()).isTrue();
+    }
+
+    @Test
+    public void testIsPowerAccountingToggleEnabled_returnTrue() {
+        assertThat(mPowerFeatureProvider.isPowerAccountingToggleEnabled()).isTrue();
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/anomaly/checker/WakeLockAnomalyDetectorTest.java b/tests/robotests/src/com/android/settings/fuelgauge/anomaly/checker/WakeLockAnomalyDetectorTest.java
index b5a4def..b0b0b99 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/anomaly/checker/WakeLockAnomalyDetectorTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/anomaly/checker/WakeLockAnomalyDetectorTest.java
@@ -18,10 +18,9 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
-import static org.mockito.Matchers.any;
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.anyLong;
-import static org.mockito.Matchers.anyString;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.spy;
@@ -101,9 +100,10 @@
         mContext = spy(RuntimeEnvironment.application);
         ReflectionHelpers.setField(mPolicy, "wakeLockThreshold", WAKELOCK_THRESHOLD_MS);
 
-        doReturn(false).when(mBatteryUtils).shouldHideSipper(any());
+        doReturn(false).when(mBatteryUtils).shouldHideSipper(nullable(BatterySipper.class));
         doReturn(mPackageManager).when(mContext).getPackageManager();
-        doReturn(mApplicationInfo).when(mPackageManager).getApplicationInfo(anyString(), anyInt());
+        doReturn(mApplicationInfo).when(mPackageManager)
+                .getApplicationInfo(nullable(String.class), anyInt());
 
         mAnomalySipper.uidObj = mAnomalyUid;
         mAnomalyWakelocks = new ArrayMap<>();
diff --git a/tests/robotests/src/com/android/settings/location/LocationPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/location/LocationPreferenceControllerTest.java
index f87f18b..d6b133b 100644
--- a/tests/robotests/src/com/android/settings/location/LocationPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/location/LocationPreferenceControllerTest.java
@@ -15,6 +15,13 @@
  */
 package com.android.settings.location;
 
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
@@ -37,13 +44,6 @@
 import org.mockito.MockitoAnnotations;
 import org.robolectric.annotation.Config;
 
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class LocationPreferenceControllerTest {
@@ -75,7 +75,7 @@
     public void updateState_shouldSetSummary() {
         mController.updateState(mPreference);
 
-        verify(mPreference).setSummary(anyString());
+        verify(mPreference).setSummary(nullable(String.class));
     }
 
     @Test
@@ -83,7 +83,7 @@
         mController.displayPreference(mScreen);
         mController.updateSummary();
 
-        verify(mPreference).setSummary(anyString());
+        verify(mPreference).setSummary(nullable(String.class));
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/network/NetworkDashboardFragmentTest.java b/tests/robotests/src/com/android/settings/network/NetworkDashboardFragmentTest.java
index e7f4968..358f12f 100644
--- a/tests/robotests/src/com/android/settings/network/NetworkDashboardFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/network/NetworkDashboardFragmentTest.java
@@ -39,6 +39,8 @@
 import java.util.List;
 
 import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.times;
@@ -85,7 +87,7 @@
 
         mFragment.onCreateOptionsMenu(null, null);
 
-        verify(resetController).buildMenuItem(any(Menu.class));
+        verify(resetController).buildMenuItem(nullable(Menu.class));
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/network/TetherPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/network/TetherPreferenceControllerTest.java
index 7e92bc5..cecc910 100644
--- a/tests/robotests/src/com/android/settings/network/TetherPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/network/TetherPreferenceControllerTest.java
@@ -20,7 +20,10 @@
 import android.bluetooth.BluetoothAdapter;
 import android.bluetooth.BluetoothPan;
 import android.bluetooth.BluetoothProfile;
+import android.content.ContentResolver;
 import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
 import android.database.ContentObserver;
 import android.net.ConnectivityManager;
 import android.provider.Settings;
@@ -41,6 +44,7 @@
 
 import java.util.concurrent.atomic.AtomicReference;
 
+import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.verify;
@@ -150,4 +154,36 @@
         verify(mPreference).setSummary(R.string.switch_off_text);
     }
 
+    @Test
+    public void onResume_shouldRegisterTetherReceiver() {
+        when(mContext.getContentResolver()).thenReturn(mock(ContentResolver.class));
+
+        mController.onResume();
+
+        verify(mContext).registerReceiver(
+            any(TetherPreferenceController.TetherBroadcastReceiver.class), any(IntentFilter.class));
+    }
+
+    @Test
+    public void onPause_shouldUnregisterTetherReceiver() {
+        when(mContext.getContentResolver()).thenReturn(mock(ContentResolver.class));
+        mController.onResume();
+
+        mController.onPause();
+
+        verify(mContext).unregisterReceiver(
+            any(TetherPreferenceController.TetherBroadcastReceiver.class));
+    }
+
+    @Test
+    public void tetherStatesChanged_shouldUpdateSummary() {
+        final Context context = RuntimeEnvironment.application;
+        ReflectionHelpers.setField(mController, "mContext", context);
+        mController.onResume();
+
+        context.sendBroadcast(new Intent(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
+
+        verify(mController).updateSummary();
+    }
+
 }
diff --git a/tests/robotests/src/com/android/settings/notification/NotificationAccessSettingsTest.java b/tests/robotests/src/com/android/settings/notification/NotificationAccessSettingsTest.java
index b0aa856..756f1d0 100644
--- a/tests/robotests/src/com/android/settings/notification/NotificationAccessSettingsTest.java
+++ b/tests/robotests/src/com/android/settings/notification/NotificationAccessSettingsTest.java
@@ -16,6 +16,10 @@
 
 package com.android.settings.notification;
 
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.verify;
+
 import android.content.Context;
 
 import com.android.internal.logging.nano.MetricsProto;
@@ -31,10 +35,6 @@
 import org.mockito.MockitoAnnotations;
 import org.robolectric.annotation.Config;
 
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.verify;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class NotificationAccessSettingsTest {
@@ -56,12 +56,12 @@
     @Test
     public void logSpecialPermissionChange() {
         mFragment.logSpecialPermissionChange(true, "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_NOTIVIEW_ALLOW),
                 eq("app"));
 
         mFragment.logSpecialPermissionChange(false, "app");
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
+        verify(mFeatureFactory.metricsFeatureProvider).action(nullable(Context.class),
                 eq(MetricsProto.MetricsEvent.APP_SPECIAL_PERMISSION_NOTIVIEW_DENY),
                 eq("app"));
     }
diff --git a/tests/robotests/src/com/android/settings/notification/VolumeSeekBarPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/notification/VolumeSeekBarPreferenceControllerTest.java
index 581ed47..657739f 100644
--- a/tests/robotests/src/com/android/settings/notification/VolumeSeekBarPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/notification/VolumeSeekBarPreferenceControllerTest.java
@@ -16,8 +16,14 @@
 
 package com.android.settings.notification;
 
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import android.content.Context;
-import android.preference.SeekBarVolumizer;
 import android.support.v7.preference.Preference;
 import android.support.v7.preference.PreferenceScreen;
 
@@ -31,13 +37,6 @@
 import org.mockito.MockitoAnnotations;
 import org.robolectric.annotation.Config;
 
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class VolumeSeekBarPreferenceControllerTest {
@@ -56,7 +55,7 @@
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
-        when(mScreen.findPreference(anyString())).thenReturn(mPreference);
+        when(mScreen.findPreference(nullable(String.class))).thenReturn(mPreference);
         mController =
             new VolumeSeekBarPreferenceControllerTestable(mContext, mCallback);
     }
diff --git a/tests/robotests/src/com/android/settings/notification/WorkSoundPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/notification/WorkSoundPreferenceControllerTest.java
index 520e1f0..44aaf04 100644
--- a/tests/robotests/src/com/android/settings/notification/WorkSoundPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/notification/WorkSoundPreferenceControllerTest.java
@@ -16,6 +16,16 @@
 
 package com.android.settings.notification;
 
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import android.content.Context;
 import android.os.UserHandle;
 import android.os.UserManager;
@@ -38,16 +48,6 @@
 import org.mockito.MockitoAnnotations;
 import org.robolectric.annotation.Config;
 
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class WorkSoundPreferenceControllerTest {
@@ -94,9 +94,9 @@
 
     @Test
     public void isAvailable_managedProfileAndNotSingleVolume_shouldReturnTrue() {
-        when(mAudioHelper.getManagedProfileId(any(UserManager.class)))
+        when(mAudioHelper.getManagedProfileId(nullable(UserManager.class)))
                 .thenReturn(UserHandle.myUserId());
-        when(mAudioHelper.isUserUnlocked(any(UserManager.class), anyInt())).thenReturn(true);
+        when(mAudioHelper.isUserUnlocked(nullable(UserManager.class), anyInt())).thenReturn(true);
         when(mAudioHelper.isSingleVolume()).thenReturn(false);
 
         assertThat(mController.isAvailable()).isTrue();
@@ -104,9 +104,9 @@
 
     @Test
     public void isAvailable_noManagedProfile_shouldReturnFalse() {
-        when(mAudioHelper.getManagedProfileId(any(UserManager.class)))
+        when(mAudioHelper.getManagedProfileId(nullable(UserManager.class)))
                 .thenReturn(UserHandle.USER_NULL);
-        when(mAudioHelper.isUserUnlocked(any(UserManager.class), anyInt())).thenReturn(true);
+        when(mAudioHelper.isUserUnlocked(nullable(UserManager.class), anyInt())).thenReturn(true);
         when(mAudioHelper.isSingleVolume()).thenReturn(false);
 
         assertThat(mController.isAvailable()).isFalse();
@@ -114,9 +114,9 @@
 
     @Test
     public void isAvailable_singleVolume_shouldReturnFalse() {
-        when(mAudioHelper.getManagedProfileId(any(UserManager.class)))
+        when(mAudioHelper.getManagedProfileId(nullable(UserManager.class)))
                 .thenReturn(UserHandle.myUserId());
-        when(mAudioHelper.isUserUnlocked(any(UserManager.class), anyInt())).thenReturn(true);
+        when(mAudioHelper.isUserUnlocked(nullable(UserManager.class), anyInt())).thenReturn(true);
         when(mAudioHelper.isSingleVolume()).thenReturn(true);
 
         assertThat(mController.isAvailable()).isFalse();
@@ -128,7 +128,7 @@
         when(mAudioHelper.isSingleVolume()).thenReturn(false);
         when(mFragment.getPreferenceScreen()).thenReturn(mScreen);
         when(mAudioHelper.createPackageContextAsUser(anyInt())).thenReturn(mContext);
-        when(mAudioHelper.getManagedProfileId(any(UserManager.class)))
+        when(mAudioHelper.getManagedProfileId(nullable(UserManager.class)))
                 .thenReturn(UserHandle.USER_NULL);
 
         // When the fragment first displays, the category should not appear.
@@ -137,7 +137,7 @@
 
         // However, when a managed profile is added later, the category should appear.
         mController.onResume();
-        when(mAudioHelper.getManagedProfileId(any(UserManager.class)))
+        when(mAudioHelper.getManagedProfileId(nullable(UserManager.class)))
                 .thenReturn(UserHandle.myUserId());
         mController.onManagedProfileAdded(UserHandle.myUserId());
 
@@ -150,9 +150,9 @@
         when(mAudioHelper.isSingleVolume()).thenReturn(false);
         when(mFragment.getPreferenceScreen()).thenReturn(mScreen);
         when(mAudioHelper.createPackageContextAsUser(anyInt())).thenReturn(mContext);
-        when(mAudioHelper.getManagedProfileId(any(UserManager.class)))
+        when(mAudioHelper.getManagedProfileId(nullable(UserManager.class)))
                 .thenReturn(UserHandle.myUserId());
-        when(mAudioHelper.isUserUnlocked(any(UserManager.class), anyInt())).thenReturn(true);
+        when(mAudioHelper.isUserUnlocked(nullable(UserManager.class), anyInt())).thenReturn(true);
 
         // Which is in resumed state:
         mController.displayPreference(mScreen);
@@ -161,7 +161,7 @@
         verify(mWorkCategory, times(2)).setVisible(true);
 
         // When a managed profile is removed, the category should be hidden.
-        when(mAudioHelper.getManagedProfileId(any(UserManager.class)))
+        when(mAudioHelper.getManagedProfileId(nullable(UserManager.class)))
                 .thenReturn(UserHandle.USER_NULL);
         mController.onManagedProfileRemoved(UserHandle.myUserId());
 
@@ -171,9 +171,9 @@
 
     @Test
     public void displayPreference_isAvailable_shouldShowPreferenceCategory() {
-        when(mAudioHelper.getManagedProfileId(any(UserManager.class)))
+        when(mAudioHelper.getManagedProfileId(nullable(UserManager.class)))
                 .thenReturn(UserHandle.myUserId());
-        when(mAudioHelper.isUserUnlocked(any(UserManager.class), anyInt())).thenReturn(true);
+        when(mAudioHelper.isUserUnlocked(nullable(UserManager.class), anyInt())).thenReturn(true);
         when(mAudioHelper.isSingleVolume()).thenReturn(false);
         when(mFragment.getPreferenceScreen()).thenReturn(mScreen);
         when(mAudioHelper.createPackageContextAsUser(anyInt())).thenReturn(mContext);
@@ -184,7 +184,7 @@
 
     @Test
     public void displayPreference_notAvailable_shouldHidePreferenceCategory() {
-        when(mAudioHelper.getManagedProfileId(any(UserManager.class)))
+        when(mAudioHelper.getManagedProfileId(nullable(UserManager.class)))
                 .thenReturn(UserHandle.USER_NULL);
         when(mAudioHelper.isSingleVolume()).thenReturn(true);
         when(mFragment.getPreferenceScreen()).thenReturn(mScreen);
@@ -200,7 +200,7 @@
 
         mController.onPreferenceChange(preference, "hello");
 
-        verify(preference).setSummary(anyString());
+        verify(preference).setSummary(nullable(String.class));
     }
 
     @Test
@@ -208,9 +208,9 @@
         when(mTelephonyManager.isVoiceCapable()).thenReturn(false);
         mController = new WorkSoundPreferenceController(mContext, mFragment, null, mAudioHelper);
 
-        when(mAudioHelper.getManagedProfileId(any(UserManager.class)))
+        when(mAudioHelper.getManagedProfileId(nullable(UserManager.class)))
                 .thenReturn(UserHandle.myUserId());
-        when(mAudioHelper.isUserUnlocked(any(UserManager.class), anyInt())).thenReturn(true);
+        when(mAudioHelper.isUserUnlocked(nullable(UserManager.class), anyInt())).thenReturn(true);
         when(mAudioHelper.isSingleVolume()).thenReturn(false);
         when(mFragment.getPreferenceScreen()).thenReturn(mScreen);
         when(mAudioHelper.createPackageContextAsUser(anyInt())).thenReturn(mContext);
@@ -234,9 +234,9 @@
         when(mAudioHelper.isSingleVolume()).thenReturn(false);
         when(mFragment.getPreferenceScreen()).thenReturn(mScreen);
         when(mAudioHelper.createPackageContextAsUser(anyInt())).thenReturn(mContext);
-        when(mAudioHelper.getManagedProfileId(any(UserManager.class)))
+        when(mAudioHelper.getManagedProfileId(nullable(UserManager.class)))
                 .thenReturn(UserHandle.myUserId());
-        when(mAudioHelper.isUserUnlocked(any(UserManager.class), anyInt())).thenReturn(false);
+        when(mAudioHelper.isUserUnlocked(nullable(UserManager.class), anyInt())).thenReturn(false);
 
         // When resumed:
         mController.displayPreference(mScreen);
@@ -256,9 +256,9 @@
     @Test
     public void onResume_shouldSetUserIdToPreference() {
         final int managedProfileUserId = 10;
-        when(mAudioHelper.getManagedProfileId(any(UserManager.class)))
+        when(mAudioHelper.getManagedProfileId(nullable(UserManager.class)))
                 .thenReturn(managedProfileUserId);
-        when(mAudioHelper.isUserUnlocked(any(UserManager.class), anyInt())).thenReturn(true);
+        when(mAudioHelper.isUserUnlocked(nullable(UserManager.class), anyInt())).thenReturn(true);
         when(mAudioHelper.isSingleVolume()).thenReturn(false);
         when(mFragment.getPreferenceScreen()).thenReturn(mScreen);
         when(mAudioHelper.createPackageContextAsUser(anyInt())).thenReturn(mContext);
diff --git a/tests/robotests/src/com/android/settings/password/ChooseLockGenericControllerTest.java b/tests/robotests/src/com/android/settings/password/ChooseLockGenericControllerTest.java
index 589e2df..198273b 100644
--- a/tests/robotests/src/com/android/settings/password/ChooseLockGenericControllerTest.java
+++ b/tests/robotests/src/com/android/settings/password/ChooseLockGenericControllerTest.java
@@ -18,6 +18,7 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyBoolean;
 import static org.mockito.Matchers.anyInt;
@@ -209,7 +210,8 @@
     @Test
     public void upgradeQuality_noDpmRequirement_shouldReturnQuality() {
         doReturn(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED)
-                .when(mDevicePolicyManager).getPasswordQuality(any(ComponentName.class), anyInt());
+                .when(mDevicePolicyManager)
+                .getPasswordQuality(nullable(ComponentName.class), anyInt());
 
         int upgradedQuality = mController.upgradeQuality(
                 DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC);
@@ -220,7 +222,8 @@
     @Test
     public void upgradeQuality_dpmRequirement_shouldReturnRequiredQuality() {
         doReturn(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC)
-                .when(mDevicePolicyManager).getPasswordQuality(any(ComponentName.class), anyInt());
+                .when(mDevicePolicyManager)
+                .getPasswordQuality(nullable(ComponentName.class), anyInt());
 
         int upgradedQuality = mController.upgradeQuality(
                 DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
diff --git a/tests/robotests/src/com/android/settings/print/PrintSettingsFragmentTest.java b/tests/robotests/src/com/android/settings/print/PrintSettingsFragmentTest.java
index 0e2a2f6..57219d4 100644
--- a/tests/robotests/src/com/android/settings/print/PrintSettingsFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/print/PrintSettingsFragmentTest.java
@@ -22,6 +22,8 @@
 
 import android.app.Activity;
 import android.content.res.Resources;
+import android.print.PrintJob;
+import android.print.PrintJobInfo;
 import android.print.PrintManager;
 import android.printservice.PrintServiceInfo;
 
@@ -34,9 +36,11 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Mock;
+import org.mockito.Mockito;
 import org.mockito.MockitoAnnotations;
 import org.robolectric.annotation.Config;
 
+import java.util.ArrayList;
 import java.util.List;
 
 
@@ -63,13 +67,26 @@
     }
 
     @Test
+    public void testSummary_hasActiveJob_shouldSetSummaryToNumberOfJobs() {
+        final List<PrintJob> printJobs = new ArrayList<>();
+        final PrintJob job = mock(PrintJob.class, Mockito.RETURNS_DEEP_STUBS);
+        printJobs.add(job);
+        when(job.getInfo().getState()).thenReturn(PrintJobInfo.STATE_STARTED);
+        when(mPrintManager.getPrintJobs()).thenReturn(printJobs);
+
+        mSummaryProvider.setListening(true);
+
+        verify(mRes).getQuantityString(R.plurals.print_jobs_summary, 1, 1);
+    }
+
+    @Test
     public void testSummary_shouldSetSummaryToNumberOfPrintServices() {
         final List<PrintServiceInfo> printServices = mock(List.class);
         when(printServices.isEmpty()).thenReturn(false);
         when(printServices.size()).thenReturn(2);
         // 2 services
         when(mPrintManager.getPrintServices(PrintManager.ENABLED_SERVICES))
-            .thenReturn(printServices);
+                .thenReturn(printServices);
 
         mSummaryProvider.setListening(true);
 
diff --git a/tests/robotests/src/com/android/settings/search/DatabaseIndexingManagerTest.java b/tests/robotests/src/com/android/settings/search/DatabaseIndexingManagerTest.java
index ab8891b..6bcefca 100644
--- a/tests/robotests/src/com/android/settings/search/DatabaseIndexingManagerTest.java
+++ b/tests/robotests/src/com/android/settings/search/DatabaseIndexingManagerTest.java
@@ -33,19 +33,14 @@
 import android.os.Build;
 import android.provider.SearchIndexableResource;
 import android.util.ArrayMap;
+
 import com.android.settings.R;
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
-import com.android.settings.search.DatabaseIndexingManager;
-import com.android.settings.search.IndexDatabaseHelper;
-import com.android.settings.search.IndexingCallback;
-import com.android.settings.search.ResultPayload;
-import com.android.settings.search.ResultPayloadUtils;
-import com.android.settings.search.SearchFeatureProviderImpl;
-import com.android.settings.search.SearchIndexableRaw;
 import com.android.settings.testutils.DatabaseTestUtils;
 import com.android.settings.testutils.shadow.ShadowDatabaseIndexingUtils;
 import com.android.settings.testutils.shadow.ShadowRunnableAsyncTask;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -140,7 +135,7 @@
 
     @After
     public void cleanUp() {
-        DatabaseTestUtils.clearDb();
+        DatabaseTestUtils.clearDb(mContext);
     }
 
     @Test
@@ -263,7 +258,7 @@
         SearchIndexableResource resource = getFakeResource(R.xml.display_settings);
         mManager.indexOneSearchIndexableData(mDb, localeStr, resource, new HashMap<>());
         Cursor cursor = mDb.rawQuery("SELECT * FROM prefs_index", null);
-        assertThat(cursor.getCount()).isEqualTo(19);
+        assertThat(cursor.getCount()).isEqualTo(16);
     }
 
     @Test
@@ -278,7 +273,7 @@
         Cursor cursor = mDb.rawQuery("SELECT * FROM prefs_index WHERE enabled = 0", null);
         assertThat(cursor.getCount()).isEqualTo(2);
         cursor = mDb.rawQuery("SELECT * FROM prefs_index WHERE enabled = 1", null);
-        assertThat(cursor.getCount()).isEqualTo(17);
+        assertThat(cursor.getCount()).isEqualTo(14);
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/search/DatabaseResultLoaderTest.java b/tests/robotests/src/com/android/settings/search/DatabaseResultLoaderTest.java
index bcd3371..5118cff 100644
--- a/tests/robotests/src/com/android/settings/search/DatabaseResultLoaderTest.java
+++ b/tests/robotests/src/com/android/settings/search/DatabaseResultLoaderTest.java
@@ -25,13 +25,6 @@
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
 import com.android.settings.dashboard.SiteMapManager;
-import com.android.settings.search.DatabaseIndexingUtils;
-import com.android.settings.search.DatabaseResultLoader;
-import com.android.settings.search.IndexDatabaseHelper;
-import com.android.settings.search.InlineSwitchPayload;
-import com.android.settings.search.ResultPayload;
-import com.android.settings.search.ResultPayloadUtils;
-import com.android.settings.search.SearchResult;
 import com.android.settings.testutils.DatabaseTestUtils;
 import com.android.settings.testutils.FakeFeatureFactory;
 
@@ -45,7 +38,10 @@
 import org.robolectric.RuntimeEnvironment;
 import org.robolectric.annotation.Config;
 
+import java.util.Arrays;
+import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
 
 import static com.google.common.truth.Truth.assertThat;
 import static org.mockito.Matchers.anyString;
@@ -81,7 +77,7 @@
 
     @After
     public void cleanUp() {
-        DatabaseTestUtils.clearDb();
+        DatabaseTestUtils.clearDb(mContext);
     }
 
     @Test
@@ -224,17 +220,19 @@
     }
 
     @Test
-    public void testSpecialCaseTwoWords_firstWordMatches_ranksHigher() {
+    public void testSpecialCaseTwoWords_multipleResults() {
         final String caseOne = "Apple pear";
         final String caseTwo = "Banana apple";
         insertSpecialCase(caseOne);
         insertSpecialCase(caseTwo);
         DatabaseResultLoader loader = new DatabaseResultLoader(mContext, "App", null);
-        List<? extends SearchResult> results = loader.loadInBackground();
-
-        assertThat(results.get(0).title).isEqualTo(caseOne);
-        assertThat(results.get(1).title).isEqualTo(caseTwo);
-        assertThat(results.get(0).rank).isLessThan(results.get(1).rank);
+        Set<? extends SearchResult> results = loader.loadInBackground();
+        Set<CharSequence> expectedTitles = new HashSet<>(Arrays.asList(caseOne, caseTwo));
+        Set<CharSequence> actualTitles = new HashSet<>();
+        for (SearchResult result : results) {
+            actualTitles.add(result.title);
+        }
+        assertThat(actualTitles).isEqualTo(expectedTitles);
     }
 
     private void insertSpecialCase(String specialCase) {
diff --git a/tests/robotests/src/com/android/settings/search/DynamicIndexableContentMonitorTest.java b/tests/robotests/src/com/android/settings/search/DynamicIndexableContentMonitorTest.java
index 8d585e5..753a512 100644
--- a/tests/robotests/src/com/android/settings/search/DynamicIndexableContentMonitorTest.java
+++ b/tests/robotests/src/com/android/settings/search/DynamicIndexableContentMonitorTest.java
@@ -16,20 +16,6 @@
 
 package com.android.settings.search;
 
-import static com.google.common.truth.Truth.assertThat;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyBoolean;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.only;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
 import android.accessibilityservice.AccessibilityServiceInfo;
 import android.app.Activity;
 import android.app.Application;
@@ -91,6 +77,19 @@
 import java.util.Collections;
 import java.util.List;
 
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyBoolean;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.only;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(
         manifest = TestConfig.MANIFEST_PATH,
@@ -163,7 +162,7 @@
         DynamicIndexableContentMonitor.resetForTesting();
         mRobolectricPackageManager.reset();
 
-        DatabaseTestUtils.clearDb();
+        DatabaseTestUtils.clearDb(mActivity);
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/search/InlineSwitchViewHolderTest.java b/tests/robotests/src/com/android/settings/search/InlineSwitchViewHolderTest.java
index 65d99f4..ce483a4 100644
--- a/tests/robotests/src/com/android/settings/search/InlineSwitchViewHolderTest.java
+++ b/tests/robotests/src/com/android/settings/search/InlineSwitchViewHolderTest.java
@@ -19,10 +19,8 @@
 
 import android.content.Context;
 import android.graphics.drawable.Drawable;
-import android.util.Pair;
 import android.view.LayoutInflater;
 
-import com.android.internal.logging.nano.MetricsProto;
 import com.android.settings.R;
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
@@ -42,8 +40,6 @@
 
 import static com.google.common.truth.Truth.assertThat;
 import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 @RunWith(SettingsRobolectricTestRunner.class)
@@ -98,10 +94,6 @@
 
         mHolder.switchView.performClick();
 
-        verify(mFeatureFactory.metricsFeatureProvider).action(
-                any(Context.class),
-                eq(MetricsProto.MetricsEvent.ACTION_CLICK_SETTINGS_SEARCH_INLINE_RESULT),
-                any(Pair.class), any(Pair.class), any(Pair.class));
         assertThat(mHolder.titleView.getText()).isEqualTo(TITLE);
         assertThat(mHolder.summaryView.getText()).isEqualTo(SUMMARY);
         assertThat(mHolder.iconView.getDrawable()).isEqualTo(mIcon);
diff --git a/tests/robotests/src/com/android/settings/search/InstalledAppResultLoaderTest.java b/tests/robotests/src/com/android/settings/search/InstalledAppResultLoaderTest.java
index e167091..1a30157 100644
--- a/tests/robotests/src/com/android/settings/search/InstalledAppResultLoaderTest.java
+++ b/tests/robotests/src/com/android/settings/search/InstalledAppResultLoaderTest.java
@@ -43,7 +43,9 @@
 
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
 
 import static android.content.pm.ApplicationInfo.FLAG_SYSTEM;
 import static android.content.pm.ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
@@ -185,18 +187,19 @@
     }
 
     @Test
-    public void query_matchingQuery_shouldRankBasedOnSimilarity() {
+    public void query_matchingQuery_multipleResults() {
         final String query = "app";
 
         mLoader = new InstalledAppResultLoader(mContext, mPackageManagerWrapper, query,
                 mSiteMapManager);
-        final List<? extends SearchResult> results = mLoader.loadInBackground();
+        final Set<? extends SearchResult> results = mLoader.loadInBackground();
 
-        // List is sorted by rank
-        assertThat(results.get(0).rank).isAtMost(results.get(1).rank);
-        assertThat(results.get(0).title).isEqualTo("app4");
-        assertThat(results.get(1).title).isEqualTo("app");
-        assertThat(results.get(2).title).isEqualTo("appBuffer");
+        Set<CharSequence> expectedTitles = new HashSet<>(Arrays.asList("app4", "app", "appBuffer"));
+        Set<CharSequence> actualTitles = new HashSet<>();
+        for (SearchResult result : results) {
+            actualTitles.add(result.title);
+        }
+        assertThat(actualTitles).isEqualTo(expectedTitles);
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/search/IntentSearchViewHolderTest.java b/tests/robotests/src/com/android/settings/search/IntentSearchViewHolderTest.java
index ee1c913..ba1408f7 100644
--- a/tests/robotests/src/com/android/settings/search/IntentSearchViewHolderTest.java
+++ b/tests/robotests/src/com/android/settings/search/IntentSearchViewHolderTest.java
@@ -21,18 +21,12 @@
 import android.content.Context;
 import android.content.Intent;
 import android.graphics.drawable.Drawable;
-import android.util.Pair;
 import android.view.LayoutInflater;
 import android.view.View;
 
-import com.android.internal.logging.nano.MetricsProto;
 import com.android.settings.R;
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
-import com.android.settings.search.IntentSearchViewHolder;
-import com.android.settings.search.ResultPayload;
-import com.android.settings.search.SearchFragment;
-import com.android.settings.search.SearchResult;
 import com.android.settings.search.SearchResult.Builder;
 import com.android.settings.testutils.FakeFeatureFactory;
 
@@ -51,6 +45,7 @@
 
 import static com.google.common.truth.Truth.assertThat;
 import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.verify;
 
@@ -102,12 +97,8 @@
         assertThat(mHolder.summaryView.getVisibility()).isEqualTo(View.VISIBLE);
         assertThat(mHolder.breadcrumbView.getVisibility()).isEqualTo(View.GONE);
 
-        verify(mFragment).onSearchResultClicked();
+        verify(mFragment).onSearchResultClicked(eq(mHolder), anyString());
         verify(mFragment).startActivity(any(Intent.class));
-        verify(mFeatureFactory.metricsFeatureProvider).action(any(Context.class),
-                eq(MetricsProto.MetricsEvent.ACTION_CLICK_SETTINGS_SEARCH_RESULT),
-                eq(((ResultPayload)result.payload).getIntent().getComponent().flattenToString()),
-                any(Pair.class));
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/search/MockAppLoader.java b/tests/robotests/src/com/android/settings/search/MockAppLoader.java
index 35e56a1..c68cbdf 100644
--- a/tests/robotests/src/com/android/settings/search/MockAppLoader.java
+++ b/tests/robotests/src/com/android/settings/search/MockAppLoader.java
@@ -21,8 +21,8 @@
 import com.android.settings.search.InstalledAppResultLoader;
 import com.android.settings.search.SearchResult;
 
-import java.util.ArrayList;
-import java.util.List;
+import java.util.HashSet;
+import java.util.Set;
 
 /**
  * Mock loader to subvert the requirements of returning data while also driving the Loader
@@ -35,12 +35,12 @@
     }
 
     @Override
-    public List<? extends SearchResult> loadInBackground() {
-        return new ArrayList<>();
+    public Set<? extends SearchResult> loadInBackground() {
+        return new HashSet<>();
     }
 
     @Override
-    protected void onDiscardResult(List<? extends SearchResult> result) {
+    protected void onDiscardResult(Set<? extends SearchResult> result) {
 
     }
 }
diff --git a/tests/robotests/src/com/android/settings/search/MockDBLoader.java b/tests/robotests/src/com/android/settings/search/MockDBLoader.java
index 562e375..b28c1ed 100644
--- a/tests/robotests/src/com/android/settings/search/MockDBLoader.java
+++ b/tests/robotests/src/com/android/settings/search/MockDBLoader.java
@@ -21,8 +21,8 @@
 import com.android.settings.search.DatabaseResultLoader;
 import com.android.settings.search.SearchResult;
 
-import java.util.ArrayList;
-import java.util.List;
+import java.util.HashSet;
+import java.util.Set;
 
 /**
  * Mock loader to subvert the requirements of returning data while also driving the Loader
@@ -35,12 +35,12 @@
     }
 
     @Override
-    public List<? extends SearchResult> loadInBackground() {
-        return new ArrayList<>();
+    public Set<? extends SearchResult> loadInBackground() {
+        return new HashSet<>();
     }
 
     @Override
-    protected void onDiscardResult(List<? extends SearchResult> result) {
+    protected void onDiscardResult(Set<? extends SearchResult> result) {
 
     }
 }
diff --git a/tests/robotests/src/com/android/settings/search/SavedQueryLoaderTest.java b/tests/robotests/src/com/android/settings/search/SavedQueryLoaderTest.java
index 5222360..943fa7e 100644
--- a/tests/robotests/src/com/android/settings/search/SavedQueryLoaderTest.java
+++ b/tests/robotests/src/com/android/settings/search/SavedQueryLoaderTest.java
@@ -59,7 +59,7 @@
 
     @After
     public void cleanUp() {
-        DatabaseTestUtils.clearDb();
+        DatabaseTestUtils.clearDb(mContext);
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/search/SavedQueryRecorderAndRemoverTest.java b/tests/robotests/src/com/android/settings/search/SavedQueryRecorderAndRemoverTest.java
index 5037626..e60d21a 100644
--- a/tests/robotests/src/com/android/settings/search/SavedQueryRecorderAndRemoverTest.java
+++ b/tests/robotests/src/com/android/settings/search/SavedQueryRecorderAndRemoverTest.java
@@ -22,10 +22,6 @@
 
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
-import com.android.settings.search.SavedQueryLoader;
-import com.android.settings.search.SavedQueryRecorder;
-import com.android.settings.search.SavedQueryRemover;
-import com.android.settings.search.SearchResult;
 import com.android.settings.testutils.DatabaseTestUtils;
 
 import org.junit.After;
@@ -54,7 +50,7 @@
 
     @After
     public void cleanUp() {
-        DatabaseTestUtils.clearDb();
+        DatabaseTestUtils.clearDb(mContext);
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/search/SavedQueryViewHolderTest.java b/tests/robotests/src/com/android/settings/search/SavedQueryViewHolderTest.java
index 6927be7..967864d 100644
--- a/tests/robotests/src/com/android/settings/search/SavedQueryViewHolderTest.java
+++ b/tests/robotests/src/com/android/settings/search/SavedQueryViewHolderTest.java
@@ -17,6 +17,10 @@
 
 package com.android.settings.search;
 
+import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
 import android.content.Context;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -36,10 +40,6 @@
 import org.robolectric.RuntimeEnvironment;
 import org.robolectric.annotation.Config;
 
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class SavedQueryViewHolderTest {
@@ -71,7 +71,7 @@
         mTitleView.performClick();
         mRemoveButton.performClick();
 
-        verify(mSearchFragment).onSavedQueryClicked(any(CharSequence.class));
-        verify(mSearchFragment).onRemoveSavedQueryClicked(any(CharSequence.class));
+        verify(mSearchFragment).onSavedQueryClicked(nullable(CharSequence.class));
+        verify(mSearchFragment).onRemoveSavedQueryClicked(nullable(CharSequence.class));
     }
 }
diff --git a/tests/robotests/src/com/android/settings/search/SearchFragmentTest.java b/tests/robotests/src/com/android/settings/search/SearchFragmentTest.java
index 94dc233..44851b1 100644
--- a/tests/robotests/src/com/android/settings/search/SearchFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/search/SearchFragmentTest.java
@@ -21,18 +21,22 @@
 import android.content.Context;
 import android.content.Loader;
 import android.os.Bundle;
+import android.util.Pair;
 import android.view.View;
 
 import com.android.internal.logging.nano.MetricsProto;
 import com.android.settings.R;
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
+import com.android.settings.testutils.DatabaseTestUtils;
 import com.android.settings.testutils.FakeFeatureFactory;
 
+import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Answers;
+import org.mockito.ArgumentMatcher;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 import org.robolectric.Robolectric;
@@ -41,11 +45,13 @@
 import org.robolectric.util.ActivityController;
 import org.robolectric.util.ReflectionHelpers;
 
-import java.util.List;
+import java.util.Set;
 
 import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.argThat;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
@@ -79,6 +85,11 @@
         mFeatureFactory = (FakeFeatureFactory) FakeFeatureFactory.getFactory(mContext);
     }
 
+    @After
+    public void tearDown() {
+        DatabaseTestUtils.clearDb(RuntimeEnvironment.application);
+    }
+
     @Test
     public void screenRotate_shouldPersistQuery() {
         when(mFeatureFactory.searchFeatureProvider
@@ -249,7 +260,7 @@
 
         Robolectric.flushForegroundThreadScheduler();
 
-        verify(fragment, times(2)).onLoadFinished(any(Loader.class), any(List.class));
+        verify(fragment, times(2)).onLoadFinished(any(Loader.class), any(Set.class));
     }
 
     @Test
@@ -353,12 +364,12 @@
     @Test
     public void onIndexingFinished_noActivity_shouldNotCrash() {
         ActivityController<SearchActivity> activityController =
-            Robolectric.buildActivity(SearchActivity.class);
+                Robolectric.buildActivity(SearchActivity.class);
         activityController.setup();
         SearchFragment fragment = (SearchFragment) spy(activityController.get().getFragmentManager()
-            .findFragmentById(R.id.main_content));
+                .findFragmentById(R.id.main_content));
         when(mFeatureFactory.searchFeatureProvider.isIndexingComplete(any(Context.class)))
-            .thenReturn(true);
+                .thenReturn(true);
         fragment.mQuery = "bright";
         ReflectionHelpers.setField(fragment, "mLoaderManager", null);
         ReflectionHelpers.setField(fragment, "mHost", null);
@@ -366,4 +377,29 @@
         fragment.onIndexingFinished();
         // no crash
     }
+
+    @Test
+    public void onSearchResultClicked_shouldLogResultMeta() {
+        SearchFragment fragment = new SearchFragment();
+        ReflectionHelpers.setField(fragment, "mMetricsFeatureProvider",
+                mFeatureFactory.metricsFeatureProvider);
+        ReflectionHelpers.setField(fragment, "mSearchAdapter", mock(SearchResultsAdapter.class));
+        fragment.mSavedQueryController = mock(SavedQueryController.class);
+
+        // Should log result name, result count, clicked rank, etc.
+        final SearchViewHolder result = mock(SearchViewHolder.class);
+        fragment.onSearchResultClicked(result, "test_setting");
+
+        verify(mFeatureFactory.metricsFeatureProvider).action(
+                nullable(Context.class),
+                eq(MetricsProto.MetricsEvent.ACTION_CLICK_SETTINGS_SEARCH_RESULT),
+                eq("test_setting"),
+                argThat(pairMatches(MetricsProto.MetricsEvent.FIELD_SETTINGS_SERACH_RESULT_COUNT)),
+                argThat(pairMatches(MetricsProto.MetricsEvent.FIELD_SETTINGS_SERACH_RESULT_RANK)),
+                argThat(pairMatches(MetricsProto.MetricsEvent.FIELD_SETTINGS_SERACH_QUERY_LENGTH)));
+    }
+
+    private ArgumentMatcher<Pair<Integer, Object>> pairMatches(int tag) {
+        return pair -> pair.first == tag;
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/search/SearchResultsAdapterTest.java b/tests/robotests/src/com/android/settings/search/SearchResultsAdapterTest.java
index 5af8550..8290348 100644
--- a/tests/robotests/src/com/android/settings/search/SearchResultsAdapterTest.java
+++ b/tests/robotests/src/com/android/settings/search/SearchResultsAdapterTest.java
@@ -46,8 +46,10 @@
 import static org.mockito.Mockito.when;
 
 import java.util.ArrayList;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Objects;
+import java.util.Set;
 
 import static com.google.common.truth.Truth.assertThat;
 
@@ -85,7 +87,7 @@
 
     @Test
     public void testSingleSourceMerge_exactCopyReturned() {
-        ArrayList<SearchResult> intentResults = getIntentSampleResults();
+        Set<SearchResult> intentResults = getIntentSampleResults();
         mAdapter.addSearchResults(intentResults, mLoaderClassName);
         mAdapter.displaySearchResults("");
 
@@ -111,8 +113,10 @@
 
     @Test
     public void testEndToEndSearch_properResultsMerged_correctOrder() {
-        mAdapter.addSearchResults(getDummyAppResults(), InstalledAppResultLoader.class.getName());
-        mAdapter.addSearchResults(getDummyDbResults(), DatabaseResultLoader.class.getName());
+        mAdapter.addSearchResults(new HashSet<SearchResult>(getDummyAppResults()),
+                InstalledAppResultLoader.class.getName());
+        mAdapter.addSearchResults(new HashSet<SearchResult>(getDummyDbResults()),
+                DatabaseResultLoader.class.getName());
         int count = mAdapter.displaySearchResults("");
 
         List<SearchResult> results = mAdapter.getSearchResults();
@@ -130,13 +134,16 @@
         List<AppSearchResult> appResults = getDummyAppResults();
         List<SearchResult> dbResults = getDummyDbResults();
         // Add two individual items
-        mAdapter.addSearchResults(appResults.subList(0,1),
+        mAdapter.addSearchResults(new HashSet<SearchResult>(appResults.subList(0, 1)),
                 InstalledAppResultLoader.class.getName());
-        mAdapter.addSearchResults(dbResults.subList(0,1), DatabaseResultLoader.class.getName());
+        mAdapter.addSearchResults(new HashSet<SearchResult>(dbResults.subList(0, 1)),
+                DatabaseResultLoader.class.getName());
         mAdapter.displaySearchResults("");
         // Add super-set of items
-        mAdapter.addSearchResults(appResults, InstalledAppResultLoader.class.getName());
-        mAdapter.addSearchResults(dbResults, DatabaseResultLoader.class.getName());
+        mAdapter.addSearchResults(
+                new HashSet<SearchResult>(appResults), InstalledAppResultLoader.class.getName());
+        mAdapter.addSearchResults(
+                new HashSet<SearchResult>(dbResults), DatabaseResultLoader.class.getName());
         int count = mAdapter.displaySearchResults("");
 
         List<SearchResult> results = mAdapter.getSearchResults();
@@ -170,13 +177,16 @@
         List<AppSearchResult> appResults = getDummyAppResults();
         List<SearchResult> dbResults = getDummyDbResults();
         // Add list of items
-        mAdapter.addSearchResults(appResults, InstalledAppResultLoader.class.getName());
-        mAdapter.addSearchResults(dbResults, DatabaseResultLoader.class.getName());
+        mAdapter.addSearchResults(new HashSet<SearchResult>(appResults),
+                InstalledAppResultLoader.class.getName());
+        mAdapter.addSearchResults(new HashSet<SearchResult>(dbResults),
+                DatabaseResultLoader.class.getName());
         mAdapter.displaySearchResults("");
         // Add subset of items
-        mAdapter.addSearchResults(appResults.subList(0,1),
+        mAdapter.addSearchResults(new HashSet<SearchResult>(appResults.subList(0, 1)),
                 InstalledAppResultLoader.class.getName());
-        mAdapter.addSearchResults(dbResults.subList(0,1), DatabaseResultLoader.class.getName());
+        mAdapter.addSearchResults(new HashSet<>(dbResults.subList(0, 1)),
+                DatabaseResultLoader.class.getName());
         int count = mAdapter.displaySearchResults("");
 
         List<SearchResult> results = mAdapter.getSearchResults();
@@ -231,8 +241,8 @@
         return results;
     }
 
-    private ArrayList<SearchResult> getIntentSampleResults() {
-        ArrayList<SearchResult> sampleResults = new ArrayList<>();
+    private Set<SearchResult> getIntentSampleResults() {
+        Set<SearchResult> sampleResults = new HashSet<>();
         ArrayList<String> breadcrumbs = new ArrayList<>();
         final Drawable icon = mContext.getDrawable(R.drawable.ic_search_history);
         final ResultPayload payload = new ResultPayload(null);
diff --git a/tests/robotests/src/com/android/settings/search/SiteMapManagerTest.java b/tests/robotests/src/com/android/settings/search/SiteMapManagerTest.java
index 2e585ac..b0a5b00 100644
--- a/tests/robotests/src/com/android/settings/search/SiteMapManagerTest.java
+++ b/tests/robotests/src/com/android/settings/search/SiteMapManagerTest.java
@@ -80,7 +80,7 @@
 
     @After
     public void cleanUp() {
-        DatabaseTestUtils.clearDb();
+        DatabaseTestUtils.clearDb(mContext);
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/security/LockscreenDashboardFragmentTest.java b/tests/robotests/src/com/android/settings/security/LockscreenDashboardFragmentTest.java
new file mode 100644
index 0000000..c6a0e53
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/security/LockscreenDashboardFragmentTest.java
@@ -0,0 +1,49 @@
+/*
+ * 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.security;
+
+import com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.XmlTestUtils;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+import java.util.List;
+
+import static com.google.common.truth.Truth.assertThat;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class LockscreenDashboardFragmentTest {
+
+    private LockscreenDashboardFragment mFragment;
+
+    @Test
+    public void containsNotificationSettingsForPrimaryUserAndWorkProfile() {
+        mFragment = new LockscreenDashboardFragment();
+
+        List<String> keys = XmlTestUtils.getKeysFromPreferenceXml(RuntimeEnvironment.application,
+                mFragment.getPreferenceScreenResId());
+
+        assertThat(keys).containsAllOf(LockscreenDashboardFragment.KEY_LOCK_SCREEN_NOTIFICATON,
+                LockscreenDashboardFragment.KEY_LOCK_SCREEN_NOTIFICATON_WORK_PROFILE,
+                LockscreenDashboardFragment.KEY_LOCK_SCREEN_NOTIFICATON_WORK_PROFILE_HEADER);
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/security/SecurityFeatureProviderImplTest.java b/tests/robotests/src/com/android/settings/security/SecurityFeatureProviderImplTest.java
index 77f5ecc..9cc33a3 100644
--- a/tests/robotests/src/com/android/settings/security/SecurityFeatureProviderImplTest.java
+++ b/tests/robotests/src/com/android/settings/security/SecurityFeatureProviderImplTest.java
@@ -28,6 +28,7 @@
 import android.util.Pair;
 
 import com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.R;
 import com.android.settings.TestConfig;
 import com.android.settingslib.drawer.DashboardCategory;
 import com.android.settingslib.drawer.Tile;
@@ -180,7 +181,7 @@
         mImpl.initPreferences(mContext, screen, dashboardCategory);
         verify(screen.findPreference(MOCK_KEY)).setIcon(SecurityFeatureProviderImpl.DEFAULT_ICON);
         verify(screen.findPreference(MOCK_KEY))
-                .setSummary(SecurityFeatureProviderImpl.DEFAULT_SUMMARY);
+                .setSummary(mContext.getString(R.string.summary_placeholder));
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/testutils/DatabaseTestUtils.java b/tests/robotests/src/com/android/settings/testutils/DatabaseTestUtils.java
index 8fbe1c9..7472996 100644
--- a/tests/robotests/src/com/android/settings/testutils/DatabaseTestUtils.java
+++ b/tests/robotests/src/com/android/settings/testutils/DatabaseTestUtils.java
@@ -16,13 +16,18 @@
 
 package com.android.settings.testutils;
 
+import android.content.Context;
+
 import com.android.settings.search.IndexDatabaseHelper;
 
 import java.lang.reflect.Field;
 
 public class DatabaseTestUtils {
 
-    public static void clearDb() {
+    public static void clearDb(Context context) {
+        IndexDatabaseHelper helper = IndexDatabaseHelper.getInstance(context);
+        helper.close();
+
         Field instance;
         Class clazz = IndexDatabaseHelper.class;
         try {
diff --git a/tests/robotests/src/com/android/settings/webview/WebViewAppPickerTest.java b/tests/robotests/src/com/android/settings/webview/WebViewAppPickerTest.java
index 655f354..56397f0 100644
--- a/tests/robotests/src/com/android/settings/webview/WebViewAppPickerTest.java
+++ b/tests/robotests/src/com/android/settings/webview/WebViewAppPickerTest.java
@@ -16,20 +16,6 @@
 
 package com.android.settings.webview;
 
-import static android.provider.Settings.ACTION_WEBVIEW_SETTINGS;
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 import android.app.Activity;
 import android.content.Context;
 import android.content.Intent;
@@ -44,6 +30,8 @@
 import com.android.settings.TestConfig;
 import com.android.settings.applications.PackageManagerWrapper;
 import com.android.settings.applications.defaultapps.DefaultAppInfo;
+import com.android.settings.core.instrumentation.MetricsFeatureProvider;
+import com.android.settings.testutils.FakeFeatureFactory;
 import com.android.settings.widget.RadioButtonPreference;
 
 import org.junit.Before;
@@ -58,6 +46,20 @@
 
 import java.util.Arrays;
 
+import static android.provider.Settings.ACTION_WEBVIEW_SETTINGS;
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class WebViewAppPickerTest {
@@ -87,6 +89,7 @@
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
+        FakeFeatureFactory.setupForTest(mActivity);
         when(mActivity.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
 
         mPicker = new WebViewAppPicker();
@@ -96,7 +99,8 @@
         doReturn(mActivity).when(mPicker).getActivity();
 
         ReflectionHelpers.setField(mPicker, "mPm", mPackageManager);
-
+        ReflectionHelpers.setField(mPicker, "mMetricsFeatureProvider",
+                mock(MetricsFeatureProvider.class));
         mWvusWrapper = mock(WebViewUpdateServiceWrapper.class);
         mPicker.setWebViewUpdateServiceWrapper(mWvusWrapper);
     }
diff --git a/tests/robotests/src/com/android/settings/widget/EntityHeaderControllerTest.java b/tests/robotests/src/com/android/settings/widget/EntityHeaderControllerTest.java
index e386282..c29068f 100644
--- a/tests/robotests/src/com/android/settings/widget/EntityHeaderControllerTest.java
+++ b/tests/robotests/src/com/android/settings/widget/EntityHeaderControllerTest.java
@@ -234,6 +234,33 @@
     }
 
     @Test
+    public void iconContentDescription_shouldWorkWithSetIcon() {
+        final View view = mLayoutInflater
+                .inflate(R.layout.settings_entity_header, null /* root */);
+        when(mFragment.getActivity()).thenReturn(mock(Activity.class));
+        mController = EntityHeaderController.newInstance(mActivity, mFragment, view);
+        String description = "Fake Description";
+        mController.setIcon(mShadowContext.getDrawable(R.drawable.ic_add));
+        mController.setIconContentDescription(description);
+        mController.done(mActivity);
+        assertThat(view.findViewById(R.id.entity_header_icon).getContentDescription().toString())
+                .isEqualTo(description);
+    }
+
+    @Test
+    public void iconContentDescription_shouldWorkWithoutSetIcon() {
+        final View view = mLayoutInflater
+                .inflate(R.layout.settings_entity_header, null /* root */);
+        when(mFragment.getActivity()).thenReturn(mock(Activity.class));
+        mController = EntityHeaderController.newInstance(mActivity, mFragment, view);
+        String description = "Fake Description";
+        mController.setIconContentDescription(description);
+        mController.done(mActivity);
+        assertThat(view.findViewById(R.id.entity_header_icon).getContentDescription().toString())
+                .isEqualTo(description);
+    }
+
+    @Test
     public void bindButton_hasAppNotifIntent_shouldShowButton() {
         final View appLinks = mLayoutInflater
                 .inflate(R.layout.settings_entity_header, null /* root */);
diff --git a/tests/robotests/src/com/android/settings/widget/SingleLineSummaryPreferenceTest.java b/tests/robotests/src/com/android/settings/widget/FixedLineSummaryPreferenceTest.java
similarity index 77%
rename from tests/robotests/src/com/android/settings/widget/SingleLineSummaryPreferenceTest.java
rename to tests/robotests/src/com/android/settings/widget/FixedLineSummaryPreferenceTest.java
index d4c5392..e1dc7f0 100644
--- a/tests/robotests/src/com/android/settings/widget/SingleLineSummaryPreferenceTest.java
+++ b/tests/robotests/src/com/android/settings/widget/FixedLineSummaryPreferenceTest.java
@@ -15,19 +15,16 @@
  */
 package com.android.settings.widget;
 
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 import android.content.Context;
 import android.support.v7.preference.PreferenceViewHolder;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.widget.LinearLayout;
 import android.widget.TextView;
+
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
-import com.android.settings.widget.SingleLineSummaryPreference;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -36,25 +33,30 @@
 import org.robolectric.RuntimeEnvironment;
 import org.robolectric.annotation.Config;
 
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
-public class SingleLineSummaryPreferenceTest {
+public class FixedLineSummaryPreferenceTest {
 
-    @Mock private TextView mSummary;
+    @Mock
+    private TextView mSummary;
 
     private Context mContext;
     private PreferenceViewHolder mHolder;
-    private SingleLineSummaryPreference mPreference;
+    private FixedLineSummaryPreference mPreference;
 
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
 
         mContext = RuntimeEnvironment.application;
-        mPreference = new SingleLineSummaryPreference(mContext, null);
+        mPreference = new FixedLineSummaryPreference(mContext, null);
         LayoutInflater inflater = LayoutInflater.from(mContext);
         final View view = inflater.inflate(mPreference.getLayoutResource(),
-            new LinearLayout(mContext), false);
+                new LinearLayout(mContext), false);
         mHolder = spy(PreferenceViewHolder.createInstanceForTests(view));
         when(mHolder.findViewById(android.R.id.summary)).thenReturn(mSummary);
     }
@@ -62,8 +64,17 @@
     @Test
     public void onBindViewHolder_shouldSetSingleLine() {
         mPreference.onBindViewHolder(mHolder);
-        final TextView summary = (TextView) mHolder.findViewById(android.R.id.summary);
 
-        verify(mSummary).setSingleLine();
+        verify(mSummary).setMinLines(1);
+        verify(mSummary).setMaxLines(1);
+    }
+
+    @Test
+    public void onBindViewHolder_TwoLineSummary_shouldSetTwoLines() {
+        mPreference.setSummaryLineCount(2);
+        mPreference.onBindViewHolder(mHolder);
+
+        verify(mSummary).setMinLines(2);
+        verify(mSummary).setMaxLines(2);
     }
 }
diff --git a/tests/robotests/src/com/android/settings/widget/RadioButtonPickerFragmentTest.java b/tests/robotests/src/com/android/settings/widget/RadioButtonPickerFragmentTest.java
index e6d00b3..b0889b4 100644
--- a/tests/robotests/src/com/android/settings/widget/RadioButtonPickerFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/widget/RadioButtonPickerFragmentTest.java
@@ -16,12 +16,6 @@
 
 package com.android.settings.widget;
 
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
 import android.app.Activity;
 import android.content.Context;
 import android.os.UserManager;
@@ -30,7 +24,7 @@
 import com.android.settings.SettingsRobolectricTestRunner;
 import com.android.settings.TestConfig;
 import com.android.settings.applications.defaultapps.DefaultAppInfo;
-import com.android.settings.applications.defaultapps.DefaultAppPickerFragment;
+import com.android.settings.testutils.FakeFeatureFactory;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -44,6 +38,12 @@
 import java.util.ArrayList;
 import java.util.List;
 
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 @RunWith(SettingsRobolectricTestRunner.class)
 @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
 public class RadioButtonPickerFragmentTest {
@@ -61,6 +61,7 @@
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
+        FakeFeatureFactory.setupForTest(mActivity);
         mFragment = spy(new TestFragment());
 
         when(mActivity.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
@@ -72,7 +73,6 @@
     public void onAttach_userIsInitialized() {
         mFragment.onAttach((Context) mActivity);
 
-        verify(mActivity).getPackageManager();
         verify(mActivity).getSystemService(Context.USER_SERVICE);
     }
 
@@ -99,7 +99,7 @@
         assertThat(mFragment.setDefaultKeyCalled).isTrue();
     }
 
-    public static class TestFragment extends DefaultAppPickerFragment {
+    public static class TestFragment extends RadioButtonPickerFragment {
 
         boolean setDefaultKeyCalled;
 
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 9601c49..526c6d1 100644
--- a/tests/robotests/src/com/android/settings/wifi/details/WifiDetailPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/wifi/details/WifiDetailPreferenceControllerTest.java
@@ -17,6 +17,7 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.inOrder;
@@ -158,7 +159,7 @@
         when(mockConnectivityManager.getNetworkInfo(any(Network.class)))
                 .thenReturn(mockNetworkInfo);
         doNothing().when(mockConnectivityManagerWrapper).registerNetworkCallback(
-                any(NetworkRequest.class), mCallbackCaptor.capture(), any(Handler.class));
+                nullable(NetworkRequest.class), mCallbackCaptor.capture(), nullable(Handler.class));
         doNothing().when(mockForgetButton).setOnClickListener(mForgetClickListener.capture());
 
         when(mockWifiInfo.getLinkSpeed()).thenReturn(LINK_SPEED);
@@ -195,9 +196,9 @@
                 .thenReturn(mockConnectionDetailPref);
         when(mockScreen.findPreference(WifiDetailPreferenceController.KEY_BUTTONS_PREF))
                 .thenReturn(mockButtonsPref);
-        when(mockButtonsPref.findViewById(R.id.left_button))
+        when(mockButtonsPref.findViewById(R.id.forget_button))
                 .thenReturn(mockForgetButton);
-        when(mockButtonsPref.findViewById(R.id.right_button))
+        when(mockButtonsPref.findViewById(R.id.signin_button))
                 .thenReturn(mockSignInButton);
         when(mockScreen.findPreference(WifiDetailPreferenceController.KEY_SIGNAL_STRENGTH_PREF))
                 .thenReturn(mockSignalStrengthPref);
@@ -254,7 +255,7 @@
         mController.onResume();
 
         verify(mockConnectivityManagerWrapper, times(1)).registerNetworkCallback(
-                any(NetworkRequest.class), mCallbackCaptor.capture(), any(Handler.class));
+                nullable(NetworkRequest.class), mCallbackCaptor.capture(), nullable(Handler.class));
     }
 
     @Test
diff --git a/tests/unit/src/com/android/settings/applications/ManageApplicationsUnitTest.java b/tests/unit/src/com/android/settings/applications/ManageApplicationsUnitTest.java
index 10c9edb..c65f9ea 100644
--- a/tests/unit/src/com/android/settings/applications/ManageApplicationsUnitTest.java
+++ b/tests/unit/src/com/android/settings/applications/ManageApplicationsUnitTest.java
@@ -20,9 +20,13 @@
 import android.support.test.filters.SmallTest;
 import android.support.test.runner.AndroidJUnit4;
 
+import com.android.settingslib.applications.AppUtils;
 import com.android.settingslib.applications.ApplicationsState;
 import com.android.settingslib.applications.ApplicationsState.AppFilter;
 
+import com.android.settingslib.applications.ApplicationsState.CompoundFilter;
+import com.android.settingslib.applications.instantapps.InstantAppDataProvider;
+import java.lang.reflect.Field;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -33,9 +37,9 @@
 @RunWith(AndroidJUnit4.class)
 public class ManageApplicationsUnitTest {
     @Test
-    public void getOverrideFilter_filtersVolumeForAudio() {
+    public void getCompositeFilter_filtersVolumeForAudio() {
         AppFilter filter =
-                ManageApplications.getOverrideFilter(
+                ManageApplications.getCompositeFilter(
                         ManageApplications.LIST_TYPE_STORAGE,
                         ManageApplications.STORAGE_TYPE_MUSIC,
                         "uuid");
@@ -49,9 +53,9 @@
     }
 
     @Test
-    public void getOverrideFilter_filtersVolumeForVideo() {
+    public void getCompositeFilter_filtersVolumeForVideo() {
         AppFilter filter =
-                ManageApplications.getOverrideFilter(
+                ManageApplications.getCompositeFilter(
                         ManageApplications.LIST_TYPE_MOVIES,
                         ManageApplications.STORAGE_TYPE_DEFAULT,
                         "uuid");
@@ -65,9 +69,9 @@
     }
 
     @Test
-    public void getOverrideFilter_filtersVolumeForGames() {
+    public void getCompositeFilter_filtersVolumeForGames() {
         ApplicationsState.AppFilter filter =
-                ManageApplications.getOverrideFilter(
+                ManageApplications.getCompositeFilter(
                         ManageApplications.LIST_TYPE_GAMES,
                         ManageApplications.STORAGE_TYPE_DEFAULT,
                         "uuid");
@@ -81,12 +85,35 @@
     }
 
     @Test
-    public void getOverrideFilter_isEmptyNormally() {
+    public void getCompositeFilter_isEmptyNormally() {
         ApplicationsState.AppFilter filter =
-                ManageApplications.getOverrideFilter(
+                ManageApplications.getCompositeFilter(
                         ManageApplications.LIST_TYPE_MAIN,
                         ManageApplications.STORAGE_TYPE_DEFAULT,
                         "uuid");
         assertThat(filter).isNull();
     }
+
+    @Test
+    public void getCompositeFilter_worksWithInstantApps() throws Exception {
+        Field field = AppUtils.class.getDeclaredField("sInstantAppDataProvider");
+        field.setAccessible(true);
+        field.set(AppUtils.class, (InstantAppDataProvider) (i -> true));
+
+        AppFilter filter =
+            ManageApplications.getCompositeFilter(
+                ManageApplications.LIST_TYPE_STORAGE,
+                ManageApplications.STORAGE_TYPE_MUSIC,
+                "uuid");
+        AppFilter composedFilter = new CompoundFilter(ApplicationsState.FILTER_INSTANT, filter);
+
+        final ApplicationInfo info = new ApplicationInfo();
+        info.volumeUuid = "uuid";
+        info.category = ApplicationInfo.CATEGORY_AUDIO;
+        info.privateFlags = ApplicationInfo.PRIVATE_FLAG_INSTANT;
+        final ApplicationsState.AppEntry appEntry = mock(ApplicationsState.AppEntry.class);
+        appEntry.info = info;
+
+        assertThat(composedFilter.filterApp(appEntry)).isTrue();
+    }
 }