Merge "Increase CHAR_LIMIT on Device Admins Settings message" into lmp-dev
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 0f7e381..2d2f9b4 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 -->
 
@@ -1508,7 +1519,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/layout/bluetooth_device_picker.xml b/res/layout/bluetooth_device_picker.xml
index 0a63e25..9d8ae86 100755
--- a/res/layout/bluetooth_device_picker.xml
+++ b/res/layout/bluetooth_device_picker.xml
@@ -15,14 +15,38 @@
 -->
 
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:orientation="vertical"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent">
+        android:gravity="center"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:orientation="vertical">
 
-    <fragment
-        android:id="@+id/bluetooth_device_picker_fragment"
-        android:name="com.android.settings.bluetooth.DevicePickerFragment"
-        android:layout_width="match_parent"
-        android:layout_height="0dip"
-        android:layout_weight="1" />
+    <LinearLayout android:id="@+id/dialog_layout"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:orientation="vertical"
+            android:paddingBottom="@dimen/bluetooth_dialog_padding"
+            style="@style/wifi_item" >
+
+            <TextView
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:text="@string/bluetooth_preference_paired_dialog_name_label"
+                    android:textDirection="locale"
+                    style="@style/wifi_item_label" />
+
+            <EditText android:id="@+id/name"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:inputType="textNoSuggestions"
+                    android:maxLength="@integer/bluetooth_name_length"
+                    android:singleLine="true"
+                    style="@style/wifi_item_edit_content" />
+
+            <fragment android:id="@+id/bluetooth_fragment_settings"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    class="com.android.settings.bluetooth.DeviceProfilesSettings" />
+
+    </LinearLayout>
+
 </LinearLayout>
diff --git a/res/layout/wifi_assistant_card.xml b/res/layout/wifi_assistant_card.xml
index a1917ba..529f9e9 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"
diff --git a/res/values/bools.xml b/res/values/bools.xml
index 137d4ce..0fdc396 100644
--- a/res/values/bools.xml
+++ b/res/values/bools.xml
@@ -19,9 +19,9 @@
     <bool name="has_dock_settings">false</bool>
     <!-- Whether there is a silent mode checkbox  -->
     <bool name="has_silent_mode">true</bool>
-    <!-- Whether the power control widget is enabled for this device. Should be overridden for 
-         specific product builds. -->
-    <bool name="has_powercontrol_widget">true</bool>
+    <!-- Whether the DEPRECATED power control widget is enabled for this
+         device. Should be overridden for specific product builds. -->
+    <bool name="has_powercontrol_widget">false</bool>
 
     <!-- Display additional System Update menu if true -->
     <bool name="config_additional_system_update_setting_enable">false</bool>
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index 62162d3..cb87bf0 100755
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -204,4 +204,8 @@
     <dimen name="checkbox_widget_min_width">58dip</dimen>
     <dimen name="checkbox_layout_padding">16dip</dimen>
 
+    <!-- Bluetooth Preferences -->
+    <dimen name="bluetooth_dialog_padding">8dip</dimen>
+    <integer name="bluetooth_name_length">32</integer>
+
 </resources>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 2d903cd..864d83c 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -264,9 +264,7 @@
     <!-- Bluetooth settings screen, menu item to scan for nearby bluetooth devices -->
     <string name="bluetooth_scan_for_devices">Scan for devices</string>
     <!-- Bluetooth settings screen, menu item to change this device's Bluetooth name. [CHAR LIMIT=30] -->
-    <string name="bluetooth_rename_device" product="tablet">Rename tablet</string>
-    <!-- Bluetooth settings screen, menu item to change this device's Bluetooth name. [CHAR LIMIT=30] -->
-    <string name="bluetooth_rename_device" product="default">Rename phone</string>
+    <string name="bluetooth_rename_device">Rename this device</string>
     <!-- Bluetooth settings screen, confirmation button for rename device dialog. [CHAR LIMIT=20] -->
     <string name="bluetooth_rename_button">Rename</string>
     <!-- Bluetooth settings.  Dialog title to confirm disconnecting from all profiles of a device. [CHAR LIMIT=30] -->
@@ -899,6 +897,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>
 
@@ -4559,6 +4578,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] -->
@@ -5160,8 +5183,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/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_device_advanced.xml b/res/xml/bluetooth_device_advanced.xml
index 8d2261c..75c89ca 100644
--- a/res/xml/bluetooth_device_advanced.xml
+++ b/res/xml/bluetooth_device_advanced.xml
@@ -18,19 +18,6 @@
         xmlns:android="http://schemas.android.com/apk/res/android"
         android:title="@string/bluetooth_device_advanced_title">
 
