Merge "Allow creating last user even if a guest exists." into lmp-dev
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 0f7e381..63cb07c 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -138,6 +138,17 @@
                 android:value="true" />
         </activity>
 
+        <activity android:name="AirplaneModeVoiceActivity"
+                android:label="@string/wireless_networks_settings_title"
+                android:theme="@android:style/Theme.Material.Light.Voice"
+                android:exported="true"
+                android:taskAffinity="">
+            <intent-filter>
+                <action android:name="android.settings.VOICE_CONTROL_AIRPLANE_MODE" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <category android:name="android.intent.category.VOICE" />
+            </intent-filter>
+        </activity>
 
         <!-- Top-level settings -->
 
@@ -458,6 +469,21 @@
                 android:value="true" />
         </activity>
 
+        <activity android:name="Settings$VoiceInputSettingsActivity"
+                android:label="@string/voice_input_settings_title"
+                android:taskAffinity="com.android.settings"
+                android:parentActivityName="Settings$InputMethodAndLanguageSettingsActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <action android:name="android.settings.VOICE_INPUT_SETTINGS" />
+                <category android:name="android.intent.category.DEFAULT" />
+            </intent-filter>
+            <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
+                android:value="com.android.settings.voice.VoiceInputSettings" />
+            <meta-data android:name="com.android.settings.TOP_LEVEL_HEADER_ID"
+                android:resource="@id/language_settings" />
+        </activity>
+
         <activity android:name="Settings$KeyboardLayoutPickerActivity"
                 android:label="@string/keyboard_layout_picker_title"
                 android:clearTaskOnLaunch="true">
@@ -973,6 +999,21 @@
             </intent-filter>
         </activity>
 
+        <activity android:name="Settings$UsageAccessSettingsActivity"
+                android:label="@string/usage_access_title"
+                android:taskAffinity="com.android.settings"
+                android:parentActivityName="Settings$SecuritySettingsActivity">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <action android:name="android.settings.USAGE_ACCESS_SETTINGS" />
+                <category android:name="android.intent.category.DEFAULT" />
+            </intent-filter>
+            <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
+                android:value="com.android.settings.UsageAccessSettings" />
+            <meta-data android:name="com.android.settings.TOP_LEVEL_HEADER_ID"
+                android:resource="@id/security_settings" />
+        </activity>
+
         <activity-alias android:name="SetProfileOwner"
                 android:label="@string/profile_owner_add_title"
                 android:targetActivity="DeviceAdminAdd">
@@ -1508,7 +1549,7 @@
             </intent-filter>
         </activity>
 
-        <activity android:name="UsageStats" android:label="@string/usage_stats_label"
+        <activity android:name="UsageStatsActivity" android:label="@string/usage_stats_label"
                   android:taskAffinity="com.android.settings"
                   android:parentActivityName="Settings">
             <intent-filter>
diff --git a/res/drawable/wifi_signal_colored.xml b/res/drawable/wifi_signal_colored.xml
new file mode 100644
index 0000000..4eb41c0
--- /dev/null
+++ b/res/drawable/wifi_signal_colored.xml
@@ -0,0 +1,68 @@
+<?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.
+-->
+
+<selector xmlns:android="http://schemas.android.com/apk/res/android"
+        xmlns:settings="http://schemas.android.com/apk/res/com.android.settings">
+    <item settings:state_encrypted="true">
+        <level-list>
+            <item android:maxLevel="0">
+                <bitmap
+                    android:src="@drawable/ic_wifi_lock_signal_1_light"
+                    android:tint="?attr/wifi_signal_color" />
+            </item>
+            <item android:maxLevel="1">
+                <bitmap
+                    android:src="@drawable/ic_wifi_lock_signal_2_light"
+                    android:tint="?attr/wifi_signal_color" />
+            </item>
+            <item android:maxLevel="2">
+                <bitmap
+                    android:src="@drawable/ic_wifi_lock_signal_3_light"
+                    android:tint="?attr/wifi_signal_color" />
+            </item>
+            <item android:maxLevel="3">
+                <bitmap
+                    android:src="@drawable/ic_wifi_lock_signal_4_light"
+                    android:tint="?attr/wifi_signal_color" />
+            </item>
+        </level-list>
+    </item>
+    <item settings:state_encrypted="false">
+        <level-list>
+            <item android:maxLevel="0">
+                <bitmap
+                    android:src="@drawable/ic_wifi_signal_1_light"
+                    android:tint="?attr/wifi_signal_color" />
+            </item>
+            <item android:maxLevel="1">
+                <bitmap
+                    android:src="@drawable/ic_wifi_signal_2_light"
+                    android:tint="?attr/wifi_signal_color" />
+            </item>
+            <item android:maxLevel="2">
+                <bitmap
+                    android:src="@drawable/ic_wifi_signal_3_light"
+                    android:tint="?attr/wifi_signal_color" />
+            </item>
+            <item android:maxLevel="3">
+                <bitmap
+                    android:src="@drawable/ic_wifi_signal_4_light"
+                    android:tint="?attr/wifi_signal_color" />
+            </item>
+        </level-list>
+    </item>
+</selector>
+
diff --git a/res/layout-sw600dp/crypt_keeper_pattern_entry.xml b/res/layout-sw600dp/crypt_keeper_pattern_entry.xml
index 4685ebf..3937008 100644
--- a/res/layout-sw600dp/crypt_keeper_pattern_entry.xml
+++ b/res/layout-sw600dp/crypt_keeper_pattern_entry.xml
@@ -18,26 +18,24 @@
 -->
 
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:orientation="vertical"
     android:layout_width="match_parent"
-    android:layout_height="match_parent">
+    android:layout_height="match_parent"
+    android:orientation="vertical"
+    android:layout_marginTop="@dimen/crypt_keeper_pattern_top_margin">
 
     <include layout="@layout/crypt_keeper_status" />
 
-    <RelativeLayout
-        android:layout_width="wrap_content"
-        android:layout_height="0dip"
-        android:layout_weight="1"
-        android:layout_gravity="center_horizontal">
+    <LinearLayout
+        android:layout_width="@dimen/crypt_keeper_pattern_size"
+        android:layout_height="@dimen/crypt_keeper_pattern_size"
+        android:orientation="horizontal"
+        android:layout_gravity="center_horizontal"
+        android:layout_marginTop="@dimen/crypt_keeper_pattern_separator">
 
-        <!-- Password entry field -->
-        <LinearLayout
-            android:layout_height="@dimen/crypt_keeper_pattern_size"
-            android:layout_width="@dimen/crypt_keeper_pattern_size"
-            android:layout_centerVertical="true"
-            android:orientation="horizontal">
-            <include layout="@layout/crypt_keeper_pattern_field" />
-        </LinearLayout>
+        <include layout="@layout/crypt_keeper_pattern_field" />
 
-    </RelativeLayout>
+    </LinearLayout>
+
+    <include layout="@layout/crypt_keeper_emergency_button" />
+
 </LinearLayout>
diff --git a/res/layout/advanced_security_settings.xml b/res/layout/advanced_security_settings.xml
deleted file mode 100644
index 98ff43d..0000000
--- a/res/layout/advanced_security_settings.xml
+++ /dev/null
@@ -1,37 +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
-  -->
-
-<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
-        android:layout_width="match_parent"
-        android:layout_height="match_parent"
-        android:paddingStart="@dimen/settings_side_margin"
-        android:paddingEnd="@dimen/settings_side_margin">
-
-    <ListView android:id="@android:id/list"
-            android:layout_width="match_parent"
-            android:layout_height="match_parent"
-            android:drawSelectorOnTop="false"
-            android:fastScrollEnabled="true" />
-
-    <TextView android:id="@android:id/empty"
-            android:layout_width="match_parent"
-            android:layout_height="match_parent"
-            android:gravity="center"
-            android:text="@string/no_trust_agents"
-            android:textAppearance="?android:attr/textAppearanceMedium" />
-
-</FrameLayout>
diff --git a/res/layout/crypt_keeper_emergency_button.xml b/res/layout/crypt_keeper_emergency_button.xml
new file mode 100644
index 0000000..d0004de
--- /dev/null
+++ b/res/layout/crypt_keeper_emergency_button.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+**
+** Copyright 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.
+*/
+-->
+
+<!-- Emergency call button.
+     Text is set by CryptKeeper.updateEmergencyCallButtonState() -->
+<Button
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/emergencyCallButton"
+    android:layout_width="wrap_content"
+    android:layout_height="0dp"
+    android:layout_gravity="center_horizontal"
+    android:textSize="14sp"
+    android:fontFamily="sans-serif"
+    android:textColor="#FFFFFF"
+    android:layout_weight="1"
+    android:gravity="bottom"
+    style="?android:attr/borderlessButtonStyle" />
diff --git a/res/layout/crypt_keeper_password_entry.xml b/res/layout/crypt_keeper_password_entry.xml
index 6e99527..a7fecba 100644
--- a/res/layout/crypt_keeper_password_entry.xml
+++ b/res/layout/crypt_keeper_password_entry.xml
@@ -20,36 +20,23 @@
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
-    android:orientation="vertical">
+    android:orientation="vertical"
+    android:layout_marginTop="@dimen/crypt_keeper_password_top_margin">
 
     <include layout="@layout/crypt_keeper_status" />
 
     <LinearLayout
-        android:layout_height="0dp"
-        android:layout_width="match_parent"
-        android:layout_weight="1"
-        android:layout_marginStart="@dimen/crypt_keeper_edit_text_margin"
-        android:layout_marginEnd="@dimen/crypt_keeper_edit_text_margin"
-        android:orientation="vertical"
-        android:gravity="center_vertical">
+        android:layout_width="@dimen/crypt_keeper_password_width"
+        android:layout_height="wrap_content"
+        android:orientation="horizontal"
+        android:layout_marginTop="16dip"
+        android:layout_gravity="center_horizontal"
+        android:background="@color/crypt_keeper_password_background">
 
-        <LinearLayout
-            android:background="@color/crypt_keeper_password_background"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:orientation="horizontal">
-            <include layout="@layout/crypt_keeper_password_field" />
-        </LinearLayout>
+        <include layout="@layout/crypt_keeper_password_field" />
 
     </LinearLayout>
 
-    <!-- Emergency call button.
-         Text is set by CryptKeeper.updateEmergencyCallButtonState() -->
-    <Button android:id="@+id/emergencyCallButton"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center_horizontal"
-        android:layout_marginTop="@dimen/crypt_keeper_emergency_call_space_above"
-        style="?android:attr/borderlessButtonStyle" />
+    <include layout="@layout/crypt_keeper_emergency_button" />
 
 </LinearLayout>
diff --git a/res/layout/crypt_keeper_pattern_entry.xml b/res/layout/crypt_keeper_pattern_entry.xml
index 80e318f..00d3d6e 100644
--- a/res/layout/crypt_keeper_pattern_entry.xml
+++ b/res/layout/crypt_keeper_pattern_entry.xml
@@ -20,35 +20,22 @@
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
-    android:orientation="vertical">
+    android:orientation="vertical"
+    android:layout_marginTop="@dimen/crypt_keeper_pattern_top_margin">
 
     <include layout="@layout/crypt_keeper_status" />
 
     <LinearLayout
-        android:layout_height="0dp"
         android:layout_width="match_parent"
-        android:layout_weight="1"
-        android:orientation="vertical"
-        android:gravity="center_vertical">
+        android:layout_height="wrap_content"
+        android:layout_marginStart="@dimen/crypt_keeper_pattern_margin"
+        android:layout_marginEnd="@dimen/crypt_keeper_pattern_margin"
+        android:orientation="horizontal">
 
-        <LinearLayout
-            android:layout_height="wrap_content"
-            android:layout_width="match_parent"
-            android:layout_marginStart="@dimen/crypt_keeper_edit_text_margin"
-            android:layout_marginEnd="@dimen/crypt_keeper_edit_text_margin"
-            android:orientation="horizontal" >
-            <include layout="@layout/crypt_keeper_pattern_field" />
-        </LinearLayout>
+        <include layout="@layout/crypt_keeper_pattern_field" />
 
     </LinearLayout>
 
-    <!-- Emergency call button.
-         Text and icon are set by CryptKeeper.updateEmergencyCallButtonState() -->
-    <Button android:id="@+id/emergencyCallButton"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center"
-        android:layout_marginTop="@dimen/crypt_keeper_emergency_call_space_above"
-        style="?android:attr/borderlessButtonStyle" />
+    <include layout="@layout/crypt_keeper_emergency_button" />
 
 </LinearLayout>
diff --git a/res/layout/crypt_keeper_pin_entry.xml b/res/layout/crypt_keeper_pin_entry.xml
index 0bcbec5..3926ab0 100644
--- a/res/layout/crypt_keeper_pin_entry.xml
+++ b/res/layout/crypt_keeper_pin_entry.xml
@@ -20,36 +20,23 @@
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
-    android:orientation="vertical">
+    android:orientation="vertical"
+    android:layout_marginTop="@dimen/crypt_keeper_password_top_margin">
 
     <include layout="@layout/crypt_keeper_status" />
 
     <LinearLayout
-        android:layout_height="0dp"
-        android:layout_width="match_parent"
-        android:layout_weight="1"
-        android:layout_marginStart="@dimen/crypt_keeper_edit_text_margin"
-        android:layout_marginEnd="@dimen/crypt_keeper_edit_text_margin"
-        android:orientation="vertical"
-        android:gravity="center_vertical">
+        android:layout_width="@dimen/crypt_keeper_password_width"
+        android:layout_height="wrap_content"
+        android:layout_marginTop="16dip"
+        android:orientation="horizontal"
+        android:layout_gravity="center_horizontal"
+        android:background="@color/crypt_keeper_password_background">
 
-        <LinearLayout
-            android:background="@color/crypt_keeper_password_background"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:orientation="horizontal">
-            <include layout="@layout/crypt_keeper_pin_field" />
-        </LinearLayout>
+        <include layout="@layout/crypt_keeper_pin_field" />
 
     </LinearLayout>
 
-    <!-- Emergency call button.
-         Text is set by CryptKeeper.updateEmergencyCallButtonState() -->
-    <Button android:id="@+id/emergencyCallButton"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_gravity="center_horizontal"
-        android:layout_marginTop="@dimen/crypt_keeper_emergency_call_space_above"
-        style="?android:attr/borderlessButtonStyle" />
+    <include layout="@layout/crypt_keeper_emergency_button" />
 
 </LinearLayout>
diff --git a/res/layout/crypt_keeper_status.xml b/res/layout/crypt_keeper_status.xml
index c366b57..bddff1a 100644
--- a/res/layout/crypt_keeper_status.xml
+++ b/res/layout/crypt_keeper_status.xml
@@ -31,11 +31,11 @@
         android:id="@+id/status"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:layout_marginTop="10dip"
         android:layout_marginStart="8dip"
         android:layout_marginEnd="8dip"
-        android:textSize="18sp"
-        android:textAppearance="?android:attr/textAppearanceLarge"
+        android:textSize="16sp"
+        android:fontFamily="sans-serif"
+        android:textColor="@android:color/white"
         android:text="@string/enter_password"
         android:layout_gravity="center_horizontal"
         android:gravity="center_horizontal" />
@@ -51,6 +51,8 @@
         android:ellipsize="marquee"
         android:marqueeRepeatLimit ="marquee_forever"
         android:textSize="16sp"
-        android:textAppearance="?android:attr/textAppearanceMedium" />
+        android:fontFamily="sans-serif"
+        android:textColor="#B3FFFFFF"
+        android:gravity="center_horizontal" />
 
 </LinearLayout>
diff --git a/res/layout/mac_preference.xml b/res/layout/mac_preference.xml
new file mode 100644
index 0000000..f096b07
--- /dev/null
+++ b/res/layout/mac_preference.xml
@@ -0,0 +1,79 @@
+<?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.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:minHeight="?android:attr/listPreferredItemHeightSmall"
+    android:gravity="center_vertical"
+    android:orientation="vertical"
+    android:background="?android:attr/selectableItemBackground">
+
+    <View
+        android:layout_width="fill_parent"
+        android:layout_height="@dimen/wifi_divider_height"
+        android:background="@color/wifi_divider" />
+
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:minHeight="?android:attr/listPreferredItemHeightSmall"
+        android:gravity="center_vertical"
+        android:background="?android:attr/selectableItemBackground">
+
+        <RelativeLayout
+            android:layout_width="0dip"
+            android:layout_height="wrap_content"
+            android:layout_weight="1"
+            android:paddingTop="6dip"
+            android:paddingBottom="6dip">
+
+            <TextView
+                android:id="@+android:id/title"
+                android:layout_width="match_parent"
+                android:layout_height="match_parent"
+                android:paddingStart="16dip"
+                android:paddingEnd="16dip"
+                android:singleLine="true"
+                android:textAppearance="?android:attr/textAppearanceSmall"
+                android:ellipsize="marquee"
+                android:fadingEdge="horizontal" />
+
+            <TextView
+                android:id="@android:id/summary"
+                android:layout_width="match_parent"
+                android:layout_height="match_parent"
+                android:layout_below="@android:id/title"
+                android:layout_alignStart="@android:id/title"
+                android:paddingStart="16dip"
+                android:layout_marginEnd="16dip"
+                android:visibility="gone"
+                android:textAppearance="?android:attr/textAppearanceSmall"
+                android:textColor="?android:attr/textColorSecondary"
+                android:maxLines="4" />
+
+        </RelativeLayout>
+
+        <LinearLayout
+            android:id="@android:id/widget_frame"
+            android:layout_width="wrap_content"
+            android:layout_height="match_parent"
+            android:gravity="center_vertical"
+            android:orientation="vertical" />
+
+    </LinearLayout>
+
+</LinearLayout>
diff --git a/res/layout/radio_info.xml b/res/layout/radio_info.xml
index 760cf80..d81dad6 100644
--- a/res/layout/radio_info.xml
+++ b/res/layout/radio_info.xml
@@ -234,14 +234,6 @@
                 android:layout_height="wrap_content"
                 />
 
-        <!-- Dial over PS (i.e. MO VoLTE) -->
-        <Button android:id="@+id/mo_over_volte"
-            android:textSize="14sp"
-            android:layout_marginTop="8dip"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            />
-
         <!-- LTE ram dump -->
         <Button android:id="@+id/lte_ram_dump"
                 android:textSize="14sp"
diff --git a/res/layout/wifi_assistant_card.xml b/res/layout/wifi_assistant_card.xml
index a1917ba..7c9af17 100644
--- a/res/layout/wifi_assistant_card.xml
+++ b/res/layout/wifi_assistant_card.xml
@@ -21,7 +21,10 @@
     android:layout_height="wrap_content"
     android:gravity="center_vertical"
     android:orientation="vertical"
-    android:padding="@dimen/wifi_assistant_padding">
+    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
+    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
+    android:paddingTop="@dimen/wifi_assistant_padding"
+    android:paddingBottom="@dimen/wifi_assistant_padding">
 
     <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="fill_parent"
@@ -29,7 +32,7 @@
 
         <ImageView
             android:id="@+id/cardBackground"
-            android:background="@color/setup_add_wifi_network_text_color"
+            android:background="@color/wifi_assistant_color_accent"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:layout_gravity="center"
diff --git a/res/values-sw600dp-land/dimens.xml b/res/values-sw600dp-land/dimens.xml
index c0a79ad..eb37d0f 100755
--- a/res/values-sw600dp-land/dimens.xml
+++ b/res/values-sw600dp-land/dimens.xml
@@ -20,4 +20,11 @@
     <dimen name="screen_margin_bottom">48dip</dimen>
     <dimen name="appwidget_preview_height">80dip</dimen>
     <dimen name="keyguard_appwidget_picker_width">720dip</dimen>
+
+    <!-- CryptKeeper top margin for password/pin screen -->
+    <dimen name="crypt_keeper_password_top_margin">116dip</dimen>
+
+    <!-- CryptKeeper top margin for pattern screen -->
+    <dimen name="crypt_keeper_pattern_top_margin">128dip</dimen>
+
 </resources>
diff --git a/res/values-sw600dp/dimens.xml b/res/values-sw600dp/dimens.xml
index e040167..e1bb33e 100755
--- a/res/values-sw600dp/dimens.xml
+++ b/res/values-sw600dp/dimens.xml
@@ -55,6 +55,18 @@
     <dimen name="dashboard_tile_image_margin_start">8dp</dimen>
     <dimen name="dashboard_tile_image_margin_end">32dp</dimen>
 
+    <!-- CryptKeeper top margin for password/pin screen -->
+    <dimen name="crypt_keeper_password_top_margin">256dip</dimen>
+
+    <!-- CryptKeeper top margin for pattern screen -->
+    <dimen name="crypt_keeper_pattern_top_margin">256dip</dimen>
+
+    <!-- CryptKeeper separation between status and pattern -->
+    <dimen name="crypt_keeper_pattern_separator">100dip</dimen>
+
+    <!-- CryptKeeper password/pin width -->
+    <dimen name="crypt_keeper_password_width">512dip</dimen>
+
     <!-- SwitchBar margin start / end -->
     <dimen name="switchbar_margin_start">24dp</dimen>
     <dimen name="switchbar_margin_end">24dp</dimen>
diff --git a/res/values/colors.xml b/res/values/colors.xml
index df61730..cba8483 100644
--- a/res/values/colors.xml
+++ b/res/values/colors.xml
@@ -40,8 +40,12 @@
     <color name="title_color">@android:color/holo_blue_light</color>
     <color name="setup_divider_color_dark">#33ffffff</color>
     <color name="setup_divider_color_light">#33000000</color>