-    <EditTextPreference
-            android:key="rename_device"
-            android:title="@string/bluetooth_device_advanced_rename_device"
-            android:order="20"
-            android:persistent="false" />
-
-    <Preference
-            android:key="unpair"
-            android:title="@string/bluetooth_device_context_unpair"
-            android:order="40"
-            android:persistent="false"
-            />
-
     <PreferenceCategory
             android:key="profile_container"
             android:order="100"
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/DataUsageSummary.java b/src/com/android/settings/DataUsageSummary.java
index ec52128..009c758 100644
--- a/src/com/android/settings/DataUsageSummary.java
+++ b/src/com/android/settings/DataUsageSummary.java
@@ -1791,10 +1791,12 @@
         public static void show(DataUsageSummary parent) {
             if (!parent.isAdded()) return;
 
+            final NetworkPolicy policy = parent.mPolicyEditor.getPolicy(parent.mTemplate);
+            if (policy == null) return;
+
             final Resources res = parent.getResources();
             final CharSequence message;
-            final long minLimitBytes = (long) (
-                    parent.mPolicyEditor.getPolicy(parent.mTemplate).warningBytes * 1.2f);
+            final long minLimitBytes = (long) (policy.warningBytes * 1.2f);
             final long limitBytes;
 
             // TODO: customize default limits based on network template
diff --git a/src/com/android/settings/MasterClearConfirm.java b/src/com/android/settings/MasterClearConfirm.java
index 2ba1e7f..d14ad39 100644
--- a/src/com/android/settings/MasterClearConfirm.java
+++ b/src/com/android/settings/MasterClearConfirm.java
@@ -65,7 +65,10 @@
                     getActivity().getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
 
             if (pdbManager != null) {
-                pdbManager.wipe();
+                // if OEM unlock is enabled, this will be wiped during FR process.
+                if (!pdbManager.getOemUnlockEnabled()) {
+                    pdbManager.wipe();
+                }
             }
 
             if (mEraseSdCard) {
diff --git a/src/com/android/settings/SecuritySettings.java b/src/com/android/settings/SecuritySettings.java
index e5f7736..1fb5e13 100644
--- a/src/com/android/settings/SecuritySettings.java
+++ b/src/com/android/settings/SecuritySettings.java
@@ -47,7 +47,9 @@
 import android.util.Log;
 
 import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.TrustAgentUtils.TrustAgentComponentInfo;
 import com.android.settings.search.BaseSearchIndexProvider;
+import com.android.settings.search.Index;
 import com.android.settings.search.Indexable;
 import com.android.settings.search.SearchIndexableRaw;
 
@@ -76,6 +78,8 @@
     private static final String KEY_DEVICE_ADMIN_CATEGORY = "device_admin_category";
     private static final String KEY_LOCK_AFTER_TIMEOUT = "lock_after_timeout";
     private static final String KEY_OWNER_INFO_SETTINGS = "owner_info_settings";
+    private static final String KEY_ADVANCED_SECURITY = "advanced_security";
+    private static final String KEY_MANAGE_TRUST_AGENTS = "manage_trust_agents";
 
     private static final int SET_OR_CHANGE_LOCK_METHOD_REQUEST = 123;
     private static final int CONFIRM_EXISTING_FOR_BIOMETRIC_WEAK_IMPROVE_REQUEST = 124;
@@ -95,6 +99,9 @@
     private static final String KEY_TRUST_AGENT = "trust_agent";
     private static final String KEY_SCREEN_PINNING = "screen_pinning_settings";
 
+    // Only allow one trust agent on the platform.
+    private static final boolean ONLY_ONE_TRUST_AGENT = true;
+
     private DevicePolicyManager mDPM;
 
     private ChooseLockSettingsHelper mChooseLockSettingsHelper;
@@ -213,35 +220,23 @@
         // Trust Agent preferences
         PreferenceGroup securityCategory = (PreferenceGroup)
                 root.findPreference(KEY_SECURITY_CATEGORY);
-        if (securityCategory != null) {
-            PackageManager pm = getPackageManager();
-            List<ResolveInfo> resolveInfos = pm.queryIntentServices(TRUST_AGENT_INTENT,
-                    PackageManager.GET_META_DATA);
-            List<ComponentName> enabledTrustAgents = mLockPatternUtils.getEnabledTrustAgents();
-            if (enabledTrustAgents != null && !enabledTrustAgents.isEmpty()) {
-                for (ResolveInfo resolveInfo : resolveInfos) {
-                    if (resolveInfo.serviceInfo == null) continue;
-                    if (!TrustAgentUtils.checkProvidePermission(resolveInfo, pm)) continue;
-                    TrustAgentUtils.TrustAgentComponentInfo trustAgentComponentInfo =
-                            TrustAgentUtils.getSettingsComponent(pm, resolveInfo);
-                    if (trustAgentComponentInfo.componentName == null ||
-                            !enabledTrustAgents.contains(
-                                    TrustAgentUtils.getComponentName(resolveInfo)) ||
-                            TextUtils.isEmpty(trustAgentComponentInfo.title)) continue;
-                    Preference trustAgentPreference =
-                            new Preference(securityCategory.getContext());
-                    trustAgentPreference.setKey(KEY_TRUST_AGENT);
-                    trustAgentPreference.setTitle(trustAgentComponentInfo.title);
-                    trustAgentPreference.setSummary(trustAgentComponentInfo.summary);
-                    // Create intent for this preference.
-                    Intent intent = new Intent();
-                    intent.setComponent(trustAgentComponentInfo.componentName);
-                    intent.setAction(Intent.ACTION_MAIN);
-                    trustAgentPreference.setIntent(intent);
-                    // Add preference to the settings menu.
-                    securityCategory.addPreference(trustAgentPreference);
-                    break; // Only render the first one.
-                }
+        if (securityCategory != null && mLockPatternUtils.isSecure()) {
+            ArrayList<TrustAgentComponentInfo> agents =
+                    getActiveTrustAgents(getPackageManager(), mLockPatternUtils);
+            for (int i = 0; i < agents.size(); i++) {
+                final TrustAgentComponentInfo agent = agents.get(i);
+                Preference trustAgentPreference =
+                        new Preference(securityCategory.getContext());
+                trustAgentPreference.setKey(KEY_TRUST_AGENT);
+                trustAgentPreference.setTitle(agent.title);
+                trustAgentPreference.setSummary(agent.summary);
+                // Create intent for this preference.
+                Intent intent = new Intent();
+                intent.setComponent(agent.componentName);
+                intent.setAction(Intent.ACTION_MAIN);
+                trustAgentPreference.setIntent(intent);
+                // Add preference to the settings menu.
+                securityCategory.addPreference(trustAgentPreference);
             }
         }
 
@@ -341,9 +336,47 @@
             mToggleAppInstallation.setEnabled(false);
         }
 
+        // Advanced Security features
+        PreferenceGroup advancedCategory =
+                (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);
+        }
+
+        // The above preferences come and go based on security state, so we need to update
+        // the index. This call is expected to be fairly cheap, but we may want to do something
+        // smarter in the future.
+        Index.getInstance(getActivity())
+                .updateFromClassNameResource(SecuritySettings.class.getName(), true, true);
+
         return root;
     }
 
+    private static ArrayList<TrustAgentComponentInfo> getActiveTrustAgents(
+            PackageManager pm, LockPatternUtils utils) {
+        ArrayList<TrustAgentComponentInfo> result = new ArrayList<TrustAgentComponentInfo>();
+        List<ResolveInfo> resolveInfos = pm.queryIntentServices(TRUST_AGENT_INTENT,
+                PackageManager.GET_META_DATA);
+        List<ComponentName> enabledTrustAgents = utils.getEnabledTrustAgents();
+        if (enabledTrustAgents != null && !enabledTrustAgents.isEmpty()) {
+            for (int i = 0; i < resolveInfos.size(); i++) {
+                ResolveInfo resolveInfo = resolveInfos.get(i);
+                if (resolveInfo.serviceInfo == null) continue;
+                if (!TrustAgentUtils.checkProvidePermission(resolveInfo, pm)) continue;
+                TrustAgentComponentInfo trustAgentComponentInfo =
+                        TrustAgentUtils.getSettingsComponent(pm, resolveInfo);
+                if (trustAgentComponentInfo.componentName == null ||
+                        !enabledTrustAgents.contains(
+                                TrustAgentUtils.getComponentName(resolveInfo)) ||
+                        TextUtils.isEmpty(trustAgentComponentInfo.title)) continue;
+                result.add(trustAgentComponentInfo);
+                if (ONLY_ONE_TRUST_AGENT) break;
+            }
+        }
+        return result;
+    }
+
     private boolean isNonMarketAppsAllowed() {
         return Settings.Global.getInt(getContentResolver(),
                                       Settings.Global.INSTALL_NON_MARKET_APPS, 0) > 0;
@@ -626,7 +659,7 @@
     public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
             new SecuritySearchIndexProvider();
 
-    static private class SecuritySearchIndexProvider extends BaseSearchIndexProvider {
+    private static class SecuritySearchIndexProvider extends BaseSearchIndexProvider {
 
         boolean mIsPrimary;
 
@@ -716,6 +749,19 @@
                 result.add(data);
             }
 
+            // Advanced
+            final LockPatternUtils lockPatternUtils = new LockPatternUtils(context);
+            if (lockPatternUtils.isSecure()) {
+                ArrayList<TrustAgentComponentInfo> agents =
+                        getActiveTrustAgents(context.getPackageManager(), lockPatternUtils);
+                for (int i = 0; i < agents.size(); i++) {
+                    final TrustAgentComponentInfo agent = agents.get(i);
+                    data = new SearchIndexableRaw(context);
+                    data.title = agent.title;
+                    data.screenTitle = screenTitle;
+                    result.add(data);
+                }
+            }
             return result;
         }
 
@@ -745,6 +791,12 @@
                 keys.add(KEY_CREDENTIALS_MANAGER);
             }
 
+            // TrustAgent settings disappear when the user has no primary security.
+            if (!lockPatternUtils.isSecure()) {
+                keys.add(KEY_TRUST_AGENT);
+                keys.add(KEY_MANAGE_TRUST_AGENTS);
+            }
+
             return keys;
         }
     }
diff --git a/src/com/android/settings/SettingsActivity.java b/src/com/android/settings/SettingsActivity.java
index bb5ac00..bf0d9a1 100644
--- a/src/com/android/settings/SettingsActivity.java
+++ b/src/com/android/settings/SettingsActivity.java
@@ -1042,7 +1042,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/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/applications/ManageApplications.java b/src/com/android/settings/applications/ManageApplications.java
index 1889634..ac5a78a 100644
--- a/src/com/android/settings/applications/ManageApplications.java
+++ b/src/com/android/settings/applications/ManageApplications.java
@@ -74,7 +74,6 @@
 import com.android.settings.UserSpinnerAdapter;
 import com.android.settings.Settings.RunningServicesActivity;
 import com.android.settings.Settings.StorageUseActivity;
-import com.android.settings.UserSpinnerAdapter.UserDetails;
 import com.android.settings.applications.ApplicationsState.AppEntry;
 import com.android.settings.deviceinfo.StorageMeasurement;
 import com.android.settings.Utils;
@@ -142,6 +141,7 @@
     static final String TAG = "ManageApplications";
     static final boolean DEBUG = false;
 
+    private static final String EXTRA_LIST_TYPE = "currentListType";
     private static final String EXTRA_SORT_ORDER = "sortOrder";
     private static final String EXTRA_SHOW_BACKGROUND = "showBackground";
     private static final String EXTRA_DEFAULT_LIST_TYPE = "defaultListType";
@@ -467,7 +467,8 @@
 
     // These are for keeping track of activity and spinner switch state.
     private boolean mActivityResumed;
-    
+
+    private static final int LIST_TYPE_MISSING = -1;
     static final int LIST_TYPE_DOWNLOADED = 0;
     static final int LIST_TYPE_RUNNING = 1;
     static final int LIST_TYPE_SDCARD = 2;