-    <color name="setup_add_wifi_network_text_color">#ff009587</color>
-    <color name="setup_add_wifi_network_background_color">#ff009587</color>
+    <color name="setup_wizard_color_accent_dark">#ff00e4ff</color>
+    <color name="setup_wizard_color_accent_light">#ff00828e</color>
+    <color name="setup_wizard_wifi_color_dark">#ff00e4ff</color>
+    <color name="setup_wizard_wifi_color_light">#ff0096a6</color>
+
+    <color name="wifi_assistant_color_accent">#ff009587</color>
 
     <color name="circle_avatar_frame_color">#ffffffff</color>
     <color name="circle_avatar_frame_shadow_color">#80000000</color>
@@ -66,13 +70,16 @@
     <color name="theme_accent">#ff009688</color>
 
     <color name="dashboard_background_color">#ffe1e1e0</color>
-    <color name="switchbar_background_color">#ff384248</color>
+    <color name="switchbar_background_color">#ff37474f</color>
     <color name="switch_accent_color">#ff7fcac3</color>
 
     <color name="default_preference_background_color">@*android:color/background_material_light</color>
     <color name="preference_background_color">@color/default_preference_background_color</color>
     <color name="search_panel_list_background_color">@color/default_preference_background_color</color>
 
+    <color name="setup_wizard_preference_background_color_dark">@*android:color/background_material_dark</color>
+    <color name="setup_wizard_preference_background_color_light">@*android:color/background_material_light</color>
+
     <!-- Default avatar colors -->
     <color name="pink_500">#ffe91e63</color>
     <color name="indigo_500">#ff3f51b5</color>
@@ -85,4 +92,6 @@
     <!-- Avatar color used for guest -->
     <color name="grey_500">@*android:color/material_grey_500</color>
 
+    <color name="wifi_divider">#ffe0e0e0</color>
+
 </resources>
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index cb87bf0..865b029 100755
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -168,8 +168,14 @@
     <dimen name="wifi_assistant_padding">25dp</dimen>
     <dimen name="wifi_assistant_text_padding">16dp</dimen>
 
-    <!-- CryptKeeper edit text margin -->
-    <dimen name="crypt_keeper_edit_text_margin">16dip</dimen>
+    <!-- CryptKeeper top margin for password/pin screen -->
+    <dimen name="crypt_keeper_password_top_margin">88dip</dimen>
+
+    <!-- CryptKeeper top margin for pattern screen -->
+    <dimen name="crypt_keeper_pattern_top_margin">88dip</dimen>
+
+    <!-- CryptKeeper password/pin width -->
+    <dimen name="crypt_keeper_password_width">280dip</dimen>
 
     <!-- CryptKeeper emergency call button dimensions -->
     <dimen name="crypt_keeper_emergency_call_space_above">16dip</dimen>
@@ -177,6 +183,9 @@
     <!-- CryptKeeper edit text ime icon padding -->
     <dimen name="crypt_keeper_edit_text_ime_padding">8dip</dimen>
 
+    <!-- CryptKeeper pattern margin on phone -->
+    <dimen name="crypt_keeper_pattern_margin">8dip</dimen>
+
     <!-- CryptKeeper pattern size for tablet -->
     <dimen name="crypt_keeper_pattern_size">354dip</dimen>
 
@@ -208,4 +217,6 @@
     <dimen name="bluetooth_dialog_padding">8dip</dimen>
     <integer name="bluetooth_name_length">32</integer>
 
+    <dimen name="wifi_divider_height">1px</dimen>
+
 </resources>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index d2a2f5d..554ffea 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -67,11 +67,6 @@
     <!-- Phone SMS over IMS off. Only shown in diagnostic screen, so precise translation is not needed. -->
     <string name="sms_over_ims_off">Turn off SMS over IMS</string>
 
-    <!-- MO over PS/VoLTE. Only shown in diagnostic screen, so precise translation is not needed. -->
-    <string name="mo_over_volte_on">Enable MO over PS/VoLTE</string>
-    <!-- MO over PS/VoLTE. Only shown in diagnostic screen, so precise translation is not needed. -->
-    <string name="mo_over_volte_off">Disable MO over PS/VoLTE</string>
-
     <!-- Phone SMS over IMS IMS registration required on. Only shown in diagnostic screen, so precise translation is not needed. -->
     <string name="ims_reg_required_on">Turn on IMS registration required</string>
     <!-- Phone IMS registration required off. Only shown in diagnostic screen, so precise translation is not needed. -->
@@ -275,7 +270,7 @@
     <string name="bluetooth_empty_list_user_restricted">You don\'t have permission to change Bluetooth settings.</string>
 
     <!-- Bluetooth Visibility message.  This message informs the user that their device is now visible to other bluetooth devices.  [CHAR LIMIT=50] -->
-    <string name="bluetooth_is_visible_message"><xliff:g id="device_name">%1$s</xliff:g> is now visible to nearby devices.</string>
+    <string name="bluetooth_is_visible_message"><xliff:g id="device_name">%1$s</xliff:g> is visible to nearby devices while Bluetooth Settings is open.</string>
     <!-- Bluetooth Visibility discoonect question.  Asks the user if they wish to disconnect a paired bluetooth device.  [CHAR LIMIT=50] -->
     <string name="bluetooth_is_disconnect_question">Disconnect <xliff:g id="device_name">%1$s</xliff:g>?</string>
     <!-- Bluetooth broadcasting settings, option to enable/disable broadcasting -->
@@ -319,8 +314,6 @@
     <string name="bluetooth_notif_message">Touch to pair with <xliff:g id="device_name">%1$s</xliff:g>.</string>
     <!-- Bluetooth settings screen, menu to show the list of received files [CHAR LIMIT=30] -->
     <string name="bluetooth_show_received_files">Show received files</string>
-    <!-- Bluetooth settings screen, menu to show the list of email accounts to pull messages from [CHAR LIMIT=30] -->
-    <string name="bluetooth_show_message_access">Message access</string>
 
     <!-- Strings for BluetoothDevicePicker -->
     <string name="device_picker">Bluetooth device chooser</string>
@@ -331,8 +324,6 @@
     <!-- Strings for asking to the user whether to allow an app to enable bluetooth -->
     <string name="bluetooth_ask_enablement">An app wants to turn on Bluetooth.</string>
 
-    <!-- String for informing the user that bluetooth devices must be granted permission. [CHAR LIMIT=100] -->
-    <string name="bluetooth_message_access_notice">Bluetooth devices must ask for permission before accessing available accounts.</string>
     <!-- Strings for asking to the user whether to allow an app to enable discovery mode -->
     <string name="bluetooth_ask_discovery" product="tablet">An app wants to make your tablet visible to other Bluetooth devices for <xliff:g id="timeout">%1$d</xliff:g> seconds.</string>
     <!-- Strings for asking to the user whether to allow an app to enable discovery mode -->
@@ -897,6 +888,27 @@
       to restore any data that was backed up to your Google Account.
     </string>
 
+    <!-- Title of the encryption screen when decrypting the device failed -->
+    <string name="crypt_keeper_data_corrupt_title">Decryption unsuccessful</string>
+
+    <!-- Informational text when encryption fails -->
+    <string name="crypt_keeper_data_corrupt_summary" product="tablet">
+      The password you entered is correct, but unfortunately your data is
+      corrupt.
+      \n\nTo resume using your tablet, you need to perform a factory reset.
+      When you set up your tablet after the reset, you\'ll have an opportunity
+      to restore any data that was backed up to your Google Account.
+    </string>
+
+    <!-- Informational text when encryption fails -->
+    <string name="crypt_keeper_data_corrupt_summary" product="default">
+      The password you entered is correct, but unfortunately your data is
+      corrupt.
+      \n\nTo resume using your phone, you need to perform a factory reset.
+      When you set up your phone after the reset, you\'ll have an opportunity
+      to restore any data that was backed up to your Google Account.
+    </string>
+
     <!-- Image button description to switch input method -->
     <string name="crypt_keeper_switch_input_method">Switch input method</string>
 
@@ -1191,8 +1203,6 @@
     <string name="bluetooth_pairing_dialog_paring_request"><xliff:g id="device_name">%1$s</xliff:g> wants to pair with Bluetooth. When connected, it will have access to your contacts and call history.</string>
     <!-- Bluetooth settings: The sub heading for devices which have already been paired with this device. [CHAR LIMIT=40] -->
     <string name="bluetooth_preference_paired_devices">Paired devices</string>
-    <!-- Bluetooth settings: The sub heading for messaging accesses. [CHAR LIMIT=50] -->
-    <string name="bluetooth_message_access">Paired devices can view messages from</string>
     <!-- Bluetooth settings: The sub heading for available devices during and after scanning. [CHAR LIMIT=40] -->
     <string name="bluetooth_preference_found_devices">Available devices</string>
     <!-- Bluetooth settings: The message displayed if no Bluetooth devices were found. [CHAR LIMIT=40] -->
@@ -1470,7 +1480,7 @@
     <!-- Checkbox title for option to Automatically manage Wi\u2011Fi  [CHAR LIMIT=40] -->
     <string name="wifi_automatically_manage_title">Automatically manage Wi\u2011Fi</string>
     <!-- Checkbox summary for option to Automatically manage Wi\u2011Fi  [CHAR LIMIT=100] -->
-    <string name="wifi_automatically_manage_summary">Let a Wi\u2011Fi assistant manage your Wi\u2011Fi connection</string>
+    <string name="wifi_automatically_manage_summary">Let <xliff:g id="wifi_assistant">%1$s</xliff:g> manage your Wi\u2011Fi connection</string>
     <!-- Checkbox title for option for Wi\u2011Fi Assistant  [CHAR LIMIT=40] -->
     <string name="wifi_assistant_setting_title">Wi\u2011Fi assistant</string>
     <!-- Checkbox summary for option for Wi\u2011Fi Assistant  [CHAR LIMIT=40] -->
@@ -4392,7 +4402,7 @@
     <string name="select_device_admin_msg">Device administrators</string>
     <!-- Message when there are no available device admins to display -->
     <string name="no_device_admins">No available device administrators</string>
-    <!-- Message displayed when the device admin can only be disabled by deleting the managed profile [CHAR_LIMIT=80] -->
+    <!-- Message displayed when the device admin can only be disabled by deleting the managed profile [CHAR_LIMIT=120] -->
     <string name="managed_profile_device_admin_info">To stop <xliff:g id="app_name">%1$s</xliff:g> from accessing your work profile, remove the profile under Settings &gt; Accounts.</string>
     <!-- Title for personal device admins on the list [CHAR_LIMIT=25] -->
     <string name="personal_device_admin_title">Personal</string>
@@ -4557,6 +4567,10 @@
     <string name="sync_is_failing">Sync is currently experiencing problems. It will be back shortly.</string>
     <!-- Button label to add an account [CHAR LIMIT=20] -->
     <string name="add_account_label">Add account</string>
+    <!-- Label for the state of the managed profile [CHAR LIMIT=80] -->
+    <string name="managed_profile_not_available_label">Work profile is not available yet</string>
+    <!-- Button label to remove the work profile [CHAR LIMIT=35] -->
+    <string name="remove_managed_profile_label">Remove work profile</string>
     <!-- Data synchronization settings screen, title of setting that controls whether background data should be used [CHAR LIMIT=30] -->
     <string name="background_data">Background data</string>
     <!-- Data synchronization settings screen, summary of setting that controls whether background data should be used [CHAR LIMIT=60] -->
@@ -5158,8 +5172,6 @@
     <string name="user_summary_restricted_profile">Restricted profile</string>
     <!-- User settings summary for a managed profile [CHAR LIMIT=50] -->
     <string name="user_summary_managed_profile">Managed profile</string>
-    <!-- User settings summary for an inactive managed profile [CHAR LIMIT=50] -->
-    <string name="user_summary_managed_profile_not_enabled">Managed profile (currently inactive)</string>
     <!-- User settings warning that restricted profile needs a screen lock [CHAR LIMIT=NONE] -->
     <string name="user_need_lock_message">Before you can create a restricted profile, you\'ll need to set up a screen lock to protect your apps and personal data.</string>
     <!-- User settings dialog button to set screen lock [CHAR LIMIT=25] -->
diff --git a/res/values/styles.xml b/res/values/styles.xml
index 566748a..1b08e0f 100644
--- a/res/values/styles.xml
+++ b/res/values/styles.xml
@@ -192,7 +192,7 @@
         <item name="android:paddingStart">@dimen/setup_list_no_icon_padding</item>
         <item name="android:textAllCaps">true</item>
         <item name="android:textAppearance">@android:style/TextAppearance.Small</item>
-        <item name="android:textColor">@color/setup_add_wifi_network_text_color</item>
+        <item name="android:textColor">?android:attr/colorAccent</item>
     </style>
 
     <style name="wifi_item">
@@ -290,7 +290,7 @@
 
     <style name="WifiAssistantButton">
         <item name="android:textAppearance">?android:attr/textAppearanceMedium</item>
-        <item name="android:textColor">@color/setup_add_wifi_network_text_color</item>
+        <item name="android:textColor">@color/wifi_assistant_color_accent</item>
     </style>
 
     <!-- Scrollbar style OUTSIDE_OVERLAY -->
diff --git a/res/values/themes.xml b/res/values/themes.xml
index ed74308..aa46341 100644
--- a/res/values/themes.xml
+++ b/res/values/themes.xml
@@ -19,10 +19,12 @@
     <attr name="ic_menu_moreoverflow" format="reference" />
     <attr name="ic_wps" format="reference" />
     <attr name="setup_divider_color" format="reference" />
+    <attr name="wifi_signal_color" format="reference" />
     <attr name="wifi_signal" format="reference" />
 
     <style name="SetupWizardWifiTheme" parent="android:Theme.Material.NoActionBar">
         <item name="android:alertDialogTheme">@style/Theme.WifiDialog</item>
+        <item name="android:colorAccent">@color/setup_wizard_color_accent_dark</item>
         <item name="android:listPreferredItemPaddingEnd">@dimen/setup_wizard_margin_sides</item>
         <item name="android:listPreferredItemPaddingStart">@dimen/setup_wizard_margin_sides</item>
         <item name="android:windowBackground">?android:attr/colorBackground</item>
@@ -32,12 +34,14 @@
         <item name="ic_menu_moreoverflow">@*android:drawable/ic_menu_moreoverflow_material</item>
         <item name="ic_wps">@drawable/ic_wps_dark</item>
         <item name="setup_divider_color">@color/setup_divider_color_dark</item>
-        <item name="wifi_signal">@drawable/wifi_signal_dark</item>
-        <item name="preferenceBackgroundColor">@drawable/preference_background</item>
+        <item name="wifi_signal_color">@color/setup_wizard_wifi_color_dark</item>
+        <item name="wifi_signal">@drawable/wifi_signal_colored</item>
+        <item name="preferenceBackgroundColor">@color/setup_wizard_preference_background_color_dark</item>
     </style>
 
     <style name="SetupWizardWifiTheme.Light" parent="android:Theme.Material.Light.NoActionBar">
         <item name="android:alertDialogTheme">@style/Theme.Light.WifiDialog</item>
+        <item name="android:colorAccent">@color/setup_wizard_color_accent_light</item>
         <item name="android:listPreferredItemPaddingEnd">@dimen/setup_wizard_margin_sides</item>
         <item name="android:listPreferredItemPaddingStart">@dimen/setup_wizard_margin_sides</item>
         <item name="android:windowBackground">?android:attr/colorBackground</item>
@@ -47,8 +51,9 @@
         <item name="ic_menu_moreoverflow">@*android:drawable/ic_menu_moreoverflow_material</item>
         <item name="ic_wps">@drawable/ic_wps_light</item>
         <item name="setup_divider_color">@color/setup_divider_color_light</item>
-        <item name="wifi_signal">@drawable/wifi_signal_light</item>
-        <item name="preferenceBackgroundColor">@drawable/preference_background</item>
+        <item name="wifi_signal_color">@color/setup_wizard_wifi_color_light</item>
+        <item name="wifi_signal">@drawable/wifi_signal_colored</item>
+        <item name="preferenceBackgroundColor">@color/setup_wizard_preference_background_color_light</item>
     </style>
 
     <style name="Theme.WifiDialog" parent="@*android:style/Theme.Material.Dialog.Alert">
diff --git a/res/xml/account_settings.xml b/res/xml/account_settings.xml
index 7437b80..33f61a2 100644
--- a/res/xml/account_settings.xml
+++ b/res/xml/account_settings.xml
@@ -19,35 +19,4 @@
         android:key="account"
         android:title="@string/account_settings_title"
         settings:keywords="@string/keywords_accounts">
-
-        <Preference
-            android:key="add_account"
-            android:title="@string/add_account_label"
-            android:icon="@drawable/ic_menu_add_dark"
-            android:order="2147483648" />
-
-        <PreferenceCategory
-            android:key="account_personal"
-            android:title="@string/category_personal" >
-
-                <Preference
-                    android:key="add_account_personal"
-                    android:title="@string/add_account_label"
-                    android:icon="@drawable/ic_menu_add_dark"
-                    android:order="2147483648" />
-
-        </PreferenceCategory>
-
-        <PreferenceCategory
-            android:key="account_work"
-            android:title="@string/category_work" >
-
-                <Preference
-                    android:key="add_account_work"
-                    android:title="@string/add_account_label"
-                    android:icon="@drawable/ic_menu_add_dark"
-                    android:order="2147483648" />
-
-        </PreferenceCategory>
-
 </PreferenceScreen>
diff --git a/res/xml/bluetooth_message_access.xml b/res/xml/bluetooth_message_access.xml
deleted file mode 100644
index d1da132..0000000
--- a/res/xml/bluetooth_message_access.xml
+++ /dev/null
@@ -1,31 +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.
--->
-<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
-        android:title="@string/bluetooth_show_message_access">
-
-    <PreferenceCategory
-            android:key="accounts"
-            android:title="@string/bluetooth_message_access" />
-
-    <Preference
-            android:key="notice"
-            android:title=""
-            android:textAppearance="?android:attr/textAppearanceSmall"
-            android:textColor="?android:attr/colorForegroundInverse"
-            android:selectable="false"
-            android:summary="@string/bluetooth_message_access_notice" />
-
-</PreferenceScreen>
diff --git a/res/xml/language_settings.xml b/res/xml/language_settings.xml
index 9d12857..b60dc5e 100644
--- a/res/xml/language_settings.xml
+++ b/res/xml/language_settings.xml
@@ -65,34 +65,6 @@
             android:persistent="false">
         <!-- Additional preference screens are inserted here programmatically
              with low order values to set the key map of each attached keyboard. -->
-
-        <CheckBoxPreference
-                android:key="auto_replace"
-                android:title="@string/auto_replace"
-                android:summaryOn="@string/auto_replace_summary"
-                android:summaryOff="@string/auto_replace_summary"
-                android:order="1000"
-                android:persistent="false"
-                />
-
-        <CheckBoxPreference
-                android:key="auto_caps"
-                android:title="@string/auto_caps"
-                android:summaryOn="@string/auto_caps_summary"
-                android:summaryOff="@string/auto_caps_summary"
-                android:order="1001"
-                android:persistent="false"
-                />
-
-        <CheckBoxPreference
-                android:key="auto_punctuate"
-                android:title="@string/auto_punctuate"
-                android:summaryOn="@string/auto_punctuate_summary"
-                android:summaryOff="@string/auto_punctuate_summary"
-                android:order="1002"
-                android:persistent="false"
-                />
-
     </PreferenceCategory>
 
     <PreferenceCategory
diff --git a/res/xml/security_settings_biometric_weak.xml b/res/xml/security_settings_biometric_weak.xml
index 750a270..4879fe6 100644
--- a/res/xml/security_settings_biometric_weak.xml
+++ b/res/xml/security_settings_biometric_weak.xml
@@ -31,12 +31,12 @@
             android:key="biometric_weak_improve_matching"
             android:title="@string/biometric_weak_improve_matching_title"/>
 
-        <CheckBoxPreference
+        <SwitchPreference
            android:key="biometric_weak_liveliness"
            android:title="@string/biometric_weak_liveliness_title"
            android:summary="@string/biometric_weak_liveliness_summary"/>
 
-        <CheckBoxPreference
+        <SwitchPreference
             android:key="visiblepattern"
             android:title="@string/lockpattern_settings_enable_visible_pattern_title"/>
 
@@ -48,7 +48,7 @@
             android:entryValues="@array/lock_after_timeout_values"
             android:persistent="false"/>
 
-        <CheckBoxPreference
+        <SwitchPreference
             android:key="power_button_instantly_locks"
             android:title="@string/lockpattern_settings_enable_power_button_instantly_locks"/>
 
diff --git a/res/xml/security_settings_misc.xml b/res/xml/security_settings_misc.xml
index 7219a6c..1f280a9 100644
--- a/res/xml/security_settings_misc.xml
+++ b/res/xml/security_settings_misc.xml
@@ -36,7 +36,7 @@
     <PreferenceCategory android:title="@string/security_passwords_title"
             android:persistent="false">
 
-        <CheckBoxPreference android:key="show_password"
+        <SwitchPreference android:key="show_password"
                 android:title="@string/show_password"
                 android:persistent="false"/>
 
@@ -52,7 +52,7 @@
                 android:persistent="false"
                 android:fragment="com.android.settings.DeviceAdminSettings"/>
 
-        <CheckBoxPreference android:key="toggle_install_applications"
+        <SwitchPreference android:key="toggle_install_applications"
                 android:title="@string/install_applications"
                 android:summaryOff="@string/install_unknown_applications"
                 android:summaryOn="@string/install_unknown_applications"
@@ -107,7 +107,7 @@
                 android:title="@string/manage_trust_agents"
                 android:summary="@string/manage_trust_agents_summary"
                 android:persistent="false"
-                android:fragment="com.android.settings.AdvancedSecuritySettings"/>
+                android:fragment="com.android.settings.TrustAgentSettings"/>
 
         <PreferenceScreen
                 android:key="screen_pinning_settings"