@@ -954,9 +955,13 @@
 
         if (savedInstanceState == null) {
             // First time init: make sure view pager is showing the correct tab.
-            for (int i = 0; i < mTabs.size(); i++) {
+            int extraCurrentListType = getActivity().getIntent().getIntExtra(EXTRA_LIST_TYPE,
+                    LIST_TYPE_MISSING);
+            int currentListType = (extraCurrentListType != LIST_TYPE_MISSING)
+                    ? extraCurrentListType : mDefaultListType;
+            for (int i = 0; i < mNumTabs; i++) {
                 TabInfo tab = mTabs.get(i);
-                if (tab.mListType == mDefaultListType) {
+                if (tab.mListType == currentListType) {
                     mViewPager.setCurrentItem(i);
                     break;
                 }
@@ -1036,6 +1041,8 @@
         if (selectedUser.getIdentifier() != UserHandle.myUserId()) {
             Intent intent = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+            int currentTab = mViewPager.getCurrentItem();
+            intent.putExtra(EXTRA_LIST_TYPE, mTabs.get(currentTab).mListType);
             mContext.startActivityAsUser(intent, selectedUser);
             getActivity().finish();
         }
diff --git a/src/com/android/settings/bluetooth/BluetoothNameDialogFragment.java b/src/com/android/settings/bluetooth/BluetoothNameDialogFragment.java
index bf0356c..b80e42a 100644
--- a/src/com/android/settings/bluetooth/BluetoothNameDialogFragment.java
+++ b/src/com/android/settings/bluetooth/BluetoothNameDialogFragment.java
@@ -178,7 +178,6 @@
             mDeviceNameUpdated = true;
             mDeviceNameEdited = false;
             mDeviceNameView.setText(mLocalAdapter.getName());
-            getActivity().setTitle(mLocalAdapter.getName());
         }
     }
 
diff --git a/src/com/android/settings/bluetooth/BluetoothSettings.java b/src/com/android/settings/bluetooth/BluetoothSettings.java
index f1125bc..4b278ac 100755
--- a/src/com/android/settings/bluetooth/BluetoothSettings.java
+++ b/src/com/android/settings/bluetooth/BluetoothSettings.java
@@ -18,28 +18,39 @@
 
 import static android.os.UserManager.DISALLOW_CONFIG_BLUETOOTH;
 
+import android.app.Activity;
+import android.app.AlertDialog;
 import android.bluetooth.BluetoothAdapter;
 import android.bluetooth.BluetoothDevice;
 import android.content.BroadcastReceiver;
 import android.content.Context;
+import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.res.Resources;
+import android.content.SharedPreferences;
+import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
 import android.os.Bundle;
 import android.preference.Preference;
 import android.preference.PreferenceCategory;
+import android.preference.PreferenceFragment;
 import android.preference.PreferenceGroup;
 import android.preference.PreferenceScreen;
 import android.util.Log;
+import android.view.LayoutInflater;
 import android.view.Menu;
 import android.view.MenuInflater;
 import android.view.MenuItem;
 import android.view.View;
+import android.view.ViewGroup;
+import android.view.WindowManager;
+import android.widget.EditText;
 import android.widget.TextView;
 
 import com.android.settings.R;
 import com.android.settings.SettingsActivity;
 import com.android.settings.search.BaseSearchIndexProvider;
+import com.android.settings.search.Index;
 import com.android.settings.search.Indexable;
 import com.android.settings.search.SearchIndexableRaw;
 import com.android.settings.widget.SwitchBar;
@@ -64,6 +75,8 @@
     private static final String BTOPP_ACTION_OPEN_RECEIVED_FILES =
             "android.btopp.intent.action.OPEN_RECEIVED_FILES";
 
+    private static View mSettingsDialogView = null;
+
     private BluetoothEnabler mBluetoothEnabler;
 
     private PreferenceGroup mPairedDevicesCategory;
@@ -86,13 +99,14 @@
         public void onReceive(Context context, Intent intent) {
             String action = intent.getAction();
             if (action.equals(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED)) {
-                updateDeviceName();
+                updateDeviceName(context);
             }
         }
 
-        private void updateDeviceName() {
+        private void updateDeviceName(Context context) {
             if (mLocalAdapter.isEnabled() && mMyDevicePreference != null) {
-                mMyDevicePreference.setTitle(mLocalAdapter.getName());
+                mMyDevicePreference.setSummary(context.getResources().getString(
+                            R.string.bluetooth_is_visible_message, mLocalAdapter.getName()));
             }
         }
     };
@@ -371,20 +385,60 @@
     private final View.OnClickListener mDeviceProfilesListener = new View.OnClickListener() {
         public void onClick(View v) {
             // User clicked on advanced options icon for a device in the list
-            if (v.getTag() instanceof CachedBluetoothDevice) {
-                if (isUiRestricted()) return;
-
-                CachedBluetoothDevice device = (CachedBluetoothDevice) v.getTag();
-
-                Bundle args = new Bundle(1);
-                args.putParcelable(DeviceProfilesSettings.EXTRA_DEVICE, device.getDevice());
-
-                ((SettingsActivity) getActivity()).startPreferencePanel(
-                        DeviceProfilesSettings.class.getName(), args,
-                        R.string.bluetooth_device_advanced_title, null, null, 0);
-            } else {
-                Log.w(TAG, "onClick() called for other View: " + v); // TODO remove
+            if (!(v.getTag() instanceof CachedBluetoothDevice)) {
+                Log.w(TAG, "onClick() called for other View: " + v);
+                return;
             }
+
+            final CachedBluetoothDevice device = (CachedBluetoothDevice) v.getTag();
+            final Activity activity = getActivity();
+            DeviceProfilesSettings profileFrag = (DeviceProfilesSettings)activity.
+                getFragmentManager().findFragmentById(R.id.bluetooth_fragment_settings);
+
+            if (mSettingsDialogView != null){
+                ViewGroup parent = (ViewGroup) mSettingsDialogView.getParent();
+                if (parent != null) {
+                    parent.removeView(mSettingsDialogView);
+                }
+            }
+            if (profileFrag == null) {
+                LayoutInflater inflater = getActivity().getLayoutInflater();
+                mSettingsDialogView = inflater.inflate(R.layout.bluetooth_device_picker, null);
+                profileFrag = (DeviceProfilesSettings)activity.getFragmentManager()
+                .findFragmentById(R.id.bluetooth_fragment_settings);
+            }
+
+            final View dialogLayout = mSettingsDialogView;
+            AlertDialog.Builder settingsDialog = new AlertDialog.Builder(activity);
+            profileFrag.setDevice(device);
+            final EditText deviceName = (EditText)dialogLayout.findViewById(R.id.name);
+            deviceName.setText(device.getName(), TextView.BufferType.EDITABLE);
+            settingsDialog.setView(dialogLayout);
+            settingsDialog.setTitle(R.string.bluetooth_preference_paired_devices);
+            settingsDialog.setPositiveButton(R.string.okay,
+                    new DialogInterface.OnClickListener() {
+                @Override
+                public void onClick(DialogInterface dialog, int which) {
+                    EditText deviceName = (EditText)dialogLayout.findViewById(R.id.name);
+                    device.setName(deviceName.getText().toString());
+                }
+            });
+            final Context context = v.getContext();
+            settingsDialog.setNegativeButton(R.string.forget,
+                    new DialogInterface.OnClickListener() {
+                @Override
+                public void onClick(DialogInterface dialog, int which) {
+                    device.unpair();
+                    com.android.settings.bluetooth.Utils.updateSearchIndex(activity,
+                            BluetoothSettings.class.getName(), device.getName(),
+                            context.getResources().getString(R.string.bluetooth_settings),
+                            R.drawable.ic_settings_bluetooth2, false);
+                }
+            });
+
+            AlertDialog dialog = settingsDialog.create();
+            dialog.create();
+            dialog.show();
         }
     };
 
diff --git a/src/com/android/settings/bluetooth/DeviceProfilesSettings.java b/src/com/android/settings/bluetooth/DeviceProfilesSettings.java
index fb7668f..ea43bad 100755
--- a/src/com/android/settings/bluetooth/DeviceProfilesSettings.java
+++ b/src/com/android/settings/bluetooth/DeviceProfilesSettings.java
@@ -17,6 +17,7 @@
 package com.android.settings.bluetooth;
 
 import android.app.AlertDialog;
+import android.app.Fragment;
 import android.bluetooth.BluetoothDevice;
 import android.bluetooth.BluetoothProfile;
 import android.content.Context;
@@ -36,6 +37,7 @@
 import android.app.Dialog;
 import android.widget.Button;
 import android.text.Editable;
+
 import com.android.settings.R;
 import com.android.settings.SettingsPreferenceFragment;
 import com.android.settings.search.Index;
@@ -52,15 +54,14 @@
         implements CachedBluetoothDevice.Callback, Preference.OnPreferenceChangeListener {
     private static final String TAG = "DeviceProfilesSettings";
 
-    private static final String KEY_RENAME_DEVICE = "rename_device";
     private static final String KEY_PROFILE_CONTAINER = "profile_container";
     private static final String KEY_UNPAIR = "unpair";
     private static final String KEY_PBAP_SERVER = "PBAP Server";
 
     public static final String EXTRA_DEVICE = "device";
-    private RenameEditTextPreference mRenameDeviceNamePref;
-    private LocalBluetoothManager mManager;
+
     private CachedBluetoothDevice mCachedDevice;
+    private LocalBluetoothManager mManager;
     private LocalBluetoothProfileManager mProfileManager;
 
     private PreferenceGroup mProfileContainer;
@@ -72,66 +73,18 @@
     private AlertDialog mDisconnectDialog;
     private boolean mProfileGroupIsRemoved;
 
-    private class RenameEditTextPreference implements TextWatcher{
-        public void afterTextChanged(Editable s) {
-            Dialog d = mDeviceNamePref.getDialog();
-            if (d instanceof AlertDialog) {
-                ((AlertDialog) d).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(s.length() > 0);
-            }
-        }
-
-        // TextWatcher interface
-        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
-            // not used
-        }
-
-        // TextWatcher interface
-        public void onTextChanged(CharSequence s, int start, int before, int count) {
-            // not used
-        }
-    }
-
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
 
-        BluetoothDevice device;
-        if (savedInstanceState != null) {
-            device = savedInstanceState.getParcelable(EXTRA_DEVICE);
-        } else {
-            Bundle args = getArguments();
-            device = args.getParcelable(EXTRA_DEVICE);
-        }
-
         addPreferencesFromResource(R.xml.bluetooth_device_advanced);
         getPreferenceScreen().setOrderingAsAdded(false);
         mProfileContainer = (PreferenceGroup) findPreference(KEY_PROFILE_CONTAINER);
-        mDeviceNamePref = (EditTextPreference) findPreference(KEY_RENAME_DEVICE);
 
-        if (device == null) {
-            Log.w(TAG, "Activity started without a remote Bluetooth device");
-            finish();
-            return;  // TODO: test this failure path
-        }
-        mRenameDeviceNamePref = new RenameEditTextPreference();
         mManager = LocalBluetoothManager.getInstance(getActivity());
         CachedBluetoothDeviceManager deviceManager =
                 mManager.getCachedDeviceManager();
         mProfileManager = mManager.getProfileManager();
-        mCachedDevice = deviceManager.findDevice(device);
-        if (mCachedDevice == null) {
-            Log.w(TAG, "Device not found, cannot connect to it");
-            finish();
-            return;  // TODO: test this failure path
-        }
-
-        String deviceName = mCachedDevice.getName();
-        mDeviceNamePref.setSummary(deviceName);
-        mDeviceNamePref.setText(deviceName);
-        mDeviceNamePref.setOnPreferenceChangeListener(this);
-
-        // Add a preference for each profile
-        addPreferencesForProfiles();
     }
 
     @Override
@@ -141,6 +94,9 @@
             mDisconnectDialog.dismiss();
             mDisconnectDialog = null;
         }
+        if (mCachedDevice != null) {
+            mCachedDevice.unregisterCallback(this);
+        }
     }
 
     @Override
@@ -154,18 +110,13 @@
         super.onResume();
 
         mManager.setForegroundActivity(getActivity());
-        mCachedDevice.registerCallback(this);
-        if(mCachedDevice.getBondState() == BluetoothDevice.BOND_NONE)
-            finish();
-        refresh();
-        EditText et = mDeviceNamePref.getEditText();
-        if (et != null) {
-            et.addTextChangedListener(mRenameDeviceNamePref);
-            Dialog d = mDeviceNamePref.getDialog();
-            if (d instanceof AlertDialog) {
-                Button b = ((AlertDialog) d).getButton(AlertDialog.BUTTON_POSITIVE);
-                b.setEnabled(et.getText().length() > 0);
+        if (mCachedDevice != null) {
+            mCachedDevice.registerCallback(this);
+            if (mCachedDevice.getBondState() == BluetoothDevice.BOND_NONE) {
+                finish();
+                return;
             }
+            refresh();
         }
     }
 
@@ -173,11 +124,23 @@
     public void onPause() {
         super.onPause();
 
-        mCachedDevice.unregisterCallback(this);
+        if (mCachedDevice != null) {
+            mCachedDevice.unregisterCallback(this);
+        }
+
         mManager.setForegroundActivity(null);
     }
 
+    public void setDevice(CachedBluetoothDevice cachedDevice) {
+        mCachedDevice = cachedDevice;
+
+        mCachedDevice.registerCallback(this);
+        addPreferencesForProfiles();
+        refresh();
+    }
+
     private void addPreferencesForProfiles() {
+        mProfileContainer.removeAll();
         for (LocalBluetoothProfile profile : mCachedDevice.getConnectableProfiles()) {
             Preference pref = createProfilePreference(profile);
             mProfileContainer.addPreference(pref);
@@ -238,28 +201,6 @@
         return pref;
     }
 
-    @Override
-    public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) {
-        String key = preference.getKey();
-        if (key.equals(KEY_UNPAIR)) {
-            unpairDevice();
-            finish();
-            final Context context = preference.getContext();
-
-            SearchIndexableRaw data = new SearchIndexableRaw(context);
-            data.className = BluetoothSettings.class.getName();
-            data.title = mCachedDevice.getName();
-            data.screenTitle = context.getResources().getString(R.string.bluetooth_settings);
-            data.iconResId = R.drawable.ic_settings_bluetooth2;
-            data.enabled = false;
-
-            Index.getInstance(context).updateFromSearchIndexableData(data);
-            return true;
-        }
-
-        return super.onPreferenceTreeClick(screen, preference);
-    }
-
     public boolean onPreferenceChange(Preference preference, Object newValue) {
         if (preference == mDeviceNamePref) {
             mCachedDevice.setName((String) newValue);
@@ -331,14 +272,16 @@
                 mDisconnectDialog, disconnectListener, title, Html.fromHtml(message));
     }
 
+    @Override
     public void onDeviceAttributesChanged() {
         refresh();
     }
 
     private void refresh() {
-        String deviceName = mCachedDevice.getName();
-        mDeviceNamePref.setSummary(deviceName);
-        mDeviceNamePref.setText(deviceName);
+        final EditText deviceNameField = (EditText) getView().findViewById(R.id.name);
+        if (deviceNameField != null) {
+            deviceNameField.setText(mCachedDevice.getName());
+        }
 
         refreshProfiles();
     }
@@ -391,8 +334,4 @@
     private int getProfilePreferenceIndex(int profIndex) {
         return mProfileContainer.getOrder() + profIndex * 10;
     }
-
-    private void unpairDevice() {
-        mCachedDevice.unpair();
-    }
 }