diff --git a/res/xml/security_settings_password.xml b/res/xml/security_settings_password.xml
index bb9c360..b6ea76e 100644
--- a/res/xml/security_settings_password.xml
+++ b/res/xml/security_settings_password.xml
@@ -35,7 +35,7 @@
             android:entryValues="@array/lock_after_timeout_values"
             android:persistent="false"/>
 
-        <CheckBoxPreference
+        <SwitchPreference
             android:key="power_button_instantly_locks"
             android:title="@string/lockpattern_settings_enable_power_button_instantly_locks"/>
 
diff --git a/res/xml/security_settings_pattern.xml b/res/xml/security_settings_pattern.xml
index 168a685..cb848c6 100644
--- a/res/xml/security_settings_pattern.xml
+++ b/res/xml/security_settings_pattern.xml
@@ -27,7 +27,7 @@
             android:summary="@string/unlock_set_unlock_mode_pattern"
             android:persistent="false"/>
 
-        <CheckBoxPreference
+        <SwitchPreference
             android:key="visiblepattern"
             android:title="@string/lockpattern_settings_enable_visible_pattern_title"/>
 
@@ -39,7 +39,7 @@
             android:entryValues="@array/lock_after_timeout_values"
             android:persistent="false"/>
 
-        <CheckBoxPreference
+        <SwitchPreference
             android:key="power_button_instantly_locks"
             android:title="@string/lockpattern_settings_enable_power_button_instantly_locks"/>
 
diff --git a/res/xml/security_settings_pin.xml b/res/xml/security_settings_pin.xml
index 4ead03f..e45bdf5 100644
--- a/res/xml/security_settings_pin.xml
+++ b/res/xml/security_settings_pin.xml
@@ -35,7 +35,7 @@
             android:entryValues="@array/lock_after_timeout_values"
             android:persistent="false"/>
 
-        <CheckBoxPreference
+        <SwitchPreference
             android:key="power_button_instantly_locks"
             android:title="@string/lockpattern_settings_enable_power_button_instantly_locks"/>
 
diff --git a/res/xml/trust_agent_settings.xml b/res/xml/trust_agent_settings.xml
new file mode 100644
index 0000000..e9374f3
--- /dev/null
+++ b/res/xml/trust_agent_settings.xml
@@ -0,0 +1,19 @@
+<?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.
+-->
+
+<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
+    android:key="trust_agents"
+    android:title="@string/manage_trust_agents" />
diff --git a/res/xml/wifi_advanced_settings.xml b/res/xml/wifi_advanced_settings.xml
index 118f691..f83a106 100644
--- a/res/xml/wifi_advanced_settings.xml
+++ b/res/xml/wifi_advanced_settings.xml
@@ -18,31 +18,30 @@
         android:title="@string/wifi_advanced_titlebar">
 
     <!-- android:dependency="enable_wifi" -->
-    <CheckBoxPreference
+    <SwitchPreference
             android:key="notify_open_networks"
             android:title="@string/wifi_notify_open_networks"
             android:summary="@string/wifi_notify_open_networks_summary"
             android:persistent="false" />
 
+    <SwitchPreference
+            android:key="wifi_scan_always_available"
+            android:title="@string/wifi_scan_always_available"
+            android:summary="@string/wifi_scan_always_available_summary"
+            android:persistent="false" />
+
+    <SwitchPreference
+            android:key="wifi_assistant"
+            android:title="@string/wifi_automatically_manage_title"
+            android:summary="@string/wifi_assistant_setting_summary"
+            android:persistent="false" />
+
     <ListPreference
             android:key="sleep_policy"
             android:title="@string/wifi_setting_sleep_policy_title"
             android:persistent="false"
             android:entries="@array/wifi_sleep_policy_entries"
-            android:entryValues="@array/wifi_sleep_policy_values"
-            />
-    <CheckBoxPreference
-            android:key="wifi_scan_always_available"
-            android:title="@string/wifi_scan_always_available"
-            android:summary="@string/wifi_scan_always_available_summary"
-            android:persistent="false" />
-
-    <!-- android:dependency="enable_wifi" -->
-    <CheckBoxPreference
-            android:key="wifi_poor_network_detection"
-            android:title="@string/wifi_poor_network_detection"
-            android:summary="@string/wifi_poor_network_detection_summary"
-            android:persistent="false" />
+            android:entryValues="@array/wifi_sleep_policy_values" />
 
     <ListPreference
             android:key="frequency_band"
@@ -50,8 +49,7 @@
             android:summary="@string/wifi_setting_frequency_band_summary"
             android:persistent="false"
             android:entries="@array/wifi_frequency_band_entries"
-            android:entryValues="@array/wifi_frequency_band_values"
-            />
+            android:entryValues="@array/wifi_frequency_band_values" />
 
     <Preference
             android:key="install_credentials"
@@ -73,16 +71,10 @@
             android:title="@string/wifi_menu_wps_pin"
             android:persistent="false" />
 
-    <CheckBoxPreference
-            android:key="suspend_optimizations"
-            android:title="@string/wifi_suspend_optimizations"
-            android:summary="@string/wifi_suspend_optimizations_summary"
-            android:persistent="false" />
-
     <Preference
             android:key="mac_address"
             android:title="@string/wifi_advanced_mac_address_title"
-            android:layout="@layout/wifi_advance_layout" />
+            android:layout="@layout/mac_preference" />
 
     <Preference
             android:key="current_ip_address"