diff --git a/src/com/android/settings/bluetooth/Utils.java b/src/com/android/settings/bluetooth/Utils.java
index 1970400..e9230de 100755
--- a/src/com/android/settings/bluetooth/Utils.java
+++ b/src/com/android/settings/bluetooth/Utils.java
@@ -24,6 +24,8 @@
 import android.widget.Toast;
 
 import com.android.settings.R;
+import com.android.settings.search.Index;
+import com.android.settings.search.SearchIndexableRaw;
 
 /**
  * Utils is a helper class that contains constants for various
@@ -101,4 +103,19 @@
             Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
         }
     }
+
+    /**
+     * Update the search Index for a specific class name and resources.
+     */
+    public static void updateSearchIndex(Context context, String className, String title,
+            String screenTitle, int iconResId, boolean enabled) {
+        SearchIndexableRaw data = new SearchIndexableRaw(context);
+        data.className = className;
+        data.title = title;
+        data.screenTitle = screenTitle;
+        data.iconResId = iconResId;
+        data.enabled = enabled;
+
+        Index.getInstance(context).updateFromSearchIndexableData(data);
+    }
 }
diff --git a/src/com/android/settings/fuelgauge/BatteryHistoryDetail.java b/src/com/android/settings/fuelgauge/BatteryHistoryDetail.java
index 248d471..63e4e13 100644
--- a/src/com/android/settings/fuelgauge/BatteryHistoryDetail.java
+++ b/src/com/android/settings/fuelgauge/BatteryHistoryDetail.java
@@ -18,31 +18,27 @@
 
 import android.app.Fragment;
 import android.content.Intent;
+import android.os.BatteryStats;
 import android.os.Bundle;
-import android.os.Parcel;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 
-import com.android.internal.os.BatteryStatsImpl;
+import com.android.internal.os.BatteryStatsHelper;
 import com.android.settings.R;
 
 public class BatteryHistoryDetail extends Fragment {
     public static final String EXTRA_STATS = "stats";
     public static final String EXTRA_BROADCAST = "broadcast";
 
-    private BatteryStatsImpl mStats;
+    private BatteryStats mStats;
     private Intent mBatteryBroadcast;
 
     @Override
     public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
-        byte[] data = getArguments().getByteArray(EXTRA_STATS);
-        Parcel parcel = Parcel.obtain();
-        parcel.unmarshall(data, 0, data.length);
-        parcel.setDataPosition(0);
-        mStats = com.android.internal.os.BatteryStatsImpl.CREATOR
-                .createFromParcel(parcel);
+        String histFile = getArguments().getString(EXTRA_STATS);
+        mStats = BatteryStatsHelper.statsFromFile(getActivity(), histFile);
         mBatteryBroadcast = getArguments().getParcelable(EXTRA_BROADCAST);
     }
     
diff --git a/src/com/android/settings/fuelgauge/BatteryHistoryPreference.java b/src/com/android/settings/fuelgauge/BatteryHistoryPreference.java
index 300b98f..e7326b1 100644
--- a/src/com/android/settings/fuelgauge/BatteryHistoryPreference.java
+++ b/src/com/android/settings/fuelgauge/BatteryHistoryPreference.java
@@ -47,8 +47,6 @@
         setLayoutResource(R.layout.preference_batteryhistory);
         mStats = stats;
         mBatteryBroadcast = batteryBroadcast;