diff --git a/src/com/android/settings/AdvancedSecuritySettings.java b/src/com/android/settings/AdvancedSecuritySettings.java
deleted file mode 100644
index 3ddbf96..0000000
--- a/src/com/android/settings/AdvancedSecuritySettings.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * 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
- */
-
-package com.android.settings;
-
-import com.android.internal.widget.LockPatternUtils;
-
-import android.app.ListFragment;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.os.Bundle;
-import android.service.trust.TrustAgentService;
-import android.util.ArrayMap;
-import android.util.ArraySet;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.BaseAdapter;
-import android.widget.CheckBox;
-import android.widget.TextView;
-
-import java.util.List;
-
-public class AdvancedSecuritySettings extends ListFragment implements View.OnClickListener {
-    static final String TAG = "AdvancedSecuritySettings";
-
-    private static final String SERVICE_INTERFACE = TrustAgentService.SERVICE_INTERFACE;
-
-    private final ArraySet<ComponentName> mActiveAgents = new ArraySet<ComponentName>();
-    private final ArrayMap<ComponentName, AgentInfo> mAvailableAgents
-            = new ArrayMap<ComponentName, AgentInfo>();
-
-    private LockPatternUtils mLockPatternUtils;
-
-    public static final class AgentInfo {
-        CharSequence label;
-        ComponentName component; // service that implements ITrustAgent
-
-        @Override
-        public boolean equals(Object other) {
-            if (other instanceof AgentInfo) {
-                return component.equals(((AgentInfo)other).component);
-            }
-            return true;
-        }
-
-        public int compareTo(AgentInfo other) {
-            return component.compareTo(other.component);
-        }
-    }
-
-    @Override
-    public void onCreate(Bundle icicle) {
-        super.onCreate(icicle);
-    }
-
-    @Override
-    public View onCreateView(LayoutInflater inflater, ViewGroup container,
-            Bundle savedInstanceState) {
-	if (mLockPatternUtils == null) {
-            mLockPatternUtils = new LockPatternUtils(
-                    container.getContext().getApplicationContext());
-        }
-        setListAdapter(new AgentListAdapter());
-        return inflater.inflate(R.layout.advanced_security_settings, container, false);
-    }
-
-    @Override
-    public void onResume() {
-        super.onResume();
-        updateList();
-    }
-
-    void updateList() {
-        Context context = getActivity();
-        if (context == null) {
-            return;
-        }
-
-        loadActiveAgents();
-
-        PackageManager pm = getActivity().getPackageManager();
-        Intent trustAgentIntent = new Intent(SERVICE_INTERFACE);
-        List<ResolveInfo> resolveInfos = pm.queryIntentServices(trustAgentIntent,
-                PackageManager.GET_META_DATA);
-
-        mAvailableAgents.clear();
-        mAvailableAgents.ensureCapacity(resolveInfos.size());
-
-        for (ResolveInfo resolveInfo : resolveInfos) {
-            if (resolveInfo.serviceInfo == null) continue;
-            if (!TrustAgentUtils.checkProvidePermission(resolveInfo, pm)) continue;
-            ComponentName name = TrustAgentUtils.getComponentName(resolveInfo);
-            if (!mAvailableAgents.containsKey(name)) {
-                AgentInfo agentInfo = new AgentInfo();
-                agentInfo.label = resolveInfo.loadLabel(pm);
-                agentInfo.component = name;
-                mAvailableAgents.put(name, agentInfo);
-            }
-        }
-        ((BaseAdapter) getListAdapter()).notifyDataSetChanged();
-    }
-
-    @Override
-    public void onClick(View view) {
-        ViewHolder h = (ViewHolder) view.getTag();
-
-        if (view.getId() == R.id.clickable) {
-            boolean wasActive = mActiveAgents.contains(h.agentInfo.component);
-            loadActiveAgents();
-            if (!wasActive) {
-                mActiveAgents.add(h.agentInfo.component);
-            } else {
-                mActiveAgents.remove(h.agentInfo.component);
-            }
-            saveActiveAgents();
-            ((BaseAdapter) getListAdapter()).notifyDataSetChanged();
-        }
-    }
-
-    private void loadActiveAgents() {
-        mActiveAgents.clear();
-        List<ComponentName> activeTrustAgents = mLockPatternUtils.getEnabledTrustAgents();
-        if (activeTrustAgents != null) {
-            mActiveAgents.addAll(activeTrustAgents);
-        }
-    }
-
-    private void saveActiveAgents() {
-        mLockPatternUtils.setEnabledTrustAgents(mActiveAgents);
-    }
-
-    static class ViewHolder {
-        TextView name;
-        CheckBox checkbox;
-        TextView description;
-        AgentInfo agentInfo;
-        View clickable;
-    }
-
-    class AgentListAdapter extends BaseAdapter {
-        final LayoutInflater mInflater;
-
-        AgentListAdapter() {
-            mInflater = (LayoutInflater)
-                    getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-        }
-
-        public boolean hasStableIds() {
-            return false;
-        }
-
-        public int getCount() {
-            return mAvailableAgents.size();
-        }
-
-        public Object getItem(int position) {
-            return mAvailableAgents.valueAt(position);
-        }
-
-        public long getItemId(int position) {
-            return position;
-        }
-
-        public boolean areAllItemsEnabled() {
-            return false;
-        }
-
-        public boolean isEnabled(int position) {
-            return true;
-        }
-
-        public View getView(int position, View convertView, ViewGroup parent) {
-            View v;
-            if (convertView == null) {
-                v = newView(parent);
-            } else {
-                v = convertView;
-            }
-            bindView(v, position);
-            return v;
-        }
-
-        public View newView(ViewGroup parent) {
-            View v = mInflater.inflate(R.layout.trust_agent_item, parent, false);
-            ViewHolder h = new ViewHolder();
-            h.name = (TextView)v.findViewById(R.id.name);
-            h.checkbox = (CheckBox)v.findViewById(R.id.checkbox);
-            h.clickable = v.findViewById(R.id.clickable);
-            h.clickable.setOnClickListener(AdvancedSecuritySettings.this);
-            h.description = (TextView)v.findViewById(R.id.description);
-            v.setTag(h);
-            h.clickable.setTag(h);
-            return v;
-        }
-
-        public void bindView(View view, int position) {
-            ViewHolder vh = (ViewHolder) view.getTag();
-            AgentInfo item = mAvailableAgents.valueAt(position);
-            vh.name.setText(item.label);
-            vh.checkbox.setChecked(mActiveAgents.contains(item.component));
-            vh.agentInfo = item;
-        }
-    }
-}
diff --git a/src/com/android/settings/AirplaneModeVoiceActivity.java b/src/com/android/settings/AirplaneModeVoiceActivity.java
new file mode 100644
index 0000000..3ab0c37
--- /dev/null
+++ b/src/com/android/settings/AirplaneModeVoiceActivity.java
@@ -0,0 +1,40 @@
+/*
+ * 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.
+ */
+
+package com.android.settings;
+
+import android.content.Intent;
+import android.provider.Settings;
+import android.util.Log;
+
+/**
+ * Activity for modifying the {@link Settings.Global#AIRPLANE_MODE_ON AIRPLANE_MODE_ON}
+ * setting using the Voice Interaction API.
+ */
+public class AirplaneModeVoiceActivity extends VoiceSettingsActivity {
+    private static final String TAG = "AirplaneModeVoiceActivity";
+
+    protected void onVoiceSettingInteraction(Intent intent) {
+        if (intent.hasExtra(Settings.EXTRA_AIRPLANE_MODE_ENABLED)) {
+            boolean enabled =
+                    intent.getBooleanExtra(Settings.EXTRA_AIRPLANE_MODE_ENABLED, false);
+            Settings.Global.putInt(getContentResolver(),
+                    Settings.Global.AIRPLANE_MODE_ON, enabled ? 1 : 0);
+        } else {
+            Log.v(TAG, "Missing airplane mode extra");
+        }
+    }
+}
diff --git a/src/com/android/settings/CryptKeeper.java b/src/com/android/settings/CryptKeeper.java
index 129b201..c2295e6 100644
--- a/src/com/android/settings/CryptKeeper.java
+++ b/src/com/android/settings/CryptKeeper.java
@@ -170,6 +170,11 @@
             } else if (failedAttempts == MAX_FAILED_ATTEMPTS) {
                 // Factory reset the device.
                 sendBroadcast(new Intent("android.intent.action.MASTER_CLEAR"));
+            } else if (failedAttempts == -1) {
+                // Right password, but decryption failed. Tell user bad news ...
+                setContentView(R.layout.crypt_keeper_progress);
+                showFactoryReset(true);
+                return;
             } else {
                 // Wrong entry. Handle pattern case.
                 if (mLockPatternView != null) {
@@ -392,7 +397,7 @@
     private void setupUi() {
         if (mEncryptionGoneBad || isDebugView(FORCE_VIEW_ERROR)) {
             setContentView(R.layout.crypt_keeper_progress);
-            showFactoryReset();
+            showFactoryReset(false);
             return;
         }
 
@@ -508,7 +513,13 @@
         updateProgress();
     }
 
-    private void showFactoryReset() {
+    /**
+     * Show factory reset screen allowing the user to reset their phone when
+     * there is nothing else we can do
+     * @param corrupt true if userdata is corrupt, false if encryption failed
+     *        partway through
+     */
+    private void showFactoryReset(boolean corrupt) {
         // Hide the encryption-bot to make room for the "factory reset" button
         findViewById(R.id.encroid).setVisibility(View.GONE);
 
@@ -524,8 +535,13 @@
         });
 
         // Alert the user of the failure.
-        ((TextView) findViewById(R.id.title)).setText(R.string.crypt_keeper_failed_title);
-        ((TextView) findViewById(R.id.status)).setText(R.string.crypt_keeper_failed_summary);
+        if (corrupt) {
+            ((TextView) findViewById(R.id.title)).setText(R.string.crypt_keeper_data_corrupt_title);
+            ((TextView) findViewById(R.id.status)).setText(R.string.crypt_keeper_data_corrupt_summary);
+        } else {
+            ((TextView) findViewById(R.id.title)).setText(R.string.crypt_keeper_failed_title);
+            ((TextView) findViewById(R.id.status)).setText(R.string.crypt_keeper_failed_summary);
+        }
 
         final View view = findViewById(R.id.bottom_divider);
         // TODO(viki): Why would the bottom divider be missing in certain layouts? Investigate.
@@ -538,7 +554,7 @@
         final String state = SystemProperties.get("vold.encrypt_progress");
 
         if ("error_partially_encrypted".equals(state)) {
-            showFactoryReset();
+            showFactoryReset(false);
             return;
         }
 
diff --git a/src/com/android/settings/RadioInfo.java b/src/com/android/settings/RadioInfo.java
index 75de222..b0a4a53 100644
--- a/src/com/android/settings/RadioInfo.java
+++ b/src/com/android/settings/RadioInfo.java
@@ -303,9 +303,6 @@
         imsRegRequiredButton = (Button) findViewById(R.id.ims_reg_required);
         imsRegRequiredButton.setOnClickListener(mImsRegRequiredHandler);
 
-        moOverVolteButton = (Button) findViewById(R.id.mo_over_volte);
-        moOverVolteButton.setOnClickListener(mMoOverVolteHandler);
-
         smsOverImsButton = (Button) findViewById(R.id.sms_over_ims);
         smsOverImsButton.setOnClickListener(mSmsOverImsHandler);
 
@@ -363,7 +360,6 @@
         updatePowerState();
         updateCellInfoListRate();
         updateImsRegRequiredState();
-        updateMoOverImsState();
         updateSmsOverImsState();
         updateLteRamDumpState();
         updateProperties();
@@ -989,35 +985,6 @@
         imsRegRequiredButton.setText(buttonText);
     }
 
-    private Button moOverVolteButton;
-    OnClickListener mMoOverVolteHandler = new OnClickListener() {
-        @Override
-        public void onClick(View v) {
-            boolean moOverVolteEnabled = isMoOverVolteEnabled();
-            log(String.format("toggle %s: currently %s",
-                    TelephonyProperties.PROPERTY_DBG_IMS_VOLTE_ENABLE,
-                    (moOverVolteEnabled ? "on" : "off")));
-            boolean newValue = !moOverVolteEnabled;
-            SystemProperties.set(TelephonyProperties.PROPERTY_DBG_IMS_VOLTE_ENABLE,
-                    newValue ? "1" : "0");
-            updateMoOverImsState();
-        }
-    };
-
-    private boolean isMoOverVolteEnabled() {
-        return SystemProperties.getInt(TelephonyProperties.PROPERTY_DBG_IMS_VOLTE_ENABLE,
-                TelephonyProperties.PROPERTY_DBG_IMS_VOLTE_ENABLE_DEAFULT) == 1;
-    }
-
-    private void updateMoOverImsState() {
-        boolean moOverVolteEnabled = isMoOverVolteEnabled();
-        log("updateMoOverImsState isMoOverVolteEnabled()=" + moOverVolteEnabled);
-        String buttonText = moOverVolteEnabled ?
-                getString(R.string.mo_over_volte_off) :
-                getString(R.string.mo_over_volte_on);
-        moOverVolteButton.setText(buttonText);
-    }
-
     private Button smsOverImsButton;
     static final String PROPERTY_SMS_OVER_IMS = "persist.radio.imsallowmtsms";
     OnClickListener mSmsOverImsHandler = new OnClickListener() {
diff --git a/src/com/android/settings/SecuritySettings.java b/src/com/android/settings/SecuritySettings.java
index 1fb5e13..1b9f44c 100644
--- a/src/com/android/settings/SecuritySettings.java
+++ b/src/com/android/settings/SecuritySettings.java
@@ -31,7 +31,7 @@
 import android.os.Bundle;
 import android.os.UserHandle;
 import android.os.UserManager;
-import android.preference.CheckBoxPreference;
+import android.preference.SwitchPreference;
 import android.preference.ListPreference;
 import android.preference.Preference;
 import android.preference.Preference.OnPreferenceChangeListener;
@@ -99,6 +99,11 @@
     private static final String KEY_TRUST_AGENT = "trust_agent";
     private static final String KEY_SCREEN_PINNING = "screen_pinning_settings";
 
+    // These switch preferences need special handling since they're not all stored in Settings.
+    private static final String SWITCH_PREFERENCE_KEYS[] = { KEY_LOCK_AFTER_TIMEOUT,
+            KEY_LOCK_ENABLED, KEY_VISIBLE_PATTERN, KEY_BIOMETRIC_WEAK_LIVELINESS,
+            KEY_POWER_INSTANTLY_LOCKS, KEY_SHOW_PASSWORD, KEY_TOGGLE_INSTALL_APPLICATIONS };
+
     // Only allow one trust agent on the platform.
     private static final boolean ONLY_ONE_TRUST_AGENT = true;
 
@@ -108,17 +113,17 @@
     private LockPatternUtils mLockPatternUtils;
     private ListPreference mLockAfter;
 
-    private CheckBoxPreference mBiometricWeakLiveliness;
-    private CheckBoxPreference mVisiblePattern;
+    private SwitchPreference mBiometricWeakLiveliness;
+    private SwitchPreference mVisiblePattern;
 
-    private CheckBoxPreference mShowPassword;
+    private SwitchPreference mShowPassword;
 
     private KeyStore mKeyStore;
     private Preference mResetCredentials;
 
-    private CheckBoxPreference mToggleAppInstallation;
+    private SwitchPreference mToggleAppInstallation;
     private DialogInterface mWarnInstallApps;
-    private CheckBoxPreference mPowerButtonInstantlyLocks;
+    private SwitchPreference mPowerButtonInstantlyLocks;
 
     private boolean mIsPrimary;
 
@@ -249,13 +254,13 @@
 
         // biometric weak liveliness
         mBiometricWeakLiveliness =
-                (CheckBoxPreference) root.findPreference(KEY_BIOMETRIC_WEAK_LIVELINESS);
+                (SwitchPreference) root.findPreference(KEY_BIOMETRIC_WEAK_LIVELINESS);
 
         // visible pattern
-        mVisiblePattern = (CheckBoxPreference) root.findPreference(KEY_VISIBLE_PATTERN);
+        mVisiblePattern = (SwitchPreference) root.findPreference(KEY_VISIBLE_PATTERN);
 
         // lock instantly on power key press
-        mPowerButtonInstantlyLocks = (CheckBoxPreference) root.findPreference(
+        mPowerButtonInstantlyLocks = (SwitchPreference) root.findPreference(
                 KEY_POWER_INSTANTLY_LOCKS);
         Preference trustAgentPreference = root.findPreference(KEY_TRUST_AGENT);
         if (mPowerButtonInstantlyLocks != null &&
@@ -291,18 +296,14 @@
                 root.findPreference(KEY_SIM_LOCK).setEnabled(false);
             }
         }
-        try {
-            if (Settings.System.getInt(getContentResolver(), Settings.System.LOCK_TO_APP_ENABLED)
-                    != 0) {
-                root.findPreference(KEY_SCREEN_PINNING).setSummary(
-                        getResources().getString(R.string.switch_on_text));
-            }
-        } catch (SettingNotFoundException e) {
-            Log.w(TAG, "No Lock-to-app enabled setting", e);
+        if (Settings.System.getInt(getContentResolver(),
+                Settings.System.LOCK_TO_APP_ENABLED, 0) != 0) {
+            root.findPreference(KEY_SCREEN_PINNING).setSummary(
+                    getResources().getString(R.string.switch_on_text));
         }
 
         // Show password
-        mShowPassword = (CheckBoxPreference) root.findPreference(KEY_SHOW_PASSWORD);
+        mShowPassword = (SwitchPreference) root.findPreference(KEY_SHOW_PASSWORD);
         mResetCredentials = root.findPreference(KEY_RESET_CREDENTIALS);
 
         // Credential storage
@@ -326,7 +327,7 @@
         // Application install
         PreferenceGroup deviceAdminCategory = (PreferenceGroup)
                 root.findPreference(KEY_DEVICE_ADMIN_CATEGORY);
-        mToggleAppInstallation = (CheckBoxPreference) findPreference(
+        mToggleAppInstallation = (SwitchPreference) findPreference(
                 KEY_TOGGLE_INSTALL_APPLICATIONS);
         mToggleAppInstallation.setChecked(isNonMarketAppsAllowed());
         // Side loading of apps.
@@ -341,7 +342,7 @@
                 (PreferenceGroup)root.findPreference(KEY_ADVANCED_SECURITY);
         if (advancedCategory != null && !mLockPatternUtils.isSecure()) {
             Preference manageAgents = advancedCategory.findPreference(KEY_MANAGE_TRUST_AGENTS);
-            if (advancedCategory != null) advancedCategory.removePreference(manageAgents);
+            if (manageAgents != null) advancedCategory.removePreference(manageAgents);
         }
 
         // The above preferences come and go based on security state, so we need to update
@@ -350,6 +351,10 @@
         Index.getInstance(getActivity())
                 .updateFromClassNameResource(SecuritySettings.class.getName(), true, true);
 
+        for (int i = 0; i < SWITCH_PREFERENCE_KEYS.length; i++) {
+            final Preference pref = findPreference(SWITCH_PREFERENCE_KEYS[i]);
+            if (pref != null) pref.setOnPreferenceChangeListener(this);
+        }
         return root;
     }
 
@@ -523,8 +528,6 @@
     @Override
     public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
         final String key = preference.getKey();
-
-        final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();
         if (KEY_UNLOCK_SET_OR_CHANGE.equals(key)) {
             startFragment(this, "com.android.settings.ChooseLockGeneric$ChooseLockGenericFragment",
                     R.string.lock_settings_picker_title, SET_OR_CHANGE_LOCK_METHOD_REQUEST, null);
@@ -539,42 +542,6 @@
                 // can't be reached, but is here in case things change in the future
                 startBiometricWeakImprove();
             }
-        } else if (KEY_BIOMETRIC_WEAK_LIVELINESS.equals(key)) {
-            if (isToggled(preference)) {
-                lockPatternUtils.setBiometricWeakLivelinessEnabled(true);
-            } else {
-                // In this case the user has just unchecked the checkbox, but this action requires
-                // them to confirm their password.  We need to re-check the checkbox until
-                // they've confirmed their password
-                mBiometricWeakLiveliness.setChecked(true);
-                ChooseLockSettingsHelper helper =
-                        new ChooseLockSettingsHelper(this.getActivity(), this);
-                if (!helper.launchConfirmationActivity(
-                                CONFIRM_EXISTING_FOR_BIOMETRIC_WEAK_LIVELINESS_OFF, null, null)) {
-                    // If this returns false, it means no password confirmation is required, so
-                    // go ahead and uncheck it here.
-                    // Note: currently a backup is required for biometric_weak so this code path
-                    // can't be reached, but is here in case things change in the future
-                    lockPatternUtils.setBiometricWeakLivelinessEnabled(false);
-                    mBiometricWeakLiveliness.setChecked(false);
-                }
-            }
-        } else if (KEY_LOCK_ENABLED.equals(key)) {
-            lockPatternUtils.setLockPatternEnabled(isToggled(preference));
-        } else if (KEY_VISIBLE_PATTERN.equals(key)) {
-            lockPatternUtils.setVisiblePatternEnabled(isToggled(preference));
-        } else if (KEY_POWER_INSTANTLY_LOCKS.equals(key)) {
-            lockPatternUtils.setPowerButtonInstantlyLocks(isToggled(preference));
-        } else if (preference == mShowPassword) {
-            Settings.System.putInt(getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD,
-                    mShowPassword.isChecked() ? 1 : 0);
-        } else if (preference == mToggleAppInstallation) {
-            if (mToggleAppInstallation.isChecked()) {
-                mToggleAppInstallation.setChecked(false);
-                warnAppInstallation();
-            } else {
-                setNonMarketAppsAllowed(false);
-            }
         } else if (KEY_TRUST_AGENT.equals(key)) {
             ChooseLockSettingsHelper helper =
                     new ChooseLockSettingsHelper(this.getActivity(), this);
@@ -589,14 +556,9 @@
             // If we didn't handle it, let preferences handle it.
             return super.onPreferenceTreeClick(preferenceScreen, preference);
         }
-
         return true;
     }
 
-    private boolean isToggled(Preference pref) {
-        return ((CheckBoxPreference) pref).isChecked();
-    }
-
     /**
      * see confirmPatternThenDisableAndClear
      */
@@ -629,7 +591,9 @@
 
     @Override
     public boolean onPreferenceChange(Preference preference, Object value) {
-        if (preference == mLockAfter) {
+        final String key = preference.getKey();
+        final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();
+        if (KEY_LOCK_AFTER_TIMEOUT.equals(key)) {
             int timeout = Integer.parseInt((String) value);
             try {
                 Settings.Secure.putInt(getContentResolver(),
@@ -638,6 +602,42 @@
                 Log.e("SecuritySettings", "could not persist lockAfter timeout setting", e);
             }
             updateLockAfterPreferenceSummary();
+        } else if (KEY_LOCK_ENABLED.equals(key)) {
+            lockPatternUtils.setLockPatternEnabled((Boolean) value);
+        } else if (KEY_VISIBLE_PATTERN.equals(key)) {
+            lockPatternUtils.setVisiblePatternEnabled((Boolean) value);
+        } else  if (KEY_BIOMETRIC_WEAK_LIVELINESS.equals(key)) {
+            if ((Boolean) value) {
+                lockPatternUtils.setBiometricWeakLivelinessEnabled(true);
+            } else {
+                // In this case the user has just unchecked the checkbox, but this action requires
+                // them to confirm their password.  We need to re-check the checkbox until
+                // they've confirmed their password
+                mBiometricWeakLiveliness.setChecked(true);
+                ChooseLockSettingsHelper helper =
+                        new ChooseLockSettingsHelper(this.getActivity(), this);
+                if (!helper.launchConfirmationActivity(
+                                CONFIRM_EXISTING_FOR_BIOMETRIC_WEAK_LIVELINESS_OFF, null, null)) {
+                    // If this returns false, it means no password confirmation is required, so
+                    // go ahead and uncheck it here.
+                    // Note: currently a backup is required for biometric_weak so this code path
+                    // can't be reached, but is here in case things change in the future
+                    lockPatternUtils.setBiometricWeakLivelinessEnabled(false);
+                    mBiometricWeakLiveliness.setChecked(false);
+                }
+            }
+        } else if (KEY_POWER_INSTANTLY_LOCKS.equals(key)) {
+            mLockPatternUtils.setPowerButtonInstantlyLocks((Boolean) value);
+        } else if (KEY_SHOW_PASSWORD.equals(key)) {
+            Settings.System.putInt(getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD,
+                    ((Boolean) value) ? 1 : 0);
+        } else if (KEY_TOGGLE_INSTALL_APPLICATIONS.equals(key)) {
+            if ((Boolean) value) {
+                mToggleAppInstallation.setChecked(false);
+                warnAppInstallation();
+            } else {
+                setNonMarketAppsAllowed(false);
+            }
         }
         return true;
     }
diff --git a/src/com/android/settings/Settings.java b/src/com/android/settings/Settings.java
index 123d4fe..3a69125 100644
--- a/src/com/android/settings/Settings.java
+++ b/src/com/android/settings/Settings.java
@@ -38,6 +38,7 @@
     public static class InputMethodAndLanguageSettingsActivity extends SettingsActivity { /* empty */ }
     public static class KeyboardLayoutPickerActivity extends SettingsActivity { /* empty */ }
     public static class InputMethodAndSubtypeEnablerActivity extends SettingsActivity { /* empty */ }
+    public static class VoiceInputSettingsActivity extends SettingsActivity { /* empty */ }
     public static class SpellCheckersSettingsActivity extends SettingsActivity { /* empty */ }
     public static class LocalePickerActivity extends SettingsActivity { /* empty */ }
     public static class UserDictionarySettingsActivity extends SettingsActivity { /* empty */ }
@@ -63,6 +64,7 @@
     public static class AccessibilityContrastSettingsActivity extends SettingsActivity { /* empty */ }
     public static class AccessibilityDaltonizerSettingsActivity extends SettingsActivity { /* empty */ }
     public static class SecuritySettingsActivity extends SettingsActivity { /* empty */ }
+    public static class UsageAccessSettingsActivity extends SettingsActivity { /* empty */ }
     public static class LocationSettingsActivity extends SettingsActivity { /* empty */ }
     public static class PrivacySettingsActivity extends SettingsActivity { /* empty */ }
     public static class RunningServicesActivity extends SettingsActivity { /* empty */ }
diff --git a/src/com/android/settings/SettingsActivity.java b/src/com/android/settings/SettingsActivity.java
index bb5ac00..e0ab5bc 100644
--- a/src/com/android/settings/SettingsActivity.java
+++ b/src/com/android/settings/SettingsActivity.java
@@ -72,7 +72,6 @@
 import com.android.settings.applications.ManageApplications;
 import com.android.settings.applications.ProcessStatsUi;
 import com.android.settings.bluetooth.BluetoothSettings;
-import com.android.settings.bluetooth.MessageAccessSettings;
 import com.android.settings.dashboard.DashboardCategory;
 import com.android.settings.dashboard.DashboardSummary;
 import com.android.settings.dashboard.DashboardTile;
@@ -105,6 +104,7 @@
 import com.android.settings.sim.SimSettings;
 import com.android.settings.tts.TextToSpeechSettings;
 import com.android.settings.users.UserSettings;
+import com.android.settings.voice.VoiceInputSettings;
 import com.android.settings.vpn2.VpnSettings;
 import com.android.settings.wfd.WifiDisplaySettings;
 import com.android.settings.widget.SwitchBar;
@@ -237,7 +237,6 @@
             AdvancedWifiSettings.class.getName(),
             SavedAccessPointsWifiSettings.class.getName(),
             BluetoothSettings.class.getName(),
-            MessageAccessSettings.class.getName(),
             SimSettings.class.getName(),
             TetherSettings.class.getName(),
             WifiP2pSettings.class.getName(),
@@ -245,6 +244,7 @@
             DateTimeSettings.class.getName(),
             LocalePicker.class.getName(),
             InputMethodAndLanguageSettings.class.getName(),
+            VoiceInputSettings.class.getName(),
             SpellCheckersSettings.class.getName(),
             UserDictionaryList.class.getName(),
             UserDictionarySettings.class.getName(),
@@ -256,6 +256,7 @@
             NotificationStation.class.getName(),
             LocationSettings.class.getName(),
             SecuritySettings.class.getName(),
+            UsageAccessSettings.class.getName(),
             PrivacySettings.class.getName(),
             DeviceAdminSettings.class.getName(),
             AccessibilitySettings.class.getName(),
@@ -1042,7 +1043,7 @@
                             }
 
                             // Show the SIM Cards setting if there are more than 2 SIMs installed.
-                            if(tile.id != R.id.sim_settings || SimSettings.showSimCardScreen(this)){
+                            if(tile.id != R.id.sim_settings || Utils.showSimCardTile(this)){
                                 category.addTile(tile);
                             }
 
diff --git a/src/com/android/settings/TrustAgentSettings.java b/src/com/android/settings/TrustAgentSettings.java
new file mode 100644
index 0000000..54fef36
--- /dev/null
+++ b/src/com/android/settings/TrustAgentSettings.java
@@ -0,0 +1,157 @@
+/*
+ * 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.
+ */
+
+package com.android.settings;
+
+import java.util.List;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.graphics.drawable.Drawable;
+import android.os.Bundle;
+import android.preference.Preference;
+import android.preference.PreferenceGroup;
+import android.preference.SwitchPreference;
+import android.service.trust.TrustAgentService;
+import android.util.ArrayMap;
+import android.util.ArraySet;
+
+import com.android.internal.widget.LockPatternUtils;
+
+public class TrustAgentSettings extends SettingsPreferenceFragment implements
+        Preference.OnPreferenceChangeListener {
+    private static final String SERVICE_INTERFACE = TrustAgentService.SERVICE_INTERFACE;
+    private ArrayMap<ComponentName, AgentInfo> mAvailableAgents;
+    private final ArraySet<ComponentName> mActiveAgents = new ArraySet<ComponentName>();
+    private LockPatternUtils mLockPatternUtils;
+
+    public static final class AgentInfo {
+        CharSequence label;
+        ComponentName component; // service that implements ITrustAgent
+        SwitchPreference preference;
+        public Drawable icon;
+
+        @Override
+        public boolean equals(Object other) {
+            if (other instanceof AgentInfo) {
+                return component.equals(((AgentInfo)other).component);
+            }
+            return true;
+        }
+
+        public int compareTo(AgentInfo other) {
+            return component.compareTo(other.component);
+        }
+    }
+
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+        addPreferencesFromResource(R.xml.trust_agent_settings);
+    }
+
+    public void onResume() {
+        super.onResume();
+        updateAgents();
+    };
+
+    private void updateAgents() {
+        final Context context = getActivity();
+        if (mAvailableAgents == null) {
+            mAvailableAgents = findAvailableTrustAgents();
+        }
+        if (mLockPatternUtils == null) {
+            mLockPatternUtils = new LockPatternUtils(getActivity());
+        }
+        loadActiveAgents();
+        PreferenceGroup category =
+                (PreferenceGroup) getPreferenceScreen().findPreference("trust_agents");
+        category.removeAll();
+        final int count = mAvailableAgents.size();
+        for (int i = 0; i < count; i++) {
+            AgentInfo agent = mAvailableAgents.valueAt(i);
+            final SwitchPreference preference = new SwitchPreference(context);
+            agent.preference = preference;
+            preference.setPersistent(false);
+            preference.setTitle(agent.label);
+            preference.setIcon(agent.icon);
+            preference.setPersistent(false);
+            preference.setOnPreferenceChangeListener(this);
+            preference.setChecked(mActiveAgents.contains(agent.component));
+            category.addPreference(agent.preference);
+        }
+    }
+
+    private void loadActiveAgents() {
+        List<ComponentName> activeTrustAgents = mLockPatternUtils.getEnabledTrustAgents();
+        if (activeTrustAgents != null) {
+            mActiveAgents.addAll(activeTrustAgents);
+        }
+    }
+
+    private void saveActiveAgents() {
+        mLockPatternUtils.setEnabledTrustAgents(mActiveAgents);
+    }
+
+    ArrayMap<ComponentName, AgentInfo> findAvailableTrustAgents() {
+        PackageManager pm = getActivity().getPackageManager();
+        Intent trustAgentIntent = new Intent(SERVICE_INTERFACE);
+        List<ResolveInfo> resolveInfos = pm.queryIntentServices(trustAgentIntent,
+                PackageManager.GET_META_DATA);
+
+        ArrayMap<ComponentName, AgentInfo> agents = new ArrayMap<ComponentName, AgentInfo>();
+        final int count = resolveInfos.size();
+        agents.ensureCapacity(count);
+        for (int i = 0; i < count; i++ ) {
+            ResolveInfo resolveInfo = resolveInfos.get(i);
+            if (resolveInfo.serviceInfo == null) continue;
+            if (!TrustAgentUtils.checkProvidePermission(resolveInfo, pm)) continue;
+            ComponentName name = TrustAgentUtils.getComponentName(resolveInfo);
+            AgentInfo agentInfo = new AgentInfo();
+            agentInfo.label = resolveInfo.loadLabel(pm);
+            agentInfo.icon = resolveInfo.loadIcon(pm);
+            agentInfo.component = name;
+            agents.put(name, agentInfo);
+        }
+        return agents;
+    }
+
+    @Override
+    public boolean onPreferenceChange(Preference preference, Object newValue) {
+        if (preference instanceof SwitchPreference) {
+            final int count = mAvailableAgents.size();
+            for (int i = 0; i < count; i++) {
+                AgentInfo agent = mAvailableAgents.valueAt(i);
+                if (agent.preference == preference) {
+                    if ((Boolean) newValue) {
+                        if (!mActiveAgents.contains(agent.component)) {
+                            mActiveAgents.add(agent.component);
+                        }
+                    } else {
+                        mActiveAgents.remove(agent.component);
+                    }
+                    saveActiveAgents();
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+}
diff --git a/src/com/android/settings/UsageStats.java b/src/com/android/settings/UsageStatsActivity.java
similarity index 83%
rename from src/com/android/settings/UsageStats.java
rename to src/com/android/settings/UsageStatsActivity.java
index 08c272e..90aec5b 100755
--- a/src/com/android/settings/UsageStats.java
+++ b/src/com/android/settings/UsageStatsActivity.java
@@ -17,7 +17,7 @@
 package com.android.settings;
 
 import android.app.Activity;
-import android.app.usage.PackageUsageStats;
+import android.app.usage.UsageStats;
 import android.app.usage.UsageStatsManager;
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
@@ -30,6 +30,7 @@
 import java.util.Calendar;
 import java.util.Collections;
 import java.util.Comparator;
+import java.util.List;
 import java.util.Map;
 
 import android.text.format.DateUtils;
@@ -48,15 +49,15 @@
 /**
  * Activity to display package usage statistics.
  */
-public class UsageStats extends Activity implements OnItemSelectedListener {
+public class UsageStatsActivity extends Activity implements OnItemSelectedListener {
     private static final String TAG = "UsageStatsActivity";
     private static final boolean localLOGV = false;
     private UsageStatsManager mUsageStatsManager;
     private LayoutInflater mInflater;
     private UsageStatsAdapter mAdapter;
     private PackageManager mPm;
-    
-    public static class AppNameComparator implements Comparator<PackageUsageStats> {
+
+    public static class AppNameComparator implements Comparator<UsageStats> {
         private Map<String, String> mAppLabelList;
 
         AppNameComparator(Map<String, String> appList) {
@@ -64,76 +65,87 @@
         }
 
         @Override
-        public final int compare(PackageUsageStats a, PackageUsageStats b) {
+        public final int compare(UsageStats a, UsageStats b) {
             String alabel = mAppLabelList.get(a.getPackageName());
             String blabel = mAppLabelList.get(b.getPackageName());
             return alabel.compareTo(blabel);
         }
     }
 
-    public static class LastTimeUsedComparator implements Comparator<PackageUsageStats> {
+    public static class LastTimeUsedComparator implements Comparator<UsageStats> {
         @Override
-        public final int compare(PackageUsageStats a, PackageUsageStats b) {
+        public final int compare(UsageStats a, UsageStats b) {
             // return by descending order
             return (int)(b.getLastTimeUsed() - a.getLastTimeUsed());
         }
     }
-    
-    public static class UsageTimeComparator implements Comparator<PackageUsageStats> {
+
+    public static class UsageTimeComparator implements Comparator<UsageStats> {
         @Override
-        public final int compare(PackageUsageStats a, PackageUsageStats b) {
-            return (int)(b.getTotalTimeSpent() - a.getTotalTimeSpent());
+        public final int compare(UsageStats a, UsageStats b) {
+            return (int)(b.getTotalTimeInForeground() - a.getTotalTimeInForeground());
         }
     }
-    
+
     // View Holder used when displaying views
     static class AppViewHolder {
         TextView pkgName;
         TextView lastTimeUsed;
         TextView usageTime;
     }
-    
+
     class UsageStatsAdapter extends BaseAdapter {
          // Constants defining order for display order
         private static final int _DISPLAY_ORDER_USAGE_TIME = 0;
         private static final int _DISPLAY_ORDER_LAST_TIME_USED = 1;
         private static final int _DISPLAY_ORDER_APP_NAME = 2;
-        
+
         private int mDisplayOrder = _DISPLAY_ORDER_USAGE_TIME;
         private LastTimeUsedComparator mLastTimeUsedComparator = new LastTimeUsedComparator();
         private UsageTimeComparator mUsageTimeComparator = new UsageTimeComparator();
         private AppNameComparator mAppLabelComparator;
         private final ArrayMap<String, String> mAppLabelMap = new ArrayMap<>();
-        private final ArrayList<PackageUsageStats> mPackageStats = new ArrayList<>();
+        private final ArrayList<UsageStats> mPackageStats = new ArrayList<>();
 
         UsageStatsAdapter() {
             Calendar cal = Calendar.getInstance();
             cal.add(Calendar.DAY_OF_YEAR, -5);
 
-            final android.app.usage.UsageStats stats =
-                    mUsageStatsManager.getRecentStatsSince(cal.getTimeInMillis());
+            final List<UsageStats> stats =
+                    mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,
+                            cal.getTimeInMillis(), System.currentTimeMillis());
             if (stats == null) {
                 return;
             }
 
-            final int pkgCount = stats.getPackageCount();
-            for (int i = 0; i < pkgCount; i++) {
-                final PackageUsageStats pkgStats = stats.getPackage(i);
+            ArrayMap<String, UsageStats> map = new ArrayMap<>();
+            final int statCount = stats.size();
+            for (int i = 0; i < statCount; i++) {
+                final android.app.usage.UsageStats pkgStats = stats.get(i);
 
                 // load application labels for each application
                 try {
                     ApplicationInfo appInfo = mPm.getApplicationInfo(pkgStats.getPackageName(), 0);
                     String label = appInfo.loadLabel(mPm).toString();
                     mAppLabelMap.put(pkgStats.getPackageName(), label);
-                    mPackageStats.add(pkgStats);
+
+                    UsageStats existingStats =
+                            map.get(pkgStats.getPackageName());
+                    if (existingStats == null) {
+                        map.put(pkgStats.getPackageName(), pkgStats);
+                    } else {
+                        existingStats.add(pkgStats);
+                    }
+
                 } catch (NameNotFoundException e) {
                     // This package may be gone.
                 }
-           }
+            }
+            mPackageStats.addAll(map.values());
 
-           // Sort list
-           mAppLabelComparator = new AppNameComparator(mAppLabelMap);
-           sortList();
+            // Sort list
+            mAppLabelComparator = new AppNameComparator(mAppLabelMap);
+            sortList();
         }
 
         @Override
@@ -177,20 +189,20 @@
             }
 
             // Bind the data efficiently with the holder
-            PackageUsageStats pkgStats = mPackageStats.get(position);
+            UsageStats pkgStats = mPackageStats.get(position);
             if (pkgStats != null) {
                 String label = mAppLabelMap.get(pkgStats.getPackageName());
                 holder.pkgName.setText(label);
                 holder.lastTimeUsed.setText(DateUtils.formatSameDayTime(pkgStats.getLastTimeUsed(),
                         System.currentTimeMillis(), DateFormat.MEDIUM, DateFormat.MEDIUM));
                 holder.usageTime.setText(
-                        DateUtils.formatElapsedTime(pkgStats.getTotalTimeSpent() / 1000));
+                        DateUtils.formatElapsedTime(pkgStats.getTotalTimeInForeground() / 1000));
             } else {
                 Log.w(TAG, "No usage stats info for package:" + position);
             }
             return convertView;
         }
-        
+
         void sortList(int sortOrder) {
             if (mDisplayOrder == sortOrder) {
                 // do nothing
@@ -226,7 +238,7 @@
 
         Spinner typeSpinner = (Spinner) findViewById(R.id.typeSpinner);
         typeSpinner.setOnItemSelectedListener(this);
-        
+
         ListView listView = (ListView) findViewById(R.id.pkg_list);
         mAdapter = new UsageStatsAdapter();
         listView.setAdapter(mAdapter);
@@ -242,4 +254,3 @@
         // do nothing
     }
 }
-
diff --git a/src/com/android/settings/Utils.java b/src/com/android/settings/Utils.java
index 255ab58..e88c0fc 100644
--- a/src/com/android/settings/Utils.java
+++ b/src/com/android/settings/Utils.java
@@ -820,4 +820,16 @@
         if (icon == null) return null;
         return CircleFramedDrawable.getInstance(context, icon);
     }
+
+    /**
+     * Return whether or not the user should have a SIM Cards option in Settings.
+     * TODO: Change back to returning true if count is greater than one after testing.
+     * TODO: See bug 16533525.
+     */
+    public static boolean showSimCardTile(Context context) {
+        final TelephonyManager tm =
+                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
+
+        return tm.getSimCount() > 0;
+    }
 }
diff --git a/src/com/android/settings/VoiceSettingsActivity.java b/src/com/android/settings/VoiceSettingsActivity.java
new file mode 100644
index 0000000..b5e8ede
--- /dev/null
+++ b/src/com/android/settings/VoiceSettingsActivity.java
@@ -0,0 +1,51 @@
+/*
+ * 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.
+ */
+
+package com.android.settings;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+import android.util.Log;
+
+/**
+ * Activity for modifying a setting using the Voice Interaction API. This activity
+ * MUST only modify the setting if the intent was sent using
+ * {@link android.service.voice.VoiceInteractionSession#startVoiceActivity startVoiceActivity}.
+ */
+abstract public class VoiceSettingsActivity extends Activity {
+
+    private static final String TAG = "VoiceSettingsActivity";
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        if (isVoiceInteraction()) {
+            // Only permit if this is a voice interaction.
+            onVoiceSettingInteraction(getIntent());
+        } else {
+            Log.v(TAG, "Cannot modify settings without voice interaction");
+        }
+        finish();
+    }
+
+    /**
+     * Modify the setting as a voice interaction. The activity will finish
+     * after this method is called.
+     */
+    abstract protected void onVoiceSettingInteraction(Intent intent);
+}
diff --git a/src/com/android/settings/accounts/AccountSettings.java b/src/com/android/settings/accounts/AccountSettings.java
index ffd6037..2eb89b0 100644
--- a/src/com/android/settings/accounts/AccountSettings.java
+++ b/src/com/android/settings/accounts/AccountSettings.java
@@ -29,10 +29,15 @@
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.content.pm.UserInfo;
 import android.graphics.drawable.Drawable;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.drawable.BitmapDrawable;
 import android.os.Bundle;
 import android.os.UserHandle;
 import android.os.UserManager;
+import android.os.Process;
 import android.util.Log;
 import android.util.SparseArray;
 import android.view.Menu;
@@ -41,6 +46,7 @@
 import android.preference.Preference;
 import android.preference.Preference.OnPreferenceClickListener;
 import android.preference.PreferenceGroup;
+import android.preference.PreferenceCategory;
 import android.preference.PreferenceScreen;
 
 import com.android.settings.R;
@@ -50,8 +56,10 @@
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Comparator;
+import java.util.List;
 
 import static android.content.Intent.EXTRA_USER;
+import static android.os.UserManager.DISALLOW_MODIFY_ACCOUNTS;
 
 /**
  * Settings screen for the account types on the device.
@@ -64,26 +72,20 @@
         implements AuthenticatorHelper.OnAccountsUpdateListener,
         OnPreferenceClickListener {
     public static final String TAG = "AccountSettings";
-    private static final String KEY_ACCOUNT = "account";
-    private static final String KEY_ADD_ACCOUNT = "add_account";
 
-    private static final String KEY_CATEGORY_PERSONAL = "account_personal";
-    private static final String KEY_ADD_ACCOUNT_PERSONAL = "add_account_personal";
-    private static final String KEY_CATEGORY_WORK = "account_work";
-    private static final String KEY_ADD_ACCOUNT_WORK = "add_account_work";
+    private static final String KEY_ACCOUNT = "account";
 
     private static final String ADD_ACCOUNT_ACTION = "android.settings.ADD_ACCOUNT_SETTINGS";
-
-    private static final ArrayList<String> EMPTY_LIST = new ArrayList<String>();
-
     private static final String TAG_CONFIRM_AUTO_SYNC_CHANGE = "confirmAutoSyncChange";
 
+    private static final int ORDER_LAST = 1001;
+    private static final int ORDER_NEXT_TO_LAST = 1000;
 
     private UserManager mUm;
-    private SparseArray<ProfileData> mProfiles;
+    private SparseArray<ProfileData> mProfiles = new SparseArray<ProfileData>();
     private ManagedProfileBroadcastReceiver mManagedProfileBroadcastReceiver
                 = new ManagedProfileBroadcastReceiver();
-    private boolean mIsSingleProfileUi = true;
+    private Preference mProfileNotAvailablePreference;
 
     /**
      * Holds data related to the accounts belonging to one profile.
@@ -98,64 +100,59 @@
          */
         public Preference addAccountPreference;
         /**
-         * The user handle of the user that these accounts belong to.
+         * The preference that displays the button to remove the managed profile
          */
-        public UserHandle userHandle;
+        public Preference removeWorkProfilePreference;
         /**
          * The {@link AuthenticatorHelper} that holds accounts data for this profile.
          */
         public AuthenticatorHelper authenticatorHelper;
+        /**
+         * The {@link UserInfo} of the profile.
+         */
+        public UserInfo userInfo;
     }
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         mUm = (UserManager) getSystemService(Context.USER_SERVICE);
-        mProfiles = new SparseArray<ProfileData>(2);
         setHasOptionsMenu(true);
     }
 
     @Override
     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
         inflater.inflate(R.menu.account_settings, menu);
-        final UserHandle currentProfile = UserHandle.getCallingUserHandle();
-        if (mIsSingleProfileUi) {
-            menu.findItem(R.id.account_settings_menu_auto_sync)
-                    .setVisible(true)
-                    .setOnMenuItemClickListener(new MasterSyncStateClickListener(currentProfile));
-            menu.removeItem(R.id.account_settings_menu_auto_sync_personal);
-            menu.removeItem(R.id.account_settings_menu_auto_sync_work);
-        } else {
-            final UserHandle managedProfile = Utils.getManagedProfile(mUm);
-
-            menu.findItem(R.id.account_settings_menu_auto_sync_personal)
-                    .setVisible(true)
-                    .setOnMenuItemClickListener(new MasterSyncStateClickListener(currentProfile));
-            menu.findItem(R.id.account_settings_menu_auto_sync_work)
-                    .setVisible(true)
-                    .setOnMenuItemClickListener(new MasterSyncStateClickListener(managedProfile));
-            menu.removeItem(R.id.account_settings_menu_auto_sync);
-        }
         super.onCreateOptionsMenu(menu, inflater);
     }
 
     @Override
     public void onPrepareOptionsMenu(Menu menu) {
-        final UserHandle currentProfile = UserHandle.getCallingUserHandle();
-        if (mIsSingleProfileUi) {
+        final UserHandle currentProfile = Process.myUserHandle();
+        if (mProfiles.size() == 1) {
             menu.findItem(R.id.account_settings_menu_auto_sync)
+                    .setVisible(true)
+                    .setOnMenuItemClickListener(new MasterSyncStateClickListener(currentProfile))
                     .setChecked(ContentResolver.getMasterSyncAutomaticallyAsUser(
                             currentProfile.getIdentifier()));
+            menu.findItem(R.id.account_settings_menu_auto_sync_personal).setVisible(false);
+            menu.findItem(R.id.account_settings_menu_auto_sync_work).setVisible(false);
         } else {
-            final UserHandle managedProfile = Utils.getManagedProfile(mUm);
+            // We assume there's only one managed profile, otherwise UI needs to change
+            final UserHandle managedProfile = mProfiles.valueAt(1).userInfo.getUserHandle();
 
             menu.findItem(R.id.account_settings_menu_auto_sync_personal)
+                    .setVisible(true)
+                    .setOnMenuItemClickListener(new MasterSyncStateClickListener(currentProfile))
                     .setChecked(ContentResolver.getMasterSyncAutomaticallyAsUser(
                             currentProfile.getIdentifier()));
             menu.findItem(R.id.account_settings_menu_auto_sync_work)
+                    .setVisible(true)
+                    .setOnMenuItemClickListener(new MasterSyncStateClickListener(managedProfile))
                     .setChecked(ContentResolver.getMasterSyncAutomaticallyAsUser(
                             managedProfile.getIdentifier()));
-            }
+            menu.findItem(R.id.account_settings_menu_auto_sync).setVisible(false);
+         }
     }
 
     @Override
@@ -192,10 +189,22 @@
             ProfileData profileData = mProfiles.valueAt(i);
             if (preference == profileData.addAccountPreference) {
                 Intent intent = new Intent(ADD_ACCOUNT_ACTION);
-                intent.putExtra(EXTRA_USER, profileData.userHandle);
+                intent.putExtra(EXTRA_USER, profileData.userInfo.getUserHandle());
                 startActivity(intent);
                 return true;
             }
+            if (preference == profileData.removeWorkProfilePreference) {
+                final int userId = profileData.userInfo.id;
+                Utils.createRemoveConfirmationDialog(getActivity(), userId,
+                        new DialogInterface.OnClickListener() {
+                            @Override
+                            public void onClick(DialogInterface dialog, int which) {
+                                mUm.removeUser(userId);
+                            }
+                        }
+                ).show();
+                return true;
+            }
         }
         return false;
     }
@@ -204,61 +213,82 @@
         // Load the preferences from an XML resource
         addPreferencesFromResource(R.xml.account_settings);
 
+        if (Utils.isManagedProfile(mUm)) {
+            // This should not happen
+            Log.e(TAG, "We should not be showing settings for a managed profile");
+            finish();
+            return;
+        }
+
+        final PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference(KEY_ACCOUNT);
         if(mUm.isLinkedUser()) {
             // Restricted user or similar
-            updateSingleProfileUi();
+            UserInfo userInfo = mUm.getUserInfo(UserHandle.myUserId());
+            updateProfileUi(userInfo, false /* no category needed */, preferenceScreen);
         } else {
-            if (Utils.isManagedProfile(mUm)) {
-                // This should not happen
-                Log.w(TAG, "We should not be showing settings for a managed profile");
-                updateSingleProfileUi();
-            }
-            final UserHandle currentProfile = UserHandle.getCallingUserHandle();
-            final UserHandle managedProfile = Utils.getManagedProfile(mUm);
-            if (managedProfile == null) {
-                updateSingleProfileUi();
-            } else {
-                mIsSingleProfileUi = false;
-                updateProfileUi(currentProfile, KEY_CATEGORY_PERSONAL, KEY_ADD_ACCOUNT_PERSONAL,
-                        EMPTY_LIST);
-                final ArrayList<String> unusedPreferences = new ArrayList<String>(2);
-                unusedPreferences.add(KEY_ADD_ACCOUNT);
-                updateProfileUi(managedProfile, KEY_CATEGORY_WORK, KEY_ADD_ACCOUNT_WORK,
-                        unusedPreferences);
+            List<UserInfo> profiles = mUm.getProfiles(UserHandle.myUserId());
+            final int profilesCount = profiles.size();
+            final boolean addCategory = profilesCount > 1;
+            for (int i = 0; i < profilesCount; i++) {
+                updateProfileUi(profiles.get(i), addCategory, preferenceScreen);
             }
         }
-        final int count = mProfiles.size();
-        for (int i = 0; i < count; i++) {
-            updateAccountTypes(mProfiles.valueAt(i));
+
+        // Add all preferences, starting with one for the primary profile.
+        // Note that we're relying on the ordering given by the SparseArray keys, and on the
+        // value of UserHandle.USER_OWNER being smaller than all the rest.
+        final int profilesCount = mProfiles.size();
+        for (int i = 0; i < profilesCount; i++) {
+            ProfileData profileData = mProfiles.valueAt(i);
+            if (!profileData.preferenceGroup.equals(preferenceScreen)) {
+                preferenceScreen.addPreference(profileData.preferenceGroup);
+            }
+            updateAccountTypes(profileData);
         }
     }
 
-    private void updateSingleProfileUi() {
-        final ArrayList<String> unusedPreferences = new ArrayList<String>(2);
-        unusedPreferences.add(KEY_CATEGORY_PERSONAL);
-        unusedPreferences.add(KEY_CATEGORY_WORK);
-        updateProfileUi(UserHandle.getCallingUserHandle(), KEY_ACCOUNT, KEY_ADD_ACCOUNT,
-                unusedPreferences);
-    }
-
-    private void updateProfileUi(final UserHandle userHandle, String categoryKey,
-            String addAccountKey, ArrayList<String> unusedPreferences) {
-        final int count = unusedPreferences.size();
-        for (int i = 0; i < count; i++) {
-            removePreference(unusedPreferences.get(i));
-        }
+    private void updateProfileUi(final UserInfo userInfo, boolean addCategory,
+            PreferenceScreen parent) {
+        final Context context = getActivity();
         final ProfileData profileData = new ProfileData();
-        profileData.preferenceGroup = (PreferenceGroup) findPreference(categoryKey);
-        if (mUm.hasUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS, userHandle)) {
-            removePreference(addAccountKey);
+        profileData.userInfo = userInfo;
+        if (addCategory) {
+            profileData.preferenceGroup = new PreferenceCategory(context);
+            profileData.preferenceGroup.setTitle(userInfo.isManagedProfile()
+                    ? R.string.category_work : R.string.category_personal);
+            parent.addPreference(profileData.preferenceGroup);
         } else {
-            profileData.addAccountPreference = findPreference(addAccountKey);
-            profileData.addAccountPreference.setOnPreferenceClickListener(this);
+            profileData.preferenceGroup = parent;
         }
-        profileData.userHandle = userHandle;
-        profileData.authenticatorHelper = new AuthenticatorHelper(
-                getActivity(), userHandle, mUm, this);
-        mProfiles.put(userHandle.getIdentifier(), profileData);
+        if (userInfo.isEnabled()) {
+            profileData.authenticatorHelper = new AuthenticatorHelper(context,
+                    userInfo.getUserHandle(), mUm, this);
+            if (!mUm.hasUserRestriction(DISALLOW_MODIFY_ACCOUNTS, userInfo.getUserHandle())) {
+                profileData.addAccountPreference = newAddAccountPreference(context);
+            }
+        }
+        if (userInfo.isManagedProfile()) {
+            profileData.removeWorkProfilePreference = newRemoveWorkProfilePreference(context);
+        }
+        mProfiles.put(userInfo.id, profileData);
+    }
+
+    private Preference newAddAccountPreference(Context context) {
+        Preference preference = new Preference(context);
+        preference.setTitle(R.string.add_account_label);
+        preference.setIcon(R.drawable.ic_menu_add_dark);
+        preference.setOnPreferenceClickListener(this);
+        preference.setOrder(ORDER_NEXT_TO_LAST);
+        return preference;
+    }
+
+    private Preference newRemoveWorkProfilePreference(Context context) {
+        Preference preference = new Preference(context);
+        preference.setTitle(R.string.remove_managed_profile_label);
+        preference.setIcon(R.drawable.ic_menu_delete);
+        preference.setOnPreferenceClickListener(this);
+        preference.setOrder(ORDER_LAST);
+        return preference;
     }
 
     private void cleanUpPreferences() {
@@ -266,32 +296,57 @@
         if (preferenceScreen != null) {
             preferenceScreen.removeAll();
         }
+        mProfiles.clear();
     }
 
     private void listenToAccountUpdates() {
         final int count = mProfiles.size();
         for (int i = 0; i < count; i++) {
-            mProfiles.valueAt(i).authenticatorHelper.listenToAccountUpdates();
+            AuthenticatorHelper authenticatorHelper = mProfiles.valueAt(i).authenticatorHelper;
+            if (authenticatorHelper != null) {
+                authenticatorHelper.listenToAccountUpdates();
+            }
         }
     }
 
     private void stopListeningToAccountUpdates() {
         final int count = mProfiles.size();
         for (int i = 0; i < count; i++) {
-            mProfiles.valueAt(i).authenticatorHelper.stopListeningToAccountUpdates();
+            AuthenticatorHelper authenticatorHelper = mProfiles.valueAt(i).authenticatorHelper;
+            if (authenticatorHelper != null) {
+                authenticatorHelper.stopListeningToAccountUpdates();
+            }
         }
     }
 
     private void updateAccountTypes(ProfileData profileData) {
         profileData.preferenceGroup.removeAll();
-        final ArrayList<AccountPreference> preferences = getAccountTypePreferences(
-                profileData.authenticatorHelper, profileData.userHandle);
-        final int count = preferences.size();
-        for (int i = 0; i < count; i++) {
-            profileData.preferenceGroup.addPreference(preferences.get(i));
+        if (profileData.userInfo.isEnabled()) {
+            final ArrayList<AccountPreference> preferences = getAccountTypePreferences(
+                    profileData.authenticatorHelper, profileData.userInfo.getUserHandle());
+            final int count = preferences.size();
+            for (int i = 0; i < count; i++) {
+                profileData.preferenceGroup.addPreference(preferences.get(i));
+            }
+            if (profileData.addAccountPreference != null) {
+                profileData.preferenceGroup.addPreference(profileData.addAccountPreference);
+            }
+        } else {
+            // Put a label instead of the accounts list
+            synchronized (this) {
+                if (mProfileNotAvailablePreference == null) {
+                    mProfileNotAvailablePreference = new Preference(getActivity());
+                    mProfileNotAvailablePreference.setEnabled(false);
+                    mProfileNotAvailablePreference.setIcon(R.drawable.empty_icon);
+                    mProfileNotAvailablePreference.setTitle(null);
+                    mProfileNotAvailablePreference.setSummary(
+                            R.string.managed_profile_not_available_label);
+                }
+            }
+            profileData.preferenceGroup.addPreference(mProfileNotAvailablePreference);
         }
-        if (profileData.addAccountPreference != null) {
-            profileData.preferenceGroup.addPreference(profileData.addAccountPreference);
+        if (profileData.removeWorkProfilePreference != null) {
+            profileData.preferenceGroup.addPreference(profileData.removeWorkProfilePreference);
         }
     }
 
@@ -404,6 +459,9 @@
                 // Build new state
                 updateUi();
                 listenToAccountUpdates();
+                // Force the menu to update. Note that #onPrepareOptionsMenu uses data built by
+                // #updateUi so we must call this later
+                getActivity().invalidateOptionsMenu();
                 return;
             }
             Log.w(TAG, "Cannot handle received broadcast: " + intent.getAction());
diff --git a/src/com/android/settings/accounts/ManageAccountsSettings.java b/src/com/android/settings/accounts/ManageAccountsSettings.java
index b69bf3f..8787bced 100644
--- a/src/com/android/settings/accounts/ManageAccountsSettings.java
+++ b/src/com/android/settings/accounts/ManageAccountsSettings.java
@@ -97,6 +97,8 @@
     public void onStart() {
         super.onStart();
         mAuthenticatorHelper.listenToAccountUpdates();
+        updateAuthDescriptions();
+        showAccountsIfNeeded();
     }
 
     @Override
@@ -124,8 +126,6 @@
         if (args != null && args.containsKey(KEY_ACCOUNT_LABEL)) {
             getActivity().setTitle(args.getString(KEY_ACCOUNT_LABEL));
         }
-        updateAuthDescriptions();
-        showAccountsIfNeeded();
     }
 
     @Override
diff --git a/src/com/android/settings/bluetooth/BluetoothNameDialogFragment.java b/src/com/android/settings/bluetooth/BluetoothNameDialogFragment.java
index b80e42a..4466aea 100644
--- a/src/com/android/settings/bluetooth/BluetoothNameDialogFragment.java
+++ b/src/com/android/settings/bluetooth/BluetoothNameDialogFragment.java
@@ -92,7 +92,6 @@
             mDeviceNameEdited = savedInstanceState.getBoolean(KEY_NAME_EDITED, false);
         }
         mAlertDialog = new AlertDialog.Builder(getActivity())
-                .setIcon(android.R.drawable.ic_dialog_info)
                 .setTitle(R.string.bluetooth_rename_device)
                 .setView(createDialogView(deviceName))
                 .setPositiveButton(R.string.bluetooth_rename_button,
diff --git a/src/com/android/settings/bluetooth/BluetoothSettings.java b/src/com/android/settings/bluetooth/BluetoothSettings.java
index 4b278ac..3c62ba9 100755
--- a/src/com/android/settings/bluetooth/BluetoothSettings.java
+++ b/src/com/android/settings/bluetooth/BluetoothSettings.java
@@ -69,7 +69,6 @@
     private static final int MENU_ID_SCAN = Menu.FIRST;
     private static final int MENU_ID_RENAME_DEVICE = Menu.FIRST + 1;
     private static final int MENU_ID_SHOW_RECEIVED = Menu.FIRST + 2;
-    private static final int MENU_ID_MESSAGE_ACCESS = Menu.FIRST + 3;
 
     /* Private intent to show the list of received files */
     private static final String BTOPP_ACTION_OPEN_RECEIVED_FILES =
@@ -205,12 +204,6 @@
                 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
         menu.add(Menu.NONE, MENU_ID_SHOW_RECEIVED, 0, R.string.bluetooth_show_received_files)
                 .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
-        // Message Access API is still not finished, once completed we undo this check.
-        // Bug 16232864
-        if (android.os.SystemProperties.get("show_bluetooth_message_access").equals("true")){
-            menu.add(Menu.NONE, MENU_ID_MESSAGE_ACCESS, 0, R.string.bluetooth_show_message_access)
-                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
-        }
         super.onCreateOptionsMenu(menu, inflater);
     }
 
@@ -232,14 +225,6 @@
                 Intent intent = new Intent(BTOPP_ACTION_OPEN_RECEIVED_FILES);
                 getActivity().sendBroadcast(intent);
                 return true;
-
-            case MENU_ID_MESSAGE_ACCESS:
-                if (getActivity() instanceof SettingsActivity) {
-                    ((SettingsActivity) getActivity()).startPreferencePanel(
-                            MessageAccessSettings.class.getCanonicalName(), null,
-                            R.string.bluetooth_show_message_access, null, this, 0);
-                }
-                return true;
         }
         return super.onOptionsItemSelected(item);
     }
@@ -249,6 +234,8 @@
         if (!mAvailableDevicesCategoryIsPresent) {
             getPreferenceScreen().addPreference(mAvailableDevicesCategory);
         }
+        mLocalManager.getCachedDeviceManager().clearCachedDevices();
+        mAvailableDevicesCategory.removeAll();
         mLocalAdapter.startScanning(true);
     }
 
@@ -375,7 +362,6 @@
         }
     }
 