-        // Make it non selectable
-        setSelectable(false);
     }
 
     BatteryStats getStats() {
diff --git a/src/com/android/settings/fuelgauge/PowerGaugePreference.java b/src/com/android/settings/fuelgauge/PowerGaugePreference.java
index 8157b5d..a558533 100644
--- a/src/com/android/settings/fuelgauge/PowerGaugePreference.java
+++ b/src/com/android/settings/fuelgauge/PowerGaugePreference.java
@@ -34,9 +34,9 @@
     private BatteryEntry mInfo;
     private int mProgress;
     private CharSequence mProgressText;
-    private final String mContentDescription;
+    private final CharSequence mContentDescription;
 
-    public PowerGaugePreference(Context context, Drawable icon, String contentDescription,
+    public PowerGaugePreference(Context context, Drawable icon, CharSequence contentDescription,
             BatteryEntry info) {
         super(context);
         setLayoutResource(R.layout.preference_app_percentage);
diff --git a/src/com/android/settings/fuelgauge/PowerUsageSummary.java b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
index e6534eb..ad8afa5 100644
--- a/src/com/android/settings/fuelgauge/PowerUsageSummary.java
+++ b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
@@ -26,7 +26,6 @@
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
-import android.os.Parcel;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.preference.Preference;
@@ -46,8 +45,6 @@
 import com.android.settings.SettingsActivity;
 
 import java.util.List;
-import java.util.ArrayList;
-import java.util.Collections;
 
 /**
  * Displays a list of apps and subsystems that consume power, ordered by how much power was
@@ -61,6 +58,8 @@
 
     private static final String KEY_APP_LIST = "app_list";
 
+    private static final String BATTERY_HISTORY_FILE = "tmp_bat_history.bin";
+
     private static final int MENU_STATS_TYPE = Menu.FIRST;
     private static final int MENU_STATS_REFRESH = Menu.FIRST + 1;
     private static final int MENU_BATTERY_SAVER = Menu.FIRST + 2;
@@ -116,6 +115,7 @@
     @Override
     public void onResume() {
         super.onResume();
+        BatteryStatsHelper.dropFile(getActivity(), BATTERY_HISTORY_FILE);
         updateBatteryStatus(getActivity().registerReceiver(mBatteryInfoReceiver,
                 new IntentFilter(Intent.ACTION_BATTERY_CHANGED)));
         if (mHandler.hasMessages(MSG_REFRESH_STATS)) {
@@ -151,11 +151,9 @@
     @Override
     public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
         if (preference instanceof BatteryHistoryPreference) {
-            Parcel hist = Parcel.obtain();
-            mStatsHelper.getStats().writeToParcelWithoutUids(hist, 0);
-            byte[] histData = hist.marshall();
+            mStatsHelper.storeStatsHistoryInFile(BATTERY_HISTORY_FILE);
             Bundle args = new Bundle();
-            args.putByteArray(BatteryHistoryDetail.EXTRA_STATS, histData);
+            args.putString(BatteryHistoryDetail.EXTRA_STATS, BATTERY_HISTORY_FILE);
             args.putParcelable(BatteryHistoryDetail.EXTRA_BROADCAST,
                     mStatsHelper.getBatteryBroadcast());
             SettingsActivity sa = (SettingsActivity) getActivity();
@@ -297,9 +295,7 @@
                 final BatteryEntry entry = new BatteryEntry(getActivity(), mHandler, mUm, sipper);
                 final Drawable badgedIcon = mUm.getBadgedDrawableForUser(entry.getIcon(),
                         userHandle);
-                // TODO: type of this will be replaced by CharSequence (see
-                // https://b.corp.google.com/issue?id=16401636 )
-                final String contentDescription = mUm.getBadgedLabelForUser(entry.getLabel(),
+                final CharSequence contentDescription = mUm.getBadgedLabelForUser(entry.getLabel(),
                         userHandle);
                 final PowerGaugePreference pref = new PowerGaugePreference(getActivity(),
                         badgedIcon, contentDescription, entry);
diff --git a/src/com/android/settings/location/RecentLocationApps.java b/src/com/android/settings/location/RecentLocationApps.java
index 5506181..13d282d 100644
--- a/src/com/android/settings/location/RecentLocationApps.java
+++ b/src/com/android/settings/location/RecentLocationApps.java
@@ -82,9 +82,9 @@
      * them for accessibility purposes.
      */
     private static class AccessiblePreference extends Preference {
-        public String mContentDescription;
+        public CharSequence mContentDescription;
 
-        public AccessiblePreference(Context context, String contentDescription) {
+        public AccessiblePreference(Context context, CharSequence contentDescription) {
             super(context);
             mContentDescription = contentDescription;
         }
@@ -103,7 +103,7 @@
             Drawable icon,
             CharSequence label,
             boolean isHighBattery,
-            String contentDescription,
+            CharSequence contentDescription,
             Preference.OnPreferenceClickListener listener) {
         AccessiblePreference pref = new AccessiblePreference(mActivity, contentDescription);
         pref.setIcon(icon);
@@ -209,7 +209,7 @@
             Drawable appIcon = mPackageManager.getApplicationIcon(appInfo);
             Drawable icon = um.getBadgedDrawableForUser(appIcon, userHandle);
             CharSequence appLabel = mPackageManager.getApplicationLabel(appInfo);
-            String badgedAppLabel = um.getBadgedLabelForUser(appLabel.toString(), userHandle);
+            CharSequence badgedAppLabel = um.getBadgedLabelForUser(appLabel.toString(), userHandle);
             preference = createRecentLocationEntry(icon,
                     appLabel, highBattery, badgedAppLabel,
                     new PackageEntryClickedListener(packageName));
diff --git a/src/com/android/settings/nfc/PaymentDefaultDialog.java b/src/com/android/settings/nfc/PaymentDefaultDialog.java
index 6bc29e1..33ac947 100644
--- a/src/com/android/settings/nfc/PaymentDefaultDialog.java
+++ b/src/com/android/settings/nfc/PaymentDefaultDialog.java
@@ -34,6 +34,7 @@
         DialogInterface.OnClickListener {
 
     public static final String TAG = "PaymentDefaultDialog";
+    private static final int PAYMENT_APP_MAX_CAPTION_LENGTH = 40;
 
     private PaymentBackend mBackend;
     private ComponentName mNewDefault;
@@ -109,12 +110,14 @@
         p.mTitle = getString(R.string.nfc_payment_set_default_label);
         if (defaultPaymentApp == null) {
             String formatString = getString(R.string.nfc_payment_set_default);
-            String msg = String.format(formatString, requestedPaymentApp.caption);
+            String msg = String.format(formatString,
+                    sanitizePaymentAppCaption(requestedPaymentApp.caption.toString()));
             p.mMessage = msg;
         } else {
             String formatString = getString(R.string.nfc_payment_set_default_instead_of);
-            String msg = String.format(formatString, requestedPaymentApp.caption,
-                    defaultPaymentApp.caption);
+            String msg = String.format(formatString,
+                    sanitizePaymentAppCaption(requestedPaymentApp.caption.toString()),
+                    sanitizePaymentAppCaption(defaultPaymentApp.caption.toString()));
             p.mMessage = msg;
         }
         p.mPositiveButtonText = getString(R.string.yes);
@@ -126,4 +129,15 @@
         return true;
     }
 
+    private String sanitizePaymentAppCaption(String input) {
+        String sanitizedString = input.replace('\n', ' ').replace('\r', ' ').trim();
+
+
+        if (sanitizedString.length() > PAYMENT_APP_MAX_CAPTION_LENGTH) {
+            return sanitizedString.substring(0, PAYMENT_APP_MAX_CAPTION_LENGTH);
+        }
+
+        return sanitizedString;
+    }
+
 }
diff --git a/src/com/android/settings/search/SearchIndexableResources.java b/src/com/android/settings/search/SearchIndexableResources.java
index a3d2b8d..e0e09a8 100644
--- a/src/com/android/settings/search/SearchIndexableResources.java
+++ b/src/com/android/settings/search/SearchIndexableResources.java
@@ -92,7 +92,7 @@
         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));
 
diff --git a/src/com/android/settings/sim/SimSettings.java b/src/com/android/settings/sim/SimSettings.java
index 2e1c0f5..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);
     }
@@ -273,8 +263,6 @@
                     // SubscriptionManager.setDefaultSMSSubId(subId);
                 }
 
-                updateAllOptions();
-
                 return true;
             }
         });
@@ -357,6 +345,7 @@
                         mSubInfoRecord.mSubId);
 
                     updateAllOptions();
+                    update();
                 }
             });
 
@@ -370,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/users/UserSettings.java b/src/com/android/settings/users/UserSettings.java
index 7dc83ef..ba93931 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) {
@@ -911,8 +907,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) {
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;
+        }
     }
 
     /**