-    @Override
     public void onDeviceBondStateChanged(CachedBluetoothDevice cachedDevice, int bondState) {
         setDeviceListGroup(getPreferenceScreen());
         removeAllDevices();
@@ -405,7 +391,7 @@
                 LayoutInflater inflater = getActivity().getLayoutInflater();
                 mSettingsDialogView = inflater.inflate(R.layout.bluetooth_device_picker, null);
                 profileFrag = (DeviceProfilesSettings)activity.getFragmentManager()
-                .findFragmentById(R.id.bluetooth_fragment_settings);
+                    .findFragmentById(R.id.bluetooth_fragment_settings);
             }
 
             final View dialogLayout = mSettingsDialogView;
diff --git a/src/com/android/settings/bluetooth/CachedBluetoothDevice.java b/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
index a7104df..3b64ade 100755
--- a/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
+++ b/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
@@ -539,7 +539,7 @@
         if (bondState == BluetoothDevice.BOND_NONE) {
             mProfiles.clear();
             mConnectAfterPairing = false;  // cancel auto-connect
-            setPhonebookPermissionChoice(ACCESS_ALLOWED);
+            setPhonebookPermissionChoice(ACCESS_UNKNOWN);
             setMessagePermissionChoice(ACCESS_UNKNOWN);
             mPhonebookRejectedTimes = 0;
             savePhonebookRejectTimes();
diff --git a/src/com/android/settings/bluetooth/CachedBluetoothDeviceManager.java b/src/com/android/settings/bluetooth/CachedBluetoothDeviceManager.java
index ff282cc..0b53b1a 100755
--- a/src/com/android/settings/bluetooth/CachedBluetoothDeviceManager.java
+++ b/src/com/android/settings/bluetooth/CachedBluetoothDeviceManager.java
@@ -86,7 +86,9 @@
             BluetoothDevice device) {
         CachedBluetoothDevice newDevice = new CachedBluetoothDevice(mContext, adapter,
             profileManager, device);
-        mCachedDevices.add(newDevice);
+        synchronized (mCachedDevices) {
+            mCachedDevices.add(newDevice);
+        }
         return newDevice;
     }
 
@@ -110,6 +112,10 @@
         return device.getAddress();
     }
 
+    public synchronized void clearCachedDevices() {
+        mCachedDevices.clear();
+    }
+
     public synchronized void onScanningStateChanged(boolean started) {
         if (!started) return;
 
diff --git a/src/com/android/settings/bluetooth/DeviceListPreferenceFragment.java b/src/com/android/settings/bluetooth/DeviceListPreferenceFragment.java
index f482ecd..e7208b5 100644
--- a/src/com/android/settings/bluetooth/DeviceListPreferenceFragment.java
+++ b/src/com/android/settings/bluetooth/DeviceListPreferenceFragment.java
@@ -167,6 +167,12 @@
      }
 
     void createDevicePreference(CachedBluetoothDevice cachedDevice) {
+        if (mDeviceListGroup == null) {
+            Log.w(TAG, "Trying to create a device preference before the list group/category "
+                    + "exists!");
+            return;
+        }
+
         BluetoothDevicePreference preference = new BluetoothDevicePreference(
                 getActivity(), cachedDevice);
 
diff --git a/src/com/android/settings/bluetooth/MessageAccessSettings.java b/src/com/android/settings/bluetooth/MessageAccessSettings.java
deleted file mode 100644
index 913357c..0000000
--- a/src/com/android/settings/bluetooth/MessageAccessSettings.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * 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.
- */
-
-package com.android.settings.bluetooth;
-
-import android.accounts.Account;
-import android.accounts.AccountManager;
-import android.app.ActivityManagerNative;
-import android.content.Context;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.graphics.drawable.Drawable;
-import android.os.Bundle;
-import android.os.UserHandle;
-import android.preference.SwitchPreference;
-import android.preference.Preference;
-import android.preference.PreferenceGroup;
-import android.preference.PreferenceScreen;
-import android.provider.SearchIndexableResource;
-import android.util.Log;
-
-import com.android.settings.accounts.AuthenticatorHelper;
-import com.android.settings.R;
-import com.android.settings.SettingsPreferenceFragment;
-import com.android.settings.Utils;
-import com.android.settings.search.BaseSearchIndexProvider;
-import com.android.settings.search.Indexable;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class MessageAccessSettings extends SettingsPreferenceFragment
-        implements AuthenticatorHelper.OnAccountsUpdateListener, Indexable {
-    private static final String TAG = "MessageAccessSettings";
-    private static final String GMAIL_PACKAGE_NAME = "com.google.android.gm";
-    private static final String EMAIL_PACKAGE_NAME = "com.google.android.email";
-
-    private Account[] mAccounts;
-    private UserHandle mUserHandle;
-    private PreferenceGroup mAvailableAccounts;
-
-    @Override
-    public void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-
-        // TODO: Define behavior for managed profile. See: http://b/16287773
-        mUserHandle = new UserHandle(UserHandle.myUserId());
-
-        addPreferencesFromResource(R.xml.bluetooth_message_access);
-    }
-
-    @Override
-    public void onResume() {
-        super.onResume();
-        initPreferences();
-    }
-
-    @Override
-    public void onAccountsUpdate(final UserHandle userHandle) {
-        mAccounts = AccountManager.get(getActivity()).getAccountsAsUser(
-                mUserHandle.getIdentifier());
-
-        final int mAccountsSize = mAccounts.length;
-        for (int i = 0; i < mAccountsSize; ++i){
-            Log.d(TAG, String.format("account.type = %s\n", mAccounts[i].type));
-        }
-    }
-
-    /**
-     * Retrieves the email icon for a given account's email preference
-     *
-     * @param accountPref The user's account to retrieve the icon from.
-     *
-     * @return The drawable representing the icon of the user's email preference
-     **/
-    private Drawable getIcon(AccountPreference accountPref){
-        Drawable icon = null;
-
-        // Currently only two types of icons are allowed.
-        final String packageName = accountPref.account.type.equals("com.google")
-                ? GMAIL_PACKAGE_NAME : EMAIL_PACKAGE_NAME;
-
-        try{
-            icon = getPackageManager().getApplicationIcon(packageName);
-        }catch(NameNotFoundException nnfe){
-            icon = null;
-        }
-
-        return icon;
-    }
-
-    private void initPreferences() {
-        final PreferenceScreen preferenceScreen = getPreferenceScreen();
-        mAvailableAccounts = (PreferenceGroup)preferenceScreen.findPreference("accounts");
-        mAccounts = AccountManager.get(getActivity()).getAccountsAsUser(
-                mUserHandle.getIdentifier());
-
-        final int mAccountsSize = mAccounts.length;
-        for (int i = 0; i < mAccountsSize; ++i){
-            AccountPreference accountPref = new AccountPreference(getActivity(), mAccounts[i]);
-            Drawable icon = getIcon(accountPref);
-            if (icon != null){
-                accountPref.setIcon(icon);
-            }
-            mAvailableAccounts.addPreference(accountPref);
-        }
-    }
-
-    private class AccountPreference extends SwitchPreference
-            implements Preference.OnPreferenceChangeListener{
-        private Account account;
-
-        AccountPreference(Context context, Account account){
-            super(context);
-            this.account = account;
-            setTitle(account.type);
-            setSummary(account.name);
-
-            setOnPreferenceChangeListener(this);
-        }
-
-        @Override
-        public boolean onPreferenceChange(Preference preference, Object val) {
-            if (preference instanceof AccountPreference){
-                final AccountPreference accountPref = (AccountPreference) preference;
-
-                if (((Boolean)val).booleanValue()){
-                    // Enable paired deviced to connect, fill in once API is available
-                    Log.w(TAG, String.format(
-                                "User has turned on '%s' for Bluetooth message access.",
-                                accountPref.account.name));
-                } else {
-                    // Disable paired deviced to connect, fill in once API is available
-                    Log.w(TAG, String.format(
-                                "User has turned off '%s' for Bluetooth message access.",
-                                accountPref.account.name));
-                }
-            }
-            return true;
-        }
-    }
-
-    public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
-        new BaseSearchIndexProvider() {
-            @Override
-            public List<SearchIndexableResource> getXmlResourcesToIndex(
-                    Context context, boolean enabled) {
-                List<SearchIndexableResource> indexables = new ArrayList<SearchIndexableResource>();
-                SearchIndexableResource indexable = new SearchIndexableResource(context);
-                indexable.xmlResId = R.xml.bluetooth_message_access;
-                indexables.add(indexable);
-                return indexables;
-            }
-        };
-}
diff --git a/src/com/android/settings/fuelgauge/BatteryHistoryChart.java b/src/com/android/settings/fuelgauge/BatteryHistoryChart.java
index d88c516..9d3edd5 100644
--- a/src/com/android/settings/fuelgauge/BatteryHistoryChart.java
+++ b/src/com/android/settings/fuelgauge/BatteryHistoryChart.java
@@ -86,7 +86,7 @@
 
         void addTick(int x, int bin) {
             if (bin != mLastBin && mNumTicks < mTicks.length) {
-                mTicks[mNumTicks] = x | bin << CHART_DATA_BIN_SHIFT;
+                mTicks[mNumTicks] = (x&CHART_DATA_X_MASK) | (bin<<CHART_DATA_BIN_SHIFT);
                 mNumTicks++;
                 mLastBin = bin;
             }
@@ -540,6 +540,7 @@
         }
         mDrainString = "";
         mChargeDurationString = "";
+        setContentDescription(mChargeLabelString);
 
         int pos = 0;
         int lastInteresting = 0;
@@ -804,6 +805,9 @@
                 }
                 if (curWalltime != 0 && rec.isDeltaData()) {
                     x = mLevelLeft + (int)(((curWalltime-walltimeStart)*levelWidth)/walltimeChange);
+                    if (x < 0) {
+                        x = 0;
+                    }
                     if (false) {
                         StringBuilder sb = new StringBuilder(128);
                         sb.append("walloff=");
@@ -984,6 +988,9 @@
         } else {
             // Figure out where the actual data ends on the screen.
             x = mLevelLeft + (int)(((mEndDataWallTime-walltimeStart)*levelWidth)/walltimeChange);
+            if (x < 0) {
+                x = 0;
+            }
         }
 
         finishPaths(x, h, levelh, startX, lastY, curLevelPath, lastX,
diff --git a/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java b/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java
index 1601cd0..c8b86ae 100644
--- a/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java
+++ b/src/com/android/settings/inputmethod/InputMethodAndLanguageSettings.java
@@ -88,14 +88,6 @@
     // false: on ICS or later
     private static final boolean SHOW_INPUT_METHOD_SWITCHER_SETTINGS = false;
 
-    private static final String[] sSystemSettingNames = {
-        System.TEXT_AUTO_REPLACE, System.TEXT_AUTO_CAPS, System.TEXT_AUTO_PUNCTUATE,
-    };
-
-    private static final String[] sHardKeyboardKeys = {
-        "auto_replace", "auto_caps", "auto_punctuate",
-    };
-
     private int mDefaultInputMethodSelectorVisibility = 0;
     private ListPreference mShowInputMethodSelectorPref;
     private PreferenceCategory mKeyboardSettingsCategory;
@@ -274,16 +266,6 @@
             }
         }
 
-        // Hard keyboard
-        if (!mHardKeyboardPreferenceList.isEmpty()) {
-            for (int i = 0; i < sHardKeyboardKeys.length; ++i) {
-                CheckBoxPreference chkPref = (CheckBoxPreference)
-                        mHardKeyboardCategory.findPreference(sHardKeyboardKeys[i]);
-                chkPref.setChecked(
-                        System.getInt(getContentResolver(), sSystemSettingNames[i], 1) > 0);
-            }
-        }
-
         updateInputDevices();
 
         // Refresh internal states in mInputMethodSettingValues to keep the latest
@@ -339,15 +321,6 @@
             }
         } else if (preference instanceof CheckBoxPreference) {
             final CheckBoxPreference chkPref = (CheckBoxPreference) preference;
-            if (!mHardKeyboardPreferenceList.isEmpty()) {
-                for (int i = 0; i < sHardKeyboardKeys.length; ++i) {
-                    if (chkPref == mHardKeyboardCategory.findPreference(sHardKeyboardKeys[i])) {
-                        System.putInt(getContentResolver(), sSystemSettingNames[i],
-                                chkPref.isChecked() ? 1 : 0);
-                        return true;
-                    }
-                }
-            }
             if (chkPref == mGameControllerCategory.findPreference("vibrate_input_devices")) {
                 System.putInt(getContentResolver(), Settings.System.VIBRATE_INPUT_DEVICES,
                         chkPref.isChecked() ? 1 : 0);
@@ -564,35 +537,33 @@
 
     private void updateHardKeyboards() {
         mHardKeyboardPreferenceList.clear();
-        if (getResources().getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY) {
-            final int[] devices = InputDevice.getDeviceIds();
-            for (int i = 0; i < devices.length; i++) {
-                InputDevice device = InputDevice.getDevice(devices[i]);
-                if (device != null
-                        && !device.isVirtual()
-                        && device.isFullKeyboard()) {
-                    final InputDeviceIdentifier identifier = device.getIdentifier();
-                    final String keyboardLayoutDescriptor =
-                            mIm.getCurrentKeyboardLayoutForInputDevice(identifier);
-                    final KeyboardLayout keyboardLayout = keyboardLayoutDescriptor != null ?
-                            mIm.getKeyboardLayout(keyboardLayoutDescriptor) : null;
+        final int[] devices = InputDevice.getDeviceIds();
+        for (int i = 0; i < devices.length; i++) {
+            InputDevice device = InputDevice.getDevice(devices[i]);
+            if (device != null
+                    && !device.isVirtual()
+                    && device.isFullKeyboard()) {
+                final InputDeviceIdentifier identifier = device.getIdentifier();
+                final String keyboardLayoutDescriptor =
+                    mIm.getCurrentKeyboardLayoutForInputDevice(identifier);
+                final KeyboardLayout keyboardLayout = keyboardLayoutDescriptor != null ?
+                    mIm.getKeyboardLayout(keyboardLayoutDescriptor) : null;
 
-                    final PreferenceScreen pref = new PreferenceScreen(getActivity(), null);
-                    pref.setTitle(device.getName());
-                    if (keyboardLayout != null) {
-                        pref.setSummary(keyboardLayout.toString());
-                    } else {
-                        pref.setSummary(R.string.keyboard_layout_default_label);
-                    }
-                    pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
-                        @Override
-                        public boolean onPreferenceClick(Preference preference) {
-                            showKeyboardLayoutDialog(identifier);
-                            return true;
-                        }
-                    });
-                    mHardKeyboardPreferenceList.add(pref);
+                final PreferenceScreen pref = new PreferenceScreen(getActivity(), null);
+                pref.setTitle(device.getName());
+                if (keyboardLayout != null) {
+                    pref.setSummary(keyboardLayout.toString());
+                } else {
+                    pref.setSummary(R.string.keyboard_layout_default_label);
                 }
+                pref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
+                    @Override
+                    public boolean onPreferenceClick(Preference preference) {
+                        showKeyboardLayoutDialog(identifier);
+                        return true;
+                    }
+                });
+                mHardKeyboardPreferenceList.add(pref);
             }
         }
 
@@ -702,8 +673,8 @@
         public List<SearchIndexableRaw> getRawDataToIndex(Context context, boolean enabled) {
             List<SearchIndexableRaw> indexables = new ArrayList<>();
 
-            Resources resources = context.getResources();
-            String screenTitle = context.getString(R.string.language_keyboard_settings_title);
+            final Resources resources = context.getResources();
+            final String screenTitle = context.getString(R.string.language_keyboard_settings_title);
 
             // Locale picker.
             if (context.getAssets().getLocales().length > 1) {
@@ -795,116 +766,82 @@
             // Hard keyboards
             InputManager inputManager = (InputManager) context.getSystemService(
                     Context.INPUT_SERVICE);
-            if (resources.getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY) {
-                boolean hasHardKeyboards = false;
+            boolean hasHardKeyboards = false;
 
-                final int[] devices = InputDevice.getDeviceIds();
-                for (int i = 0; i < devices.length; i++) {
-                    InputDevice device = InputDevice.getDevice(devices[i]);
-                    if (device == null || device.isVirtual() || !device.isFullKeyboard()) {
-                        continue;
-                    }
-
-                    hasHardKeyboards = true;
-
-                    InputDeviceIdentifier identifier = device.getIdentifier();
-                    String keyboardLayoutDescriptor =
-                            inputManager.getCurrentKeyboardLayoutForInputDevice(identifier);
-                    KeyboardLayout keyboardLayout = keyboardLayoutDescriptor != null ?
-                            inputManager.getKeyboardLayout(keyboardLayoutDescriptor) : null;
-
-                    String summary;
-                    if (keyboardLayout != null) {
-                        summary = keyboardLayout.toString();
-                    } else {
-                        summary = context.getString(R.string.keyboard_layout_default_label);
-                    }
-
-                    indexable = new SearchIndexableRaw(context);
-                    indexable.key = device.getName();
-                    indexable.title = device.getName();
-                    indexable.summaryOn = summary;
-                    indexable.summaryOff = summary;
-                    indexable.screenTitle = screenTitle;
-                    indexables.add(indexable);
+            final int[] devices = InputDevice.getDeviceIds();
+            for (int i = 0; i < devices.length; i++) {
+                InputDevice device = InputDevice.getDevice(devices[i]);
+                if (device == null || device.isVirtual() || !device.isFullKeyboard()) {
+                    continue;
                 }
 
-                if (hasHardKeyboards) {
-                    // Hard keyboard category.
-                    indexable = new SearchIndexableRaw(context);
-                    indexable.key = "builtin_keyboard_settings";
-                    indexable.title = context.getString(
-                            R.string.builtin_keyboard_settings_title);
-                    indexable.screenTitle = screenTitle;
-                    indexables.add(indexable);
+                hasHardKeyboards = true;
 
-                    // Auto replace.
-                    indexable = new SearchIndexableRaw(context);
-                    indexable.key = "auto_replace";
-                    indexable.title = context.getString(R.string.auto_replace);
-                    indexable.summaryOn = context.getString(R.string.auto_replace_summary);
-                    indexable.summaryOff = context.getString(R.string.auto_replace_summary);
-                    indexable.screenTitle = screenTitle;
-                    indexables.add(indexable);
+                InputDeviceIdentifier identifier = device.getIdentifier();
+                String keyboardLayoutDescriptor =
+                        inputManager.getCurrentKeyboardLayoutForInputDevice(identifier);
+                KeyboardLayout keyboardLayout = keyboardLayoutDescriptor != null ?
+                        inputManager.getKeyboardLayout(keyboardLayoutDescriptor) : null;
 
-                    // Auto caps.
-                    indexable = new SearchIndexableRaw(context);
-                    indexable.key = "auto_caps";
-                    indexable.title = context.getString(R.string.auto_caps);
-                    indexable.summaryOn = context.getString(R.string.auto_caps_summary);
-                    indexable.summaryOff = context.getString(R.string.auto_caps_summary);
-                    indexable.screenTitle = screenTitle;
-                    indexables.add(indexable);
-
-                    // Auto punctuate.
-                    indexable = new SearchIndexableRaw(context);
-                    indexable.key = "auto_punctuate";
-                    indexable.title = context.getString(R.string.auto_punctuate);
-                    indexable.summaryOn = context.getString(R.string.auto_punctuate_summary);
-                    indexable.summaryOff = context.getString(R.string.auto_punctuate_summary);
-                    indexable.screenTitle = screenTitle;
-                    indexables.add(indexable);
+                String summary;
+                if (keyboardLayout != null) {
+                    summary = keyboardLayout.toString();
+                } else {
+                    summary = context.getString(R.string.keyboard_layout_default_label);
                 }
-            }
 
-            // Voice recognizers.
-            List<ResolveInfo> recognizers = context.getPackageManager()
-                    .queryIntentServices(new Intent(RecognitionService.SERVICE_INTERFACE),
-                            PackageManager.GET_META_DATA);
-
-            final int recognizerCount = recognizers.size();
-
-            // Recognizer settings.
-            if (recognizerCount > 0) {
                 indexable = new SearchIndexableRaw(context);
-                indexable.key = "recognizer_settings";
-                indexable.title = context.getString(R.string.recognizer_settings_title);
+                indexable.key = device.getName();
+                indexable.title = device.getName();
+                indexable.summaryOn = summary;
+                indexable.summaryOff = summary;
                 indexable.screenTitle = screenTitle;
                 indexables.add(indexable);
             }
 
-            if (recognizerCount > 1) {
-                // Recognizer chooser.
+            if (hasHardKeyboards) {
+                // Hard keyboard category.
                 indexable = new SearchIndexableRaw(context);
-                indexable.key = "recognizer_title";
-                indexable.title = context.getString(R.string.recognizer_title);
+                indexable.key = "builtin_keyboard_settings";
+                indexable.title = context.getString(
+                        R.string.builtin_keyboard_settings_title);
+                indexable.screenTitle = screenTitle;
+                indexables.add(indexable);
+
+                // Auto replace.
+                indexable = new SearchIndexableRaw(context);
+                indexable.key = "auto_replace";
+                indexable.title = context.getString(R.string.auto_replace);
+                indexable.summaryOn = context.getString(R.string.auto_replace_summary);
+                indexable.summaryOff = context.getString(R.string.auto_replace_summary);
+                indexable.screenTitle = screenTitle;
+                indexables.add(indexable);
+
+                // Auto caps.
+                indexable = new SearchIndexableRaw(context);
+                indexable.key = "auto_caps";
+                indexable.title = context.getString(R.string.auto_caps);
+                indexable.summaryOn = context.getString(R.string.auto_caps_summary);
+                indexable.summaryOff = context.getString(R.string.auto_caps_summary);
+                indexable.screenTitle = screenTitle;
+                indexables.add(indexable);
+
+                // Auto punctuate.
+                indexable = new SearchIndexableRaw(context);
+                indexable.key = "auto_punctuate";
+                indexable.title = context.getString(R.string.auto_punctuate);
+                indexable.summaryOn = context.getString(R.string.auto_punctuate_summary);
+                indexable.summaryOff = context.getString(R.string.auto_punctuate_summary);
                 indexable.screenTitle = screenTitle;
                 indexables.add(indexable);
             }
 
-            for (int i = 0; i < recognizerCount; i++) {
-                ResolveInfo recognizer = recognizers.get(i);
-
-                ServiceInfo serviceInfo = recognizer.serviceInfo;
-                ComponentName componentName = new ComponentName(serviceInfo.packageName,
-                        serviceInfo.name);
-
-                indexable = new SearchIndexableRaw(context);
-                indexable.key = componentName.flattenToString();
-                indexable.title = recognizer.loadLabel(context.getPackageManager()).toString();
-                indexable.screenTitle = screenTitle;
-                indexables.add(indexable);
-            }
+            // Voice input
+            indexable = new SearchIndexableRaw(context);
+            indexable.key = "voice_input_settings";
+            indexable.title = context.getString(R.string.voice_input_settings);
+            indexable.screenTitle = screenTitle;
+            indexables.add(indexable);
 
             // Text-to-speech.
             TtsEngines ttsEngines = new TtsEngines(context);
diff --git a/src/com/android/settings/search/Ranking.java b/src/com/android/settings/search/Ranking.java
index 44717c1..2c76002 100644
--- a/src/com/android/settings/search/Ranking.java
+++ b/src/com/android/settings/search/Ranking.java
@@ -30,7 +30,6 @@
 import com.android.settings.WirelessSettings;
 import com.android.settings.accessibility.AccessibilitySettings;
 import com.android.settings.bluetooth.BluetoothSettings;
-import com.android.settings.bluetooth.MessageAccessSettings;
 import com.android.settings.deviceinfo.Memory;
 import com.android.settings.fuelgauge.BatterySaverSettings;
 import com.android.settings.fuelgauge.PowerUsageSummary;
@@ -43,6 +42,7 @@
 import com.android.settings.print.PrintSettingsFragment;
 import com.android.settings.sim.SimSettings;
 import com.android.settings.users.UserSettings;
+import com.android.settings.voice.VoiceInputSettings;
 import com.android.settings.wifi.AdvancedWifiSettings;
 import com.android.settings.wifi.SavedAccessPointsWifiSettings;
 import com.android.settings.wifi.WifiSettings;
@@ -93,7 +93,6 @@
 
         // BT
         sRankMap.put(BluetoothSettings.class.getName(), RANK_BT);
-        sRankMap.put(MessageAccessSettings.class.getName(), RANK_BT);
 
         // SIM Cards
         sRankMap.put(SimSettings.class.getName(), RANK_SIM);
@@ -139,6 +138,7 @@
 
         // IMEs
         sRankMap.put(InputMethodAndLanguageSettings.class.getName(), RANK_IME);
+        sRankMap.put(VoiceInputSettings.class.getName(), RANK_IME);
 
         // Privacy
         sRankMap.put(PrivacySettings.class.getName(), RANK_PRIVACY);
diff --git a/src/com/android/settings/search/SearchIndexableResources.java b/src/com/android/settings/search/SearchIndexableResources.java
index a3d2b8d..5108da3 100644
--- a/src/com/android/settings/search/SearchIndexableResources.java
+++ b/src/com/android/settings/search/SearchIndexableResources.java
@@ -33,7 +33,6 @@
 import com.android.settings.WirelessSettings;
 import com.android.settings.accessibility.AccessibilitySettings;
 import com.android.settings.bluetooth.BluetoothSettings;
-import com.android.settings.bluetooth.MessageAccessSettings;
 import com.android.settings.deviceinfo.Memory;
 import com.android.settings.fuelgauge.BatterySaverSettings;
 import com.android.settings.fuelgauge.PowerUsageSummary;
@@ -46,6 +45,7 @@
 import com.android.settings.print.PrintSettingsFragment;
 import com.android.settings.sim.SimSettings;
 import com.android.settings.users.UserSettings;
+import com.android.settings.voice.VoiceInputSettings;
 import com.android.settings.wifi.AdvancedWifiSettings;
 import com.android.settings.wifi.SavedAccessPointsWifiSettings;
 import com.android.settings.wifi.WifiSettings;
@@ -92,17 +92,10 @@
         sResMap.put(SimSettings.class.getName(),
                 new SearchIndexableResource(
                         Ranking.getRankForClassName(SimSettings.class.getName()),
-                        R.xml.sim_settings,
+                        NO_DATA_RES_ID,
                         SimSettings.class.getName(),
                         R.drawable.ic_sim_sd));
 
-        sResMap.put(MessageAccessSettings.class.getName(),
-                new SearchIndexableResource(
-                        Ranking.getRankForClassName(MessageAccessSettings.class.getName()),
-                        NO_DATA_RES_ID,
-                        MessageAccessSettings.class.getName(),
-                        R.drawable.ic_settings_bluetooth2));
-
         sResMap.put(DataUsageSummary.class.getName(),
                 new SearchIndexableResource(
                         Ranking.getRankForClassName(DataUsageSummary.class.getName()),
@@ -230,6 +223,13 @@
                         InputMethodAndLanguageSettings.class.getName(),
                         R.drawable.ic_settings_language));
 
+        sResMap.put(VoiceInputSettings.class.getName(),
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(VoiceInputSettings.class.getName()),
+                        NO_DATA_RES_ID,
+                        VoiceInputSettings.class.getName(),
+                        R.drawable.ic_settings_language));
+
         sResMap.put(PrivacySettings.class.getName(),
                 new SearchIndexableResource(
                         Ranking.getRankForClassName(PrivacySettings.class.getName()),
diff --git a/src/com/android/settings/sim/SimSettings.java b/src/com/android/settings/sim/SimSettings.java
index 15c5548..9762c51 100644
--- a/src/com/android/settings/sim/SimSettings.java
+++ b/src/com/android/settings/sim/SimSettings.java
@@ -16,6 +16,7 @@
 
 package com.android.settings.sim;
 
+import android.provider.SearchIndexableResource;
 import com.android.settings.R;
 
 import android.app.AlertDialog;
@@ -55,6 +56,7 @@
 import com.android.internal.telephony.TelephonyIntents;
 import com.android.settings.RestrictedSettingsFragment;
 import com.android.settings.SettingsPreferenceFragment;
+import com.android.settings.Utils;
 import com.android.settings.notification.DropDownPreference;
 import com.android.settings.search.BaseSearchIndexProvider;
 import com.android.settings.search.Indexable;
@@ -86,18 +88,6 @@
     private SubInfoRecord mCalls = null;
     private SubInfoRecord mSMS = null;
 
-    /**
-     * Return whether or not the user should have a SIM Cards option in Settings.
-     * TODO: Change back to returning true if count is greater than one after testing.
-     * TODO: See bug 16533525.
-     */
-    public static boolean showSimCardScreen(Context context) {
-        final TelephonyManager tm =
-            (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
-
-        return tm.getSimCount() > 0;
-    }
-
     public SimSettings() {
         super(DISALLOW_CONFIG_SIM);
     }
@@ -369,4 +359,26 @@
             builder.create().show();
         }
     }
+
+    /**
+     * For search
+     */
+    public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
+            new BaseSearchIndexProvider() {
+                @Override
+                public List<SearchIndexableResource> getXmlResourcesToIndex(Context context,
+                        boolean enabled) {
+                    ArrayList<SearchIndexableResource> result =
+                            new ArrayList<SearchIndexableResource>();
+
+                    if (Utils.showSimCardTile(context)) {
+                        SearchIndexableResource sir = new SearchIndexableResource(context);
+                        sir.xmlResId = R.xml.sim_settings;
+                        result.add(sir);
+                    }
+
+                    return result;
+                }
+            };
+
 }
diff --git a/src/com/android/settings/tts/TtsEngineSettingsFragment.java b/src/com/android/settings/tts/TtsEngineSettingsFragment.java
index c8531fa..2449353 100644
--- a/src/com/android/settings/tts/TtsEngineSettingsFragment.java
+++ b/src/com/android/settings/tts/TtsEngineSettingsFragment.java
@@ -140,7 +140,7 @@
 
             mLocalePreference.setEntries(entries);
             mLocalePreference.setEntryValues(entryValues);
-            mLocalePreference.setValue(value.toString());
+            mLocalePreference.setValue(value != null ? value.toString() : null);
             mLocalePreference.setEnabled(entries.length > 0);
         }
 
diff --git a/src/com/android/settings/users/UserSettings.java b/src/com/android/settings/users/UserSettings.java
index aa5ec38..9ad34a9 100644
--- a/src/com/android/settings/users/UserSettings.java
+++ b/src/com/android/settings/users/UserSettings.java
@@ -741,6 +741,10 @@
         final boolean voiceCapable = Utils.isVoiceCapable(context);
         final ArrayList<Integer> missingIcons = new ArrayList<Integer>();
         for (UserInfo user : users) {
+            if (user.isManagedProfile()) {
+                // Managed profiles appear under Accounts Settings instead
+                continue;
+            }
             Preference pref;
             if (user.id == UserHandle.myUserId()) {
                 pref = mMePreference;
@@ -773,19 +777,11 @@
             if (!isInitialized(user)) {
                 if (user.isRestricted()) {
                     pref.setSummary(R.string.user_summary_restricted_not_set_up);
-                } else if (user.isManagedProfile()) {
-                    pref.setSummary(R.string.user_summary_managed_profile_not_set_up);
                 } else {
                     pref.setSummary(R.string.user_summary_not_set_up);
                 }
             } else if (user.isRestricted()) {
                 pref.setSummary(R.string.user_summary_restricted_profile);
-            } else if (user.isManagedProfile()) {
-                if (user.isEnabled()) {
-                    pref.setSummary(R.string.user_summary_managed_profile);
-                } else {
-                    pref.setSummary(R.string.user_summary_managed_profile_not_enabled);
-                }
             }
             if (user.iconPath != null) {
                 if (mUserIcons.get(user.id) == null) {
@@ -809,7 +805,19 @@
             mUserListCategory.addPreference(pref);
         }
 
-        if (!mIsGuest) {
+        boolean showGuestPreference = !mIsGuest;
+        // If user has DISALLOW_ADD_USER don't allow creating a guest either.
+        if (showGuestPreference && mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER)) {
+            showGuestPreference = false;
+            // If guest already exists, no user creation needed.
+            for (UserInfo user : users) {
+                if (user.isGuest()) {
+                    showGuestPreference = true;
+                    break;
+                }
+            }
+        }
+        if (showGuestPreference) {
             // Add a virtual Guest user for guest defaults
             Preference pref = new UserPreference(getActivity(), null,
                     UserPreference.USERID_GUEST_DEFAULTS,
@@ -916,8 +924,6 @@
                 if (!isInitialized(user)) {
                     mHandler.sendMessage(mHandler.obtainMessage(
                             MESSAGE_SETUP_USER, user.id, user.serialNumber));
-                } else if (!user.isManagedProfile()) {
-                    switchUserNow(userId);
                 }
             }
         } else if (pref == mAddUser) {
@@ -941,6 +947,10 @@
             }
         }
         // No guest user. Create one.
+        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER)) {
+            Log.i(TAG, "Blocking guest creation because it is restricted");
+            return;
+        }
         UserInfo guestUser = mUserManager.createGuest(getActivity(),
                     getResources().getString(R.string.user_guest));
         if (guestUser != null) {
diff --git a/src/com/android/settings/voice/VoiceInputSettings.java b/src/com/android/settings/voice/VoiceInputSettings.java
index 309c6e9..aa85024 100644
--- a/src/com/android/settings/voice/VoiceInputSettings.java
+++ b/src/com/android/settings/voice/VoiceInputSettings.java
@@ -16,18 +16,33 @@
 
 package com.android.settings.voice;
 
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.content.pm.ServiceInfo;
 import android.preference.Preference;
 import android.provider.Settings;
+import android.service.voice.VoiceInteractionService;
+import android.service.voice.VoiceInteractionServiceInfo;
+import android.speech.RecognitionService;
 import com.android.settings.R;
 import com.android.settings.SettingsPreferenceFragment;
+import com.android.settings.search.BaseSearchIndexProvider;
+import com.android.settings.search.Indexable;
+import com.android.settings.search.SearchIndexableRaw;
 import com.android.settings.voice.VoiceInputPreference.RadioButtonGroupState;
 
 import android.os.Bundle;
 import android.preference.PreferenceCategory;
 import android.widget.Checkable;
 
+import java.util.ArrayList;
+import java.util.List;
+
 public class VoiceInputSettings extends SettingsPreferenceFragment implements
-        Preference.OnPreferenceClickListener, RadioButtonGroupState {
+        Preference.OnPreferenceClickListener, RadioButtonGroupState, Indexable {
 
     private static final String TAG = "VoiceInputSettings";
     private static final boolean DBG = false;
@@ -160,4 +175,68 @@
         }
         return true;
     }
+
+    // For Search
+    public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
+        new BaseSearchIndexProvider() {
+
+            @Override
+            public List<SearchIndexableRaw> getRawDataToIndex(Context context,
+                    boolean enabled) {
+
+                List<SearchIndexableRaw> indexables = new ArrayList<>();
+
+                final String screenTitle = context.getString(R.string.voice_input_settings_title);
+
+                SearchIndexableRaw indexable = new SearchIndexableRaw(context);
+                indexable.key = "voice_service_preference_section_title";
+                indexable.title = context.getString(R.string.voice_service_preference_section_title);
+                indexable.screenTitle = screenTitle;
+                indexables.add(indexable);
+
+                final List<ResolveInfo> voiceInteractions =
+                        context.getPackageManager().queryIntentServices(
+                                new Intent(VoiceInteractionService.SERVICE_INTERFACE),
+                                PackageManager.GET_META_DATA);
+
+                final int countInteractions = voiceInteractions.size();
+                for (int i = 0; i < countInteractions; i++) {
+                    ResolveInfo info = voiceInteractions.get(i);
+                    VoiceInteractionServiceInfo visInfo = new VoiceInteractionServiceInfo(
+                            context.getPackageManager(), info.serviceInfo);
+                    if (visInfo.getParseError() != null) {
+                        continue;
+                    }
+                    indexables.add(getSearchIndexableRaw(context, info, screenTitle));
+                }
+
+                final List<ResolveInfo> recognitions =
+                        context.getPackageManager().queryIntentServices(
+                                new Intent(RecognitionService.SERVICE_INTERFACE),
+                                PackageManager.GET_META_DATA);
+
+                final int countRecognitions = recognitions.size();
+                for (int i = 0; i < countRecognitions; i++) {
+                    ResolveInfo info = recognitions.get(i);
+                    indexables.add(getSearchIndexableRaw(context, info, screenTitle));
+                }
+
+                return indexables;
+            }
+
+            private SearchIndexableRaw getSearchIndexableRaw(Context context,
+                    ResolveInfo info, String screenTitle) {
+
+                ServiceInfo serviceInfo = info.serviceInfo;
+                ComponentName componentName = new ComponentName(serviceInfo.packageName,
+                        serviceInfo.name);
+
+                SearchIndexableRaw indexable = new SearchIndexableRaw(context);
+                indexable.key = componentName.flattenToString();
+                indexable.title = info.loadLabel(context.getPackageManager()).toString();
+                indexable.screenTitle = screenTitle;
+
+                return indexable;
+            }
+        };
 }
diff --git a/src/com/android/settings/wifi/AccessPoint.java b/src/com/android/settings/wifi/AccessPoint.java
index b3fafa4..0ec1f13 100644
--- a/src/com/android/settings/wifi/AccessPoint.java
+++ b/src/com/android/settings/wifi/AccessPoint.java
@@ -520,6 +520,10 @@
         final Context context = getContext();
         updateIcon(getLevel(), context);
 
+        // Force new summary
+        setSummary(null);
+
+        // Update to new summary
         StringBuilder summary = new StringBuilder();
 
         if (mState != null) { // This is the active connection
@@ -551,22 +555,18 @@
                 summary.append(context.getString(R.string.wifi_remembered));
             }
 
-            if (security != SECURITY_NONE) {
-                String securityStrFormat;
-                if (summary.length() == 0) {
-                    securityStrFormat = context.getString(R.string.wifi_secured_first_item);
-                } else {
-                    securityStrFormat = context.getString(R.string.wifi_secured_second_item);
-                }
-            }
+// TODO: Wi-Fi team needs to decide what to do with this code.
+//            if (security != SECURITY_NONE) {
+//                String securityStrFormat;
+//                if (summary.length() == 0) {
+//                    securityStrFormat = context.getString(R.string.wifi_secured_first_item);
+//                } else {
+//                    securityStrFormat = context.getString(R.string.wifi_secured_second_item);
+//                }
+//            }
 
         }
 
-        // This is a workaround, see bug report...
-        if (summary.length() < 1) {
-            summary.append("   ");
-        }
-
         if (WifiSettings.mVerboseLogging > 0) {
             //add RSSI/band information for this config, what was seen up to 6 seconds ago
             //verbose WiFi Logging is only turned on thru developers settings
@@ -591,7 +591,11 @@
             }
         }
 
-        setSummary(summary.toString());
+        if (summary.length() > 0) {
+            setSummary(summary.toString());
+        } else {
+            showSummary = false;
+        }
     }
 
     /**
diff --git a/src/com/android/settings/wifi/AdvancedWifiSettings.java b/src/com/android/settings/wifi/AdvancedWifiSettings.java
index b7316d0..236aecd 100644
--- a/src/com/android/settings/wifi/AdvancedWifiSettings.java
+++ b/src/com/android/settings/wifi/AdvancedWifiSettings.java
@@ -20,6 +20,9 @@
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.net.NetworkScoreManager;
+import android.net.NetworkScorerAppManager;
+import android.net.NetworkScorerAppManager.NetworkScorerAppData;
 import android.net.wifi.WifiInfo;
 import android.net.wifi.WifiManager;
 import android.net.wifi.WpsInfo;
@@ -29,6 +32,7 @@
 import android.preference.Preference;
 import android.preference.Preference.OnPreferenceClickListener;
 import android.preference.PreferenceScreen;
+import android.preference.SwitchPreference;
 import android.provider.Settings;
 import android.provider.Settings.Global;
 import android.security.Credentials;
@@ -40,6 +44,8 @@
 import com.android.settings.SettingsPreferenceFragment;
 import com.android.settings.Utils;
 
+import java.util.Collection;
+
 public class AdvancedWifiSettings extends SettingsPreferenceFragment
         implements Preference.OnPreferenceChangeListener {
 
@@ -49,13 +55,12 @@
     private static final String KEY_FREQUENCY_BAND = "frequency_band";
     private static final String KEY_NOTIFY_OPEN_NETWORKS = "notify_open_networks";
     private static final String KEY_SLEEP_POLICY = "sleep_policy";
-    private static final String KEY_POOR_NETWORK_DETECTION = "wifi_poor_network_detection";
     private static final String KEY_SCAN_ALWAYS_AVAILABLE = "wifi_scan_always_available";
     private static final String KEY_INSTALL_CREDENTIALS = "install_credentials";
+    private static final String KEY_WIFI_ASSISTANT = "wifi_assistant";
     private static final String KEY_WIFI_DIRECT = "wifi_direct";
     private static final String KEY_WPS_PUSH = "wps_push_button";
     private static final String KEY_WPS_PIN = "wps_pin_entry";
-    private static final String KEY_SUSPEND_OPTIMIZATIONS = "suspend_optimizations";
 
     private WifiManager mWifiManager;
 
@@ -102,27 +107,14 @@
     }
 
     private void initPreferences() {
-        CheckBoxPreference notifyOpenNetworks =
-            (CheckBoxPreference) findPreference(KEY_NOTIFY_OPEN_NETWORKS);
+        SwitchPreference notifyOpenNetworks =
+            (SwitchPreference) findPreference(KEY_NOTIFY_OPEN_NETWORKS);
         notifyOpenNetworks.setChecked(Settings.Global.getInt(getContentResolver(),
                 Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1);
         notifyOpenNetworks.setEnabled(mWifiManager.isWifiEnabled());
 
-        CheckBoxPreference poorNetworkDetection =
-            (CheckBoxPreference) findPreference(KEY_POOR_NETWORK_DETECTION);
-        if (poorNetworkDetection != null) {
-            if (Utils.isWifiOnly(getActivity())) {
-                getPreferenceScreen().removePreference(poorNetworkDetection);
-            } else {
-                poorNetworkDetection.setChecked(Global.getInt(getContentResolver(),
-                        Global.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED,
-                        WifiManager.DEFAULT_POOR_NETWORK_AVOIDANCE_ENABLED ?
-                        1 : 0) == 1);
-            }
-        }
-
-        CheckBoxPreference scanAlwaysAvailable =
-            (CheckBoxPreference) findPreference(KEY_SCAN_ALWAYS_AVAILABLE);
+        SwitchPreference scanAlwaysAvailable =
+            (SwitchPreference) findPreference(KEY_SCAN_ALWAYS_AVAILABLE);
         scanAlwaysAvailable.setChecked(Global.getInt(getContentResolver(),
                     Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1);
 
@@ -133,7 +125,20 @@
         Preference pref = findPreference(KEY_INSTALL_CREDENTIALS);
         pref.setIntent(intent);
 
-        Intent wifiDirectIntent = new Intent(getActivity(),
+        final Context context = getActivity();
+        NetworkScorerAppData scorer = WifiSettings.getWifiAssistantApp(context);
+        SwitchPreference wifiAssistant = (SwitchPreference)findPreference(KEY_WIFI_ASSISTANT);
+        if (scorer != null) {
+            final boolean checked = NetworkScorerAppManager.getActiveScorer(context) != null;
+            wifiAssistant.setSummary(getResources().getString(
+                    R.string.wifi_automatically_manage_summary, scorer.mScorerName));
+            wifiAssistant.setOnPreferenceChangeListener(this);
+            wifiAssistant.setChecked(checked);
+        } else {
+            getPreferenceScreen().removePreference(wifiAssistant);
+        }
+
+        Intent wifiDirectIntent = new Intent(context,
                 com.android.settings.Settings.WifiP2pSettingsActivity.class);
         Preference wifiDirectPref = findPreference(KEY_WIFI_DIRECT);
         wifiDirectPref.setIntent(wifiDirectIntent);
@@ -142,7 +147,7 @@
         Preference wpsPushPref = findPreference(KEY_WPS_PUSH);
         wpsPushPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                 public boolean onPreferenceClick(Preference arg0) {
-                    WpsDialog wpsDialog = new WpsDialog(getActivity(), WpsInfo.PBC);
+                    WpsDialog wpsDialog = new WpsDialog(context, WpsInfo.PBC);
                     wpsDialog.show();
                     return true;
                 }
@@ -152,17 +157,12 @@
         Preference wpsPinPref = findPreference(KEY_WPS_PIN);
         wpsPinPref.setOnPreferenceClickListener(new OnPreferenceClickListener(){
                 public boolean onPreferenceClick(Preference arg0) {
-                    WpsDialog wpsDialog = new WpsDialog(getActivity(), WpsInfo.DISPLAY);
+                    WpsDialog wpsDialog = new WpsDialog(context, WpsInfo.DISPLAY);
                     wpsDialog.show();
                     return true;
                 }
         });
 
-        CheckBoxPreference suspendOptimizations =
-            (CheckBoxPreference) findPreference(KEY_SUSPEND_OPTIMIZATIONS);
-        suspendOptimizations.setChecked(Global.getInt(getContentResolver(),
-                Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED, 1) == 1);
-
         ListPreference frequencyPref = (ListPreference) findPreference(KEY_FREQUENCY_BAND);
 
         if (mWifiManager.isDualBandSupported()) {
@@ -183,7 +183,7 @@
 
         ListPreference sleepPolicyPref = (ListPreference) findPreference(KEY_SLEEP_POLICY);
         if (sleepPolicyPref != null) {
-            if (Utils.isWifiOnly(getActivity())) {
+            if (Utils.isWifiOnly(context)) {
                 sleepPolicyPref.setEntries(R.array.wifi_sleep_policy_entries_wifi_only);
             }
             sleepPolicyPref.setOnPreferenceChangeListener(this);
@@ -228,19 +228,11 @@
         if (KEY_NOTIFY_OPEN_NETWORKS.equals(key)) {
             Global.putInt(getContentResolver(),
                     Settings.Global.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
-                    ((CheckBoxPreference) preference).isChecked() ? 1 : 0);
-        } else if (KEY_POOR_NETWORK_DETECTION.equals(key)) {
-            Global.putInt(getContentResolver(),
-                    Global.WIFI_WATCHDOG_POOR_NETWORK_TEST_ENABLED,
-                    ((CheckBoxPreference) preference).isChecked() ? 1 : 0);
-        } else if (KEY_SUSPEND_OPTIMIZATIONS.equals(key)) {
-            Global.putInt(getContentResolver(),
-                    Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED,
-                    ((CheckBoxPreference) preference).isChecked() ? 1 : 0);
+                    ((SwitchPreference) preference).isChecked() ? 1 : 0);
         } else if (KEY_SCAN_ALWAYS_AVAILABLE.equals(key)) {
             Global.putInt(getContentResolver(),
                     Global.WIFI_SCAN_ALWAYS_AVAILABLE,
-                    ((CheckBoxPreference) preference).isChecked() ? 1 : 0);
+                    ((SwitchPreference) preference).isChecked() ? 1 : 0);
         } else {
             return super.onPreferenceTreeClick(screen, preference);
         }
@@ -249,6 +241,7 @@
 
     @Override
     public boolean onPreferenceChange(Preference preference, Object newValue) {
+        final Context context = getActivity();
         String key = preference.getKey();
 
         if (KEY_FREQUENCY_BAND.equals(key)) {
@@ -257,10 +250,32 @@
                 mWifiManager.setFrequencyBand(value, true);
                 updateFrequencyBandSummary(preference, value);
             } catch (NumberFormatException e) {
-                Toast.makeText(getActivity(), R.string.wifi_setting_frequency_band_error,
+                Toast.makeText(context, R.string.wifi_setting_frequency_band_error,
                         Toast.LENGTH_SHORT).show();
                 return false;
             }
+        } else if (KEY_WIFI_ASSISTANT.equals(key)) {
+            if (((Boolean)newValue).booleanValue() == false) {
+                NetworkScorerAppManager.setActiveScorer(context, null);
+                return true;
+            }
+
+            NetworkScorerAppData wifiAssistant = WifiSettings.getWifiAssistantApp(context);
+            Intent intent = new Intent();
+            if (wifiAssistant.mConfigurationActivityClassName != null) {
+                // App has a custom configuration activity; launch that.
+                // This custom activity will be responsible for launching the system
+                // dialog.
+                intent.setClassName(wifiAssistant.mPackageName,
+                        wifiAssistant.mConfigurationActivityClassName);
+            } else {
+                // Fall back on the system dialog.
+                intent.setAction(NetworkScoreManager.ACTION_CHANGE_ACTIVE);
+                intent.putExtra(NetworkScoreManager.EXTRA_PACKAGE_NAME,
+                        wifiAssistant.mPackageName);
+            }
+
+            startActivity(intent);
         }
 
         if (KEY_SLEEP_POLICY.equals(key)) {
@@ -270,7 +285,7 @@
                         Integer.parseInt(stringValue));
                 updateSleepPolicySummary(preference, stringValue);
             } catch (NumberFormatException e) {
-                Toast.makeText(getActivity(), R.string.wifi_setting_sleep_policy_error,
+                Toast.makeText(context, R.string.wifi_setting_sleep_policy_error,
                         Toast.LENGTH_SHORT).show();
                 return false;
             }
@@ -280,18 +295,19 @@
     }
 
     private void refreshWifiInfo() {
+        final Context context = getActivity();
         WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
 
         Preference wifiMacAddressPref = findPreference(KEY_MAC_ADDRESS);
         String macAddress = wifiInfo == null ? null : wifiInfo.getMacAddress();
         wifiMacAddressPref.setSummary(!TextUtils.isEmpty(macAddress) ? macAddress
-                : getActivity().getString(R.string.status_unavailable));
+                : context.getString(R.string.status_unavailable));
         wifiMacAddressPref.setSelectable(false);
 
         Preference wifiIpAddressPref = findPreference(KEY_CURRENT_IP_ADDRESS);
-        String ipAddress = Utils.getWifiIpAddresses(getActivity());
+        String ipAddress = Utils.getWifiIpAddresses(context);
         wifiIpAddressPref.setSummary(ipAddress == null ?
-                getActivity().getString(R.string.status_unavailable) : ipAddress);
+                context.getString(R.string.status_unavailable) : ipAddress);
         wifiIpAddressPref.setSelectable(false);
     }
 
diff --git a/src/com/android/settings/wifi/WifiSettings.java b/src/com/android/settings/wifi/WifiSettings.java
index e83cb06..5366d66 100644
--- a/src/com/android/settings/wifi/WifiSettings.java
+++ b/src/com/android/settings/wifi/WifiSettings.java
@@ -27,7 +27,6 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.SharedPreferences;
-import android.content.pm.PackageManager;
 import android.content.res.Resources;
 import android.content.res.TypedArray;
 import android.location.LocationManager;
@@ -45,11 +44,13 @@
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
+import android.os.Parcelable;
 import android.preference.Preference;
 import android.preference.PreferenceScreen;
 import android.util.Log;
 import android.view.ContextMenu;
 import android.view.ContextMenu.ContextMenuInfo;
+import android.view.LayoutInflater;
 import android.view.Menu;
 import android.view.MenuInflater;
 import android.view.MenuItem;
@@ -129,7 +130,6 @@
     private WifiManager.ActionListener mConnectListener;
     private WifiManager.ActionListener mSaveListener;
     private WifiManager.ActionListener mForgetListener;
-    private boolean mP2pSupported;
 
     private WifiEnabler mWifiEnabler;
     // An access point being editted is stored here.
@@ -156,7 +156,7 @@
     private boolean mDlgEdit;
     private AccessPoint mDlgAccessPoint;
     private Bundle mAccessPointSavedState;
-    private Preference mWifiAssistantPreference;
+    private View mWifiAssistantCard;
     private NetworkScorerAppData mWifiAssistantApp;
 
     /** verbose logging flag. this flag is set thru developer debugging options
@@ -165,52 +165,6 @@
 
     /* End of "used in Wifi Setup context" */
 
-    /** Holds the Wifi Assistant Card. */
-    private class WifiAssistantPreference extends Preference {
-        public WifiAssistantPreference() {
-            super(getActivity());
-            setLayoutResource(R.layout.wifi_assistant_card);
-        }
-
-        @Override
-        public void onBindView(View view) {
-            super.onBindView(view);
-            Button setup = (Button)view.findViewById(R.id.setup);
-            Button noThanks = (Button)view.findViewById(R.id.no_thanks_button);
-
-            if (setup != null && noThanks != null) {
-                setup.setOnClickListener(new OnClickListener() {
-                    @Override
-                    public void onClick(View v) {
-                        Intent intent = new Intent();
-                        if (mWifiAssistantApp.mConfigurationActivityClassName != null) {
-                            // App has a custom configuration activity; launch that.
-                            // This custom activity will be responsible for launching the system
-                            // dialog.
-                            intent.setClassName(mWifiAssistantApp.mPackageName,
-                                    mWifiAssistantApp.mConfigurationActivityClassName);
-                        } else {
-                            // Fall back on the system dialog.
-                            intent.setAction(NetworkScoreManager.ACTION_CHANGE_ACTIVE);
-                            intent.putExtra(NetworkScoreManager.EXTRA_PACKAGE_NAME,
-                                    mWifiAssistantApp.mPackageName);
-                        }
-                        startActivityForResult(intent, REQUEST_ENABLE_WIFI_ASSISTANT);
-                    }
-                });
-
-                noThanks.setOnClickListener(new OnClickListener() {
-                    @Override
-                    public void onClick(View v) {
-                        setWifiAssistantTimeout();
-                        getPreferenceScreen().removePreference(WifiAssistantPreference.this);
-                        mWifiAssistantApp = null;
-                    }
-                });
-            }
-        }
-    }
-
     /** A restricted multimap for use in constructAccessPoints */
     private static class Multimap<K,V> {
         private final HashMap<K,List<V>> store = new HashMap<K,List<V>>();
@@ -285,7 +239,7 @@
         mReceiver = new BroadcastReceiver() {
             @Override
             public void onReceive(Context context, Intent intent) {
-                handleEvent(context, intent);
+                handleEvent(intent);
             }
         };
 
@@ -296,7 +250,6 @@
     public void onActivityCreated(Bundle savedInstanceState) {
         super.onActivityCreated(savedInstanceState);
 
-        mP2pSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT);
         mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
 
         mConnectListener = new WifiManager.ActionListener() {
@@ -347,7 +300,7 @@
         if (savedInstanceState != null) {
             mDlgEdit = savedInstanceState.getBoolean(SAVE_DIALOG_EDIT_MODE);
             if (savedInstanceState.containsKey(SAVE_DIALOG_ACCESS_POINT_STATE)) {
-                mAccessPointSavedState = 
+                mAccessPointSavedState =
                     savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE);
             }
         }
@@ -384,7 +337,7 @@
         if (requestCode == REQUEST_ENABLE_WIFI_ASSISTANT) {
             if (resultCode == Activity.RESULT_OK) {
                 setWifiAssistantTimeout();
-                getPreferenceScreen().removePreference(mWifiAssistantPreference);
+                getListView().removeHeaderView(mWifiAssistantCard);
                 mWifiAssistantApp = null;
             }
         } else {
@@ -706,8 +659,9 @@
                     addMessagePreference(R.string.wifi_empty_list_wifi_on);
                 }
 
+                getListView().removeHeaderView(mWifiAssistantCard);
                 if (mWifiAssistantApp != null) {
-                    getPreferenceScreen().addPreference(mWifiAssistantPreference);
+                    getListView().addHeaderView(mWifiAssistantCard);
                 }
 
                 for (AccessPoint accessPoint : accessPoints) {
@@ -732,38 +686,88 @@
         }
     }
 
-    private boolean prepareWifiAssistantCard() {
-        if (mWifiAssistantPreference == null) {
-            mWifiAssistantPreference = new WifiAssistantPreference();
+    /**
+     * Returns the Network Scorer for the Wifi Assistant App.
+     */
+    public static NetworkScorerAppData getWifiAssistantApp(Context context) {
+        Collection<NetworkScorerAppData> scorers =
+                NetworkScorerAppManager.getAllValidScorers(context);
+
+        if (scorers.isEmpty()) {
+            return null;
         }
 
+        // TODO: b/13780935 - Implement proper scorer selection. Rather than pick the first
+        // scorer on the system, we should allow the user to select one.
+        return scorers.iterator().next();
+    }
+
+    private void prepareWifiAssistantCard() {
         if (getActivity() instanceof WifiPickerActivity) {
-            return false;
+            return;
         }
 
         if (NetworkScorerAppManager.getActiveScorer(getActivity()) != null) {
             // A scorer is already enabled; don't show the card.
-            return false;
+            return;
         }
 
         Collection<NetworkScorerAppData> scorers =
                 NetworkScorerAppManager.getAllValidScorers(getActivity());
         if (scorers.isEmpty()) {
             // No scorers are available to enable; don't show the card.
-            return false;
+            return;
         }
 
         SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences();
         long lastTimeoutEndTime = sharedPreferences.getLong(KEY_ASSISTANT_START_TIME, 0);
         long dismissTime = sharedPreferences.getLong(KEY_ASSISTANT_DISMISS_TIME, 0);
 
-        boolean shouldShow = ((System.currentTimeMillis() - lastTimeoutEndTime) > dismissTime);
-        if (shouldShow) {
-            // TODO: b/13780935 - Implement proper scorer selection. Rather than pick the first
-            // scorer on the system, we should allow the user to select one.
-            mWifiAssistantApp = scorers.iterator().next();
+        if ((System.currentTimeMillis() - lastTimeoutEndTime) <= dismissTime) {
+            return;
         }
-        return shouldShow;
+
+        // TODO: b/13780935 - Implement proper scorer selection. Rather than pick the first
+        // scorer on the system, we should allow the user to select one.
+        mWifiAssistantApp = scorers.iterator().next();
+
+        if (mWifiAssistantCard == null) {
+            mWifiAssistantCard = LayoutInflater.from(getActivity())
+                    .inflate(R.layout.wifi_assistant_card, getListView(), false);
+            Button setup = (Button) mWifiAssistantCard.findViewById(R.id.setup);
+            Button noThanks = (Button) mWifiAssistantCard.findViewById(R.id.no_thanks_button);
+
+            if (setup != null && noThanks != null) {
+                setup.setOnClickListener(new OnClickListener() {
+                    @Override
+                    public void onClick(View v) {
+                        Intent intent = new Intent();
+                        if (mWifiAssistantApp.mConfigurationActivityClassName != null) {
+                            // App has a custom configuration activity; launch that.
+                            // This custom activity will be responsible for launching the system
+                            // dialog.
+                            intent.setClassName(mWifiAssistantApp.mPackageName,
+                                    mWifiAssistantApp.mConfigurationActivityClassName);
+                        } else {
+                            // Fall back on the system dialog.
+                            intent.setAction(NetworkScoreManager.ACTION_CHANGE_ACTIVE);
+                            intent.putExtra(NetworkScoreManager.EXTRA_PACKAGE_NAME,
+                                    mWifiAssistantApp.mPackageName);
+                        }
+                        startActivityForResult(intent, REQUEST_ENABLE_WIFI_ASSISTANT);
+                    }
+                });
+
+                noThanks.setOnClickListener(new OnClickListener() {
+                    @Override
+                    public void onClick(View v) {
+                        setWifiAssistantTimeout();
+                        getListView().removeHeaderView(mWifiAssistantCard);
+                        mWifiAssistantApp = null;
+                    }
+                });
+            }
+        }
     }
 
     private void setWifiAssistantTimeout() {
@@ -861,7 +865,7 @@
         return accessPoints;
     }
 
-    private void handleEvent(Context context, Intent intent) {
+    private void handleEvent(Intent intent) {
         String action = intent.getAction();
         if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
             updateWifiState(intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
diff --git a/src/com/android/settings/wifi/WifiSetupActivity.java b/src/com/android/settings/wifi/WifiSetupActivity.java
index 3dd7a03..5452a03 100644
--- a/src/com/android/settings/wifi/WifiSetupActivity.java
+++ b/src/com/android/settings/wifi/WifiSetupActivity.java
@@ -218,6 +218,7 @@
         final Intent nextIntent = new Intent(ACTION_NEXT);
         nextIntent.putExtra(EXTRA_SCRIPT_URI, intent.getStringExtra(EXTRA_SCRIPT_URI));
         nextIntent.putExtra(EXTRA_ACTION_ID, intent.getStringExtra(EXTRA_ACTION_ID));
+        nextIntent.putExtra(EXTRA_THEME, intent.getStringExtra(EXTRA_THEME));
         nextIntent.putExtra(EXTRA_RESULT_CODE, resultCode);
         startActivityForResult(nextIntent, NEXT_REQUEST);
     }