Merge "Disable orientation switching on CryptKeeper screen"
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 36cf32c..030e051 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -169,6 +169,7 @@
         </activity>
 
         <activity android:name=".wifi.WifiSetupActivity"
+                android:taskAffinity="com.android.wizard"
                 android:theme="@style/SetupWizardWifiTheme"
                 android:label="@string/wifi_setup_wizard_title"
                 android:icon="@drawable/empty_icon"
diff --git a/res/layout/trust_agent_settings.xml b/res/layout/advanced_security_settings.xml
similarity index 100%
rename from res/layout/trust_agent_settings.xml
rename to res/layout/advanced_security_settings.xml
diff --git a/res/layout/setup_preference.xml b/res/layout/setup_preference.xml
index d0cbc02..dc6130d 100644
--- a/res/layout/setup_preference.xml
+++ b/res/layout/setup_preference.xml
@@ -18,7 +18,7 @@
 -->
 <view
     xmlns:android="http://schemas.android.com/apk/res/android"
-    class="com.android.settings.wifi.WifiSettings$ProportionalOuterFrame"
+    class="com.android.settings.widget.ProportionalOuterFrame"
     android:layout_height="match_parent"
     android:layout_width="match_parent">
 
diff --git a/res/values-sw600dp/dimens.xml b/res/values-sw600dp/dimens.xml
index 0cef851..76ce998 100755
--- a/res/values-sw600dp/dimens.xml
+++ b/res/values-sw600dp/dimens.xml
@@ -44,5 +44,10 @@
 
     <!-- SwitchBar padding start -->
     <dimen name="switchbar_padding_start">80dp</dimen>
+    <!-- SwitchBar padding end -->
+    <dimen name="switchbar_padding_end">80dp</dimen>
+
+    <!-- ActionBar contentInsetStart -->
+    <dimen name="actionbar_contentInsetStart">80dp</dimen>
 
 </resources>
diff --git a/res/values/arrays.xml b/res/values/arrays.xml
index a632f54..3695d3a 100644
--- a/res/values/arrays.xml
+++ b/res/values/arrays.xml
@@ -1034,7 +1034,6 @@
     <string-array name="track_frame_time_entries">
         <item>Off</item>
         <item>On screen as bars</item>
-        <item>On screen as lines</item>
         <item>In adb shell dumpsys gfxinfo</item>
     </string-array>
 
@@ -1042,7 +1041,6 @@
     <string-array name="track_frame_time_values" translatable="false" >
         <item>false</item>
         <item>visual_bars</item>
-        <item>visual_lines</item>
         <item>true</item>
     </string-array>
 
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index 460fb44..aa8ab5e 100755
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -94,8 +94,11 @@
     <dimen name="dashboard_category_title_height">48dp</dimen>
 
     <!-- SwitchBar padding start -->
-    <dimen name="switchbar_padding_start">72dp</dimen>
-    <!-- SwitchBar padding emd -->
-    <dimen name="switchbar_padding_end">@*android:dimen/preference_fragment_padding_side</dimen>
+    <dimen name="switchbar_padding_start">84dp</dimen>
+    <!-- SwitchBar padding end. Should be 2 x @*android:dimen/preference_fragment_padding_side -->
+    <dimen name="switchbar_padding_end">32dp</dimen>
+
+    <!-- ActionBar contentInsetStart -->
+    <dimen name="actionbar_contentInsetStart">84dp</dimen>
 
 </resources>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index b39a46d..fe487bb 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -610,7 +610,7 @@
     <!-- Wireless controls settings screen, setting check box label -->
     <string name="airplane_mode">Airplane mode</string>
     <!-- Main Settings screen settings title for things like airplane mode, tethering, NFC, VPN.  This will take you to another screen with those settings. -->
-    <string name="radio_controls_title">More\u2026</string>
+    <string name="radio_controls_title">NFC &amp; more</string>
     <!-- Wireless Settings screen title for things like Wi-Fi, bluetooth, airplane mode. -->
     <string name="wireless_networks_settings_title">Wireless &amp; networks</string>
     <!-- Main Settings screen settings summary text for the "Wireless controls" setting -->
@@ -3979,6 +3979,8 @@
     <string name="trusted_credentials">Trusted credentials</string>
     <!-- Summary of preference to display trusted credentials (aka CA certificates) [CHAR LIMIT=NONE] -->
     <string name="trusted_credentials_summary">Display trusted CA certificates</string>
+    <!-- Title of preference group for advance security settings [CHAR LIMIT=30] -->
+    <string name="advanced_security_title">Advanced</string>
     <!-- Title of preference of what type of credential storage this device has: hardware or software [CHAR LIMIT=30] -->
     <string name="credential_storage_type">Storage type</string>
     <!-- Summary text for preference showing what type of credential storage this device has when it is stored in a hardware-backed storage (as opposed to "software only") [CHAR LIMIT=NONE] -->
@@ -4211,6 +4213,8 @@
     <string name="accessibility_sync_enabled">Sync enabled</string>
     <!-- Content description of the disabled sync icon for accessibility. [CHAR LIMIT=NONE] -->
     <string name="accessibility_sync_disabled">Sync disabled</string>
+    <!-- Content description of the in progress sync icon for accessibility. [CHAR LIMIT=NONE] -->
+    <string name="accessibility_sync_in_progress">Syncing now</string>
     <!-- Content description of the disabled sync icon for accessibility. [CHAR LIMIT=NONE] -->
     <string name="accessibility_sync_error">Sync error.</string>
     <!-- Image description for the sync failed icon. -->
diff --git a/res/values/themes.xml b/res/values/themes.xml
index c39910b..366492d 100644
--- a/res/values/themes.xml
+++ b/res/values/themes.xml
@@ -89,6 +89,12 @@
         <!-- Used by the StatusBar and NavBar -->
         <item name="android:colorPrimaryDark">@color/actionbar_background_color</item>
         <item name="android:colorAccent">@color/quantum_orange_A200</item>
+        <!-- Redefine the ActionBar style for contentInsetStart -->
+        <item name="android:actionBarStyle">@style/Theme.ActionBar</item>
+    </style>
+
+    <style name="Theme.ActionBar" parent="@android:style/Widget.Quantum.Light.ActionBar.Solid">
+        <item name="android:contentInsetStart">@dimen/actionbar_contentInsetStart</item>
     </style>
 
 </resources>
diff --git a/res/xml/device_info_settings.xml b/res/xml/device_info_settings.xml
index 0261b67..c9a9a48 100644
--- a/res/xml/device_info_settings.xml
+++ b/res/xml/device_info_settings.xml
@@ -80,15 +80,6 @@
             <intent android:action="android.settings.SAFETY" />
         </PreferenceScreen>
 
-        <!-- Contributors -->
-        <!-- 
-        <PreferenceScreen
-                android:key="contributors"
-                android:title="@string/contributors_title">
-            <intent android:action="android.settings.TEAM" />
-        </PreferenceScreen>
-        -->
-
         <PreferenceScreen
                 android:key="regulatory_info"
                 android:title="@string/regulatory_information">
diff --git a/res/xml/security_settings_misc.xml b/res/xml/security_settings_misc.xml
index 84ce96c..c8f3e02 100644
--- a/res/xml/security_settings_misc.xml
+++ b/res/xml/security_settings_misc.xml
@@ -47,12 +47,6 @@
                 android:persistent="false"
                 android:fragment="com.android.settings.DeviceAdminSettings"/>
 
-        <Preference android:key="manage_trust_agents"
-                    android:title="@string/manage_trust_agents"
-                    android:summary="@string/manage_trust_agents_summary"
-                    android:persistent="false"
-                    android:fragment="com.android.settings.TrustAgentSettings"/>
-
         <CheckBoxPreference android:key="toggle_install_applications"
                 android:title="@string/install_applications"
                 android:summaryOff="@string/install_unknown_applications"
@@ -64,7 +58,6 @@
                 android:summaryOff="@string/verify_applications_summary"
                 android:summaryOn="@string/verify_applications_summary"
                 android:persistent="false" />
-
     </PreferenceCategory>
 
     <PreferenceCategory android:key="credentials_management"
@@ -99,4 +92,14 @@
                     android:targetClass="com.android.settings.CredentialStorage"/>
         </Preference>
     </PreferenceCategory>
+
+    <PreferenceCategory android:key="advanced_security"
+            android:title="@string/advanced_security_title"
+            android:persistent="false">
+        <Preference android:key="manage_trust_agents"
+                android:title="@string/manage_trust_agents"
+                android:summary="@string/manage_trust_agents_summary"
+                android:persistent="false"
+                android:fragment="com.android.settings.AdvancedSecuritySettings"/>
+    </PreferenceCategory>
 </PreferenceScreen>
diff --git a/src/com/android/settings/AccountPreference.java b/src/com/android/settings/AccountPreference.java
index 2cc013c..7547721 100644
--- a/src/com/android/settings/AccountPreference.java
+++ b/src/com/android/settings/AccountPreference.java
@@ -140,6 +140,8 @@
                 return getContext().getString(R.string.accessibility_sync_disabled);
             case SYNC_ERROR:
                 return getContext().getString(R.string.accessibility_sync_error);
+            case SYNC_IN_PROGRESS:
+                return getContext().getString(R.string.accessibility_sync_in_progress);
             default:
                 Log.e(TAG, "Unknown sync status: " + status);
                 return getContext().getString(R.string.accessibility_sync_error);
diff --git a/src/com/android/settings/TrustAgentSettings.java b/src/com/android/settings/AdvancedSecuritySettings.java
similarity index 69%
rename from src/com/android/settings/TrustAgentSettings.java
rename to src/com/android/settings/AdvancedSecuritySettings.java
index d31436d..c497ac4 100644
--- a/src/com/android/settings/TrustAgentSettings.java
+++ b/src/com/android/settings/AdvancedSecuritySettings.java
@@ -18,26 +18,17 @@
 
 import com.android.internal.widget.LockPatternUtils;
 
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
 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.content.res.Resources;
-import android.content.res.TypedArray;
-import android.content.res.XmlResourceParser;
 import android.graphics.drawable.Drawable;
 import android.os.Bundle;
 import android.service.trust.TrustAgentService;
 import android.util.ArrayMap;
 import android.util.ArraySet;
-import android.util.AttributeSet;
-import android.util.Slog;
-import android.util.Xml;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
@@ -46,15 +37,12 @@
 import android.widget.ImageView;
 import android.widget.TextView;
 
-import java.io.IOException;
 import java.util.List;
 
-public class TrustAgentSettings extends ListFragment implements View.OnClickListener {
-    static final String TAG = "TrustAgentSettings";
+public class AdvancedSecuritySettings extends ListFragment implements View.OnClickListener {
+    static final String TAG = "AdvancedSecuritySettings";
 
     private static final String SERVICE_INTERFACE = TrustAgentService.SERVICE_INTERFACE;
-    private static final String TRUST_AGENT_META_DATA = TrustAgentService.TRUST_AGENT_META_DATA;
-
 
     private final ArraySet<ComponentName> mActiveAgents = new ArraySet<ComponentName>();
     private final ArrayMap<ComponentName, AgentInfo> mAvailableAgents
@@ -94,7 +82,7 @@
                     container.getContext().getApplicationContext());
         }
         setListAdapter(new AgentListAdapter());
-        return inflater.inflate(R.layout.trust_agent_settings, container, false);
+        return inflater.inflate(R.layout.advanced_security_settings, container, false);
     }
 
     @Override
@@ -121,70 +109,21 @@
 
         for (ResolveInfo resolveInfo : resolveInfos) {
             if (resolveInfo.serviceInfo == null) continue;
-            ComponentName name = getComponentName(resolveInfo);
+            ComponentName name = TrustAgentUtils.getComponentName(resolveInfo);
             if (!mAvailableAgents.containsKey(name)) {
                 AgentInfo agentInfo = new AgentInfo();
                 agentInfo.label = resolveInfo.loadLabel(pm);
                 agentInfo.icon = resolveInfo.loadIcon(pm);
                 agentInfo.component = name;
-                agentInfo.settings = getSettingsComponentName(pm, resolveInfo);
+                TrustAgentUtils.TrustAgentComponentInfo trustAgentComponentInfo =
+                        TrustAgentUtils.getSettingsComponent(pm, resolveInfo);
+                agentInfo.settings = trustAgentComponentInfo.componentName;
                 mAvailableAgents.put(name, agentInfo);
             }
         }
         ((BaseAdapter) getListAdapter()).notifyDataSetChanged();
     }
 
-    private ComponentName getComponentName(ResolveInfo resolveInfo) {
-        if (resolveInfo == null || resolveInfo.serviceInfo == null) return null;
-        return new ComponentName(resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name);
-    }
-
-    private ComponentName getSettingsComponentName(PackageManager pm, ResolveInfo resolveInfo) {
-        if (resolveInfo == null || resolveInfo.serviceInfo == null
-                || resolveInfo.serviceInfo.metaData == null) return null;
-        String cn = null;
-        XmlResourceParser parser = null;
-        Exception caughtException = null;
-        try {
-            parser = resolveInfo.serviceInfo.loadXmlMetaData(pm, TRUST_AGENT_META_DATA);
-            if (parser == null) {
-                Slog.w(TAG, "Can't find " + TRUST_AGENT_META_DATA + " meta-data");
-                return null;
-            }
-            Resources res = pm.getResourcesForApplication(resolveInfo.serviceInfo.applicationInfo);
-            AttributeSet attrs = Xml.asAttributeSet(parser);
-            int type;
-            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
-                    && type != XmlPullParser.START_TAG) {
-            }
-            String nodeName = parser.getName();
-            if (!"trust-agent".equals(nodeName)) {
-                Slog.w(TAG, "Meta-data does not start with trust-agent tag");
-                return null;
-            }
-            TypedArray sa = res
-                    .obtainAttributes(attrs, com.android.internal.R.styleable.TrustAgent);
-            cn = sa.getString(com.android.internal.R.styleable.TrustAgent_settingsActivity);
-            sa.recycle();
-        } catch (PackageManager.NameNotFoundException e) {
-            caughtException = e;
-        } catch (IOException e) {
-            caughtException = e;
-        } catch (XmlPullParserException e) {
-            caughtException = e;
-        } finally {
-            if (parser != null) parser.close();
-        }
-        if (caughtException != null) {
-            Slog.w(TAG, "Error parsing : " + resolveInfo.serviceInfo.packageName, caughtException);
-            return null;
-        }
-        if (cn != null && cn.indexOf('/') < 0) {
-            cn = resolveInfo.serviceInfo.packageName + "/" + cn;
-        }
-        return cn == null ? null : ComponentName.unflattenFromString(cn);
-    }
-
     @Override
     public void onClick(View view) {
         ViewHolder h = (ViewHolder) view.getTag();
@@ -282,10 +221,10 @@
             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(TrustAgentSettings.this);
+            h.clickable.setOnClickListener(AdvancedSecuritySettings.this);
             h.description = (TextView)v.findViewById(R.id.description);
             h.settings = v.findViewById(R.id.settings);
-            h.settings.setOnClickListener(TrustAgentSettings.this);
+            h.settings.setOnClickListener(AdvancedSecuritySettings.this);
             v.setTag(h);
             h.settings.setTag(h);
             h.clickable.setTag(h);
diff --git a/src/com/android/settings/CryptKeeper.java b/src/com/android/settings/CryptKeeper.java
index 661e304..322bda0 100644
--- a/src/com/android/settings/CryptKeeper.java
+++ b/src/com/android/settings/CryptKeeper.java
@@ -58,7 +58,6 @@
 import android.widget.TextView;
 
 import com.android.internal.statusbar.StatusBarIcon;
-import com.android.internal.telephony.ITelephony;
 import com.android.internal.telephony.Phone;
 import com.android.internal.telephony.PhoneConstants;
 import com.android.internal.widget.LockPatternUtils;
@@ -409,6 +408,7 @@
 
                     final TextView status = (TextView) findViewById(R.id.owner_info);
                     status.setText(owner_info);
+                    status.setSelected(true);
                     passwordEntryInit();
                 }
             }.execute();
@@ -605,8 +605,7 @@
         }
 
         // Disable the Emergency call button if the device has no voice telephone capability
-        final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
-        if (!tm.isVoiceCapable()) {
+        if (!getTelephonyManager().isVoiceCapable()) {
             final View emergencyCall = findViewById(R.id.emergencyCallButton);
             if (emergencyCall != null) {
                 Log.d(TAG, "Removing the emergency Call button");
@@ -760,7 +759,7 @@
      */
     private final void setAirplaneModeIfNecessary() {
         final boolean isLteDevice =
-                TelephonyManager.getDefault().getLteOnCdmaMode() == PhoneConstants.LTE_ON_CDMA_TRUE;
+                getTelephonyManager().getLteOnCdmaMode() == PhoneConstants.LTE_ON_CDMA_TRUE;
         if (!isLteDevice) {
             Log.d(TAG, "Going into airplane mode.");
             Settings.Global.putInt(getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 1);
@@ -796,7 +795,7 @@
             return;
         }
 
-        final int newState = TelephonyManager.getDefault().getCallState();
+        final int newState = getTelephonyManager().getCallState();
         int textId;
         if (newState == TelephonyManager.CALL_STATE_OFFHOOK) {
             // Show "return to call" text and show phone icon
@@ -816,23 +815,14 @@
     }
 
     private void takeEmergencyCallAction() {
-        if (TelephonyManager.getDefault().getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) {
-            resumeCall();
+        TelephonyManager telephonyManager = getTelephonyManager();
+        if (telephonyManager.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) {
+            telephonyManager.showCallScreen();
         } else {
             launchEmergencyDialer();
         }
     }
 
-    private void resumeCall() {
-        final ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
-        if (phone != null) {
-            try {
-                phone.showCallScreen();
-            } catch (RemoteException e) {
-                Log.e(TAG, "Error calling ITelephony service: " + e);
-            }
-        }
-    }
 
     private void launchEmergencyDialer() {
         final Intent intent = new Intent(ACTION_EMERGENCY_DIAL);
@@ -841,6 +831,10 @@
         startActivity(intent);
     }
 
+    private TelephonyManager getTelephonyManager() {
+        return (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
+    }
+
     /**
      * Listen to key events so we can disable sounds when we get a keyinput in EditText.
      */
diff --git a/src/com/android/settings/DeviceInfoSettings.java b/src/com/android/settings/DeviceInfoSettings.java
index 9d10ecb..c26e4ab 100644
--- a/src/com/android/settings/DeviceInfoSettings.java
+++ b/src/com/android/settings/DeviceInfoSettings.java
@@ -35,27 +35,30 @@
 import android.preference.Preference;
 import android.preference.PreferenceGroup;
 import android.preference.PreferenceScreen;
+import android.provider.SearchIndexableResource;
 import android.provider.Settings;
 import android.text.TextUtils;
 import android.util.Log;
 import android.widget.Toast;
+import com.android.settings.search.BaseSearchIndexProvider;
+import com.android.settings.search.Indexable;
 
 import java.io.BufferedReader;
 import java.io.FileReader;
 import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
-public class DeviceInfoSettings extends SettingsPreferenceFragment {
+public class DeviceInfoSettings extends SettingsPreferenceFragment implements Indexable {
 
     private static final String LOG_TAG = "DeviceInfoSettings";
     private static final String FILENAME_PROC_VERSION = "/proc/version";
     private static final String FILENAME_MSV = "/sys/board_properties/soc/msv";
 
     private static final String KEY_CONTAINER = "container";
-    private static final String KEY_TEAM = "team";
-    private static final String KEY_CONTRIBUTORS = "contributors";
     private static final String KEY_REGULATORY_INFO = "regulatory_info";
     private static final String KEY_TERMS = "terms";
     private static final String KEY_LICENSE = "license";
@@ -73,6 +76,7 @@
     private static final String KEY_EQUIPMENT_ID = "fcc_equipment_id";
     private static final String PROPERTY_EQUIPMENT_ID = "ro.ril.fccid";
     private static final String KEY_DEVICE_FEEDBACK = "device_feedback";
+    private static final String KEY_SAFETY_LEGAL = "safetylegal";
 
     static final int TAPS_TO_BE_A_DEVELOPER = 7;
 
@@ -109,7 +113,7 @@
                 PROPERTY_SELINUX_STATUS);
 
         // Remove Safety information preference if PROPERTY_URL_SAFETYLEGAL is not set
-        removePreferenceIfPropertyMissing(getPreferenceScreen(), "safetylegal",
+        removePreferenceIfPropertyMissing(getPreferenceScreen(), KEY_SAFETY_LEGAL,
                 PROPERTY_URL_SAFETYLEGAL);
 
         // Remove Equipment id preference if FCC ID is not set by RIL
@@ -139,8 +143,6 @@
                 Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
         Utils.updatePreferenceToSpecificActivityOrRemove(act, parentPreference, KEY_COPYRIGHT,
                 Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
-        Utils.updatePreferenceToSpecificActivityOrRemove(act, parentPreference, KEY_TEAM,
-                Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
 
         // These are contained by the root preference screen
         parentPreference = getPreferenceScreen();
@@ -152,8 +154,6 @@
             // Remove for secondary users
             removePreference(KEY_SYSTEM_UPDATE_SETTINGS);
         }
-        Utils.updatePreferenceToSpecificActivityOrRemove(act, parentPreference, KEY_CONTRIBUTORS,
-                Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);
 
         // Read platform settings for additional system update setting
         removePreferenceIfBoolFalse(KEY_UPDATE_SETTING,
@@ -365,7 +365,7 @@
     }
 
     private static String getFeedbackReporterPackage(Context context) {
-        String feedbackReporter =
+        final String feedbackReporter =
                 context.getResources().getString(R.string.oem_preferred_feedback_reporter);
         if (TextUtils.isEmpty(feedbackReporter)) {
             // Reporter not configured. Return.
@@ -373,7 +373,7 @@
         }
         // Additional checks to ensure the reporter is on system image, and reporter is
         // configured to listen to the intent. Otherwise, dont show the "send feedback" option.
-        Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
+        final Intent intent = new Intent(Intent.ACTION_BUG_REPORT);
 
         PackageManager pm = context.getPackageManager();
         List<ResolveInfo> resolvedPackages =
@@ -398,5 +398,83 @@
         }
         return null;
     }
+
+    /**
+     * For Search.
+     */
+    public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
+        new BaseSearchIndexProvider() {
+
+            @Override
+            public List<SearchIndexableResource> getXmlResourcesToIndex(
+                    Context context, boolean enabled) {
+                final SearchIndexableResource sir = new SearchIndexableResource(context);
+                sir.xmlResId = R.xml.device_info_settings;
+                return Arrays.asList(sir);
+            }
+
+            @Override
+            public List<String> getNonIndexableKeys(Context context) {
+                final List<String> keys = new ArrayList<String>();
+                if (isPropertyMissing(PROPERTY_SELINUX_STATUS)) {
+                    keys.add(KEY_SELINUX_STATUS);
+                }
+                if (isPropertyMissing(PROPERTY_URL_SAFETYLEGAL)) {
+                    keys.add(KEY_SAFETY_LEGAL);
+                }
+                if (isPropertyMissing(PROPERTY_EQUIPMENT_ID)) {
+                    keys.add(KEY_EQUIPMENT_ID);
+                }
+                // Remove Baseband version if wifi-only device
+                if (Utils.isWifiOnly(context)) {
+                    keys.add((KEY_BASEBAND_VERSION));
+                }
+                // Dont show feedback option if there is no reporter.
+                if (TextUtils.isEmpty(getFeedbackReporterPackage(context))) {
+                    keys.add(KEY_DEVICE_FEEDBACK);
+                }
+                if (!checkIntentAction(context, "android.settings.TERMS")) {
+                    keys.add(KEY_TERMS);
+                }
+                if (!checkIntentAction(context, "android.settings.LICENSE")) {
+                    keys.add(KEY_LICENSE);
+                }
+                if (!checkIntentAction(context, "android.settings.COPYRIGHT")) {
+                    keys.add(KEY_COPYRIGHT);
+                }
+                if (UserHandle.myUserId() != UserHandle.USER_OWNER) {
+                    keys.add(KEY_SYSTEM_UPDATE_SETTINGS);
+                }
+                if (!context.getResources().getBoolean(
+                        R.bool.config_additional_system_update_setting_enable)) {
+                    keys.add(KEY_UPDATE_SETTING);
+                }
+                return keys;
+            }
+
+            private boolean isPropertyMissing(String property) {
+                return SystemProperties.get(property).equals("");
+            }
+
+            private boolean checkIntentAction(Context context, String action) {
+                final Intent intent = new Intent(action);
+
+                // Find the activity that is in the system image
+                final PackageManager pm = context.getPackageManager();
+                final List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
+                final int listSize = list.size();
+
+                for (int i = 0; i < listSize; i++) {
+                    ResolveInfo resolveInfo = list.get(i);
+                    if ((resolveInfo.activityInfo.applicationInfo.flags &
+                            ApplicationInfo.FLAG_SYSTEM) != 0) {
+                        return true;
+                    }
+                }
+
+                return false;
+            }
+        };
+
 }
 
diff --git a/src/com/android/settings/SecuritySettings.java b/src/com/android/settings/SecuritySettings.java
index 00d1d89..ab03853 100644
--- a/src/com/android/settings/SecuritySettings.java
+++ b/src/com/android/settings/SecuritySettings.java
@@ -41,6 +41,7 @@
 import android.provider.SearchIndexableResource;
 import android.provider.Settings;
 import android.security.KeyStore;
+import android.service.trust.TrustAgentService;
 import android.telephony.TelephonyManager;
 import android.util.Log;
 
@@ -58,6 +59,8 @@
 public class SecuritySettings extends RestrictedSettingsFragment
         implements OnPreferenceChangeListener, DialogInterface.OnClickListener, Indexable {
     static final String TAG = "SecuritySettings";
+    private static final Intent TRUST_AGENT_INTENT =
+            new Intent(TrustAgentService.SERVICE_INTERFACE);
 
     // Lock Settings
     private static final String KEY_UNLOCK_SET_OR_CHANGE = "unlock_set_or_change";
@@ -74,6 +77,7 @@
     private static final int SET_OR_CHANGE_LOCK_METHOD_REQUEST = 123;
     private static final int CONFIRM_EXISTING_FOR_BIOMETRIC_WEAK_IMPROVE_REQUEST = 124;
     private static final int CONFIRM_EXISTING_FOR_BIOMETRIC_WEAK_LIVELINESS_OFF = 125;
+    private static final int CHANGE_TRUST_AGENT_SETTINGS = 126;
 
     // Misc Settings
     private static final String KEY_SIM_LOCK = "sim_lock";
@@ -86,6 +90,7 @@
     private static final String KEY_POWER_INSTANTLY_LOCKS = "power_button_instantly_locks";
     private static final String KEY_CREDENTIALS_MANAGER = "credentials_management";
     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
+    private static final String KEY_TRUST_AGENT = "trust_agent";
 
     private DevicePolicyManager mDPM;
 
@@ -161,7 +166,7 @@
     /**
      * Important!
      *
-     * Dont forget to update the SecuritySearchIndexProvider if you are doing any change in the
+     * Don't forget to update the SecuritySearchIndexProvider if you are doing any change in the
      * logic or adding/removing preferences here.
      */
     private PreferenceScreen createPreferenceHierarchy() {
@@ -270,7 +275,7 @@
         }
 
         // Application install
-        PreferenceGroup deviceAdminCategory= (PreferenceGroup)
+        PreferenceGroup deviceAdminCategory = (PreferenceGroup)
                 root.findPreference(KEY_DEVICE_ADMIN_CATEGORY);
         mToggleAppInstallation = (CheckBoxPreference) findPreference(
                 KEY_TOGGLE_INSTALL_APPLICATIONS);
@@ -303,6 +308,36 @@
             protectByRestrictions(root.findPreference(KEY_CREDENTIALS_INSTALL));
         }
 
+        // 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);
+            for (ResolveInfo resolveInfo : resolveInfos) {
+                if (resolveInfo.serviceInfo == null) continue;
+                TrustAgentUtils.TrustAgentComponentInfo trustAgentComponentInfo =
+                        TrustAgentUtils.getSettingsComponent(pm, resolveInfo);
+                if (trustAgentComponentInfo.componentName == null ||
+                        trustAgentComponentInfo.title == null ||
+                        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.
+            }
+        }
+
         return root;
     }
 
@@ -522,6 +557,13 @@
         } else if (KEY_TOGGLE_VERIFY_APPLICATIONS.equals(key)) {
             Settings.Global.putInt(getContentResolver(), Settings.Global.PACKAGE_VERIFIER_ENABLE,
                     mToggleVerifyApps.isChecked() ? 1 : 0);
+        } else if (KEY_TRUST_AGENT.equals(key)) {
+            ChooseLockSettingsHelper helper =
+                    new ChooseLockSettingsHelper(this.getActivity(), this);
+            if (!helper.launchConfirmationActivity(CHANGE_TRUST_AGENT_SETTINGS, null, null)) {
+                // If this returns false, it means no password confirmation is required.
+                startActivity(preference.getIntent());
+            }
         } else {
             // If we didn't handle it, let preferences handle it.
             return super.onPreferenceTreeClick(preferenceScreen, preference);
@@ -552,6 +594,14 @@
             // is called by grabbing the value from lockPatternUtils.  We can't set it here
             // because mBiometricWeakLiveliness could be null
             return;
+        } else if (requestCode == CHANGE_TRUST_AGENT_SETTINGS && resultCode == Activity.RESULT_OK) {
+            Preference preference = getPreferenceScreen().findPreference(KEY_TRUST_AGENT);
+            if (preference != null) {
+                Intent intent = preference.getIntent();
+                if (intent != null) {
+                    startActivity(intent);
+                }
+            }
         }
         createPreferenceHierarchy();
     }
diff --git a/src/com/android/settings/TrustAgentUtils.java b/src/com/android/settings/TrustAgentUtils.java
new file mode 100644
index 0000000..64829a2
--- /dev/null
+++ b/src/com/android/settings/TrustAgentUtils.java
@@ -0,0 +1,103 @@
+/*
+ * 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.ComponentName;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.content.res.Resources;
+import android.content.res.TypedArray;
+import android.content.res.XmlResourceParser;
+import android.service.trust.TrustAgentService;
+import android.util.AttributeSet;
+import android.util.Slog;
+import android.util.Xml;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.IOException;
+
+public class TrustAgentUtils {
+    static final String TAG = "TrustAgentUtils";
+
+    private static final String TRUST_AGENT_META_DATA = TrustAgentService.TRUST_AGENT_META_DATA;
+
+    public static class TrustAgentComponentInfo {
+        ComponentName componentName;
+        String title;
+        String summary;
+    }
+
+    public static ComponentName getComponentName(ResolveInfo resolveInfo) {
+        if (resolveInfo == null || resolveInfo.serviceInfo == null) return null;
+        return new ComponentName(resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name);
+    }
+
+    public static TrustAgentComponentInfo getSettingsComponent(
+            PackageManager pm, ResolveInfo resolveInfo) {
+        if (resolveInfo == null || resolveInfo.serviceInfo == null
+                || resolveInfo.serviceInfo.metaData == null) return null;
+        String cn = null;
+        TrustAgentComponentInfo trustAgentComponentInfo = new TrustAgentComponentInfo();
+        XmlResourceParser parser = null;
+        Exception caughtException = null;
+        try {
+            parser = resolveInfo.serviceInfo.loadXmlMetaData(pm, TRUST_AGENT_META_DATA);
+            if (parser == null) {
+                Slog.w(TAG, "Can't find " + TRUST_AGENT_META_DATA + " meta-data");
+                return null;
+            }
+            Resources res = pm.getResourcesForApplication(resolveInfo.serviceInfo.applicationInfo);
+            AttributeSet attrs = Xml.asAttributeSet(parser);
+            int type;
+            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
+                    && type != XmlPullParser.START_TAG) {
+            }
+            String nodeName = parser.getName();
+            if (!"trust-agent".equals(nodeName)) {
+                Slog.w(TAG, "Meta-data does not start with trust-agent tag");
+                return null;
+            }
+            TypedArray sa =
+                    res.obtainAttributes(attrs, com.android.internal.R.styleable.TrustAgent);
+            trustAgentComponentInfo.summary =
+                    sa.getString(com.android.internal.R.styleable.TrustAgent_summary);
+            trustAgentComponentInfo.title =
+                    sa.getString(com.android.internal.R.styleable.TrustAgent_title);
+            cn = sa.getString(com.android.internal.R.styleable.TrustAgent_settingsActivity);
+            sa.recycle();
+        } catch (PackageManager.NameNotFoundException e) {
+            caughtException = e;
+        } catch (IOException e) {
+            caughtException = e;
+        } catch (XmlPullParserException e) {
+            caughtException = e;
+        } finally {
+            if (parser != null) parser.close();
+        }
+        if (caughtException != null) {
+            Slog.w(TAG, "Error parsing : " + resolveInfo.serviceInfo.packageName, caughtException);
+            return null;
+        }
+        if (cn != null && cn.indexOf('/') < 0) {
+            cn = resolveInfo.serviceInfo.packageName + "/" + cn;
+        }
+        trustAgentComponentInfo.componentName = (cn == null) ? null : ComponentName.unflattenFromString(cn);
+        return trustAgentComponentInfo;
+    }
+}
diff --git a/src/com/android/settings/notification/ZenModeSettings.java b/src/com/android/settings/notification/ZenModeSettings.java
index 8a66d1b..379b4c7 100644
--- a/src/com/android/settings/notification/ZenModeSettings.java
+++ b/src/com/android/settings/notification/ZenModeSettings.java
@@ -74,6 +74,7 @@
     private static final String KEY_GENERAL = "general";
     private static final String KEY_CALLS = "phone_calls";
     private static final String KEY_MESSAGES = "messages";
+    private static final String KEY_STARRED = "starred";
 
     private static final String KEY_AUTOMATIC = "automatic";
     private static final String KEY_WHEN = "when";
@@ -91,6 +92,7 @@
             rt.put(R.string.zen_mode_phone_calls, KEY_CALLS);
         }
         rt.put(R.string.zen_mode_messages, KEY_MESSAGES);
+        rt.put(R.string.zen_mode_from_starred, KEY_STARRED);
         rt.put(R.string.zen_mode_automatic_category, KEY_AUTOMATIC);
         rt.put(R.string.zen_mode_when, KEY_WHEN);
         rt.put(R.string.zen_mode_start_time, KEY_START_TIME);
@@ -194,12 +196,25 @@
         });
 
         mStarred = new DropDownPreference(mContext);
-        mStarred.setEnabled(false);
+        mStarred.setKey(KEY_STARRED);
         mStarred.setTitle(R.string.zen_mode_from);
         mStarred.setDropDownWidth(R.dimen.zen_mode_dropdown_width);
-        mStarred.addItem(R.string.zen_mode_from_anyone, null);
-        mStarred.addItem(R.string.zen_mode_from_starred, null);
-        mStarred.addItem(R.string.zen_mode_from_contacts, null);
+        mStarred.addItem(R.string.zen_mode_from_anyone, ZenModeConfig.SOURCE_ANYONE);
+        mStarred.addItem(R.string.zen_mode_from_starred, ZenModeConfig.SOURCE_STAR);
+        mStarred.addItem(R.string.zen_mode_from_contacts, ZenModeConfig.SOURCE_CONTACT);
+        mStarred.setCallback(new DropDownPreference.Callback() {
+            @Override
+            public boolean onItemSelected(int pos, Object newValue) {
+                if (mDisableListeners) return true;
+                final int val = (Integer) newValue;
+                if (val == mConfig.allowFrom) return true;
+                if (DEBUG) Log.d(TAG, "onPrefChange allowFrom=" +
+                        ZenModeConfig.sourceToString(val));
+                final ZenModeConfig newConfig = mConfig.copy();
+                newConfig.allowFrom = val;
+                return setZenModeConfig(newConfig);
+            }
+        });
         general.addPreference(mStarred);
 
         final Preference alarmInfo = new Preference(mContext) {
@@ -266,7 +281,6 @@
         mEnd = new TimePickerPreference(mContext, mgr);
         mEnd.setKey(KEY_END_TIME);
         mEnd.setTitle(R.string.zen_mode_end_time);
-        mEnd.setSummaryFormat(R.string.zen_mode_end_time_summary_format);
         mEnd.setCallback(new TimePickerPreference.Callback() {
             @Override
             public boolean onSetTime(int hour, int minute) {
@@ -311,18 +325,26 @@
         updateControls();
     }
 
+    private void updateEndSummary() {
+        final int startMin = 60 * mConfig.sleepStartHour + mConfig.sleepStartMinute;
+        final int endMin = 60 * mConfig.sleepEndHour + mConfig.sleepEndMinute;
+        final boolean nextDay = startMin >= endMin;
+        mEnd.setSummaryFormat(nextDay ? R.string.zen_mode_end_time_summary_format : 0);
+    }
+
     private void updateControls() {
         mDisableListeners = true;
         if (mCalls != null) {
             mCalls.setChecked(mConfig.allowCalls);
         }
         mMessages.setChecked(mConfig.allowMessages);
-        mStarred.setSelectedItem(0);
+        mStarred.setSelectedValue(mConfig.allowFrom);
         mWhen.setSelectedValue(mConfig.sleepMode);
         mStart.setTime(mConfig.sleepStartHour, mConfig.sleepStartMinute);
         mEnd.setTime(mConfig.sleepEndHour, mConfig.sleepEndMinute);
         mDisableListeners = false;
         refreshAutomationSection();
+        updateEndSummary();
     }
 
     private void refreshAutomationSection() {
@@ -425,6 +447,7 @@
             if (success) {
                 mConfig = config;
                 if (DEBUG) Log.d(TAG, "Saved mConfig=" + mConfig);
+                updateEndSummary();
             }
             return success;
         } catch (Exception e) {
diff --git a/src/com/android/settings/search/Index.java b/src/com/android/settings/search/Index.java
index b1d21af..1b1825c 100644
--- a/src/com/android/settings/search/Index.java
+++ b/src/com/android/settings/search/Index.java
@@ -284,15 +284,17 @@
 
     private boolean addIndexablesFromRemoteProvider(String packageName, String authority) {
         try {
+            final int baseRank = Ranking.getBaseRankForAuthority(authority);
+
             final Context packageContext = mContext.createPackageContext(packageName, 0);
 
             final Uri uriForResources = buildUriForXmlResources(authority);
             addIndexablesForXmlResourceUri(packageContext, packageName, uriForResources,
-                    SearchIndexablesContract.INDEXABLES_XML_RES_COLUMNS);
+                    SearchIndexablesContract.INDEXABLES_XML_RES_COLUMNS, baseRank);
 
             final Uri uriForRawData = buildUriForRawData(authority);
             addIndexablesForRawDataUri(packageContext, packageName, uriForRawData,
-                    SearchIndexablesContract.INDEXABLES_RAW_COLUMNS);
+                    SearchIndexablesContract.INDEXABLES_RAW_COLUMNS, baseRank);
             return true;
         } catch (PackageManager.NameNotFoundException e) {
             Log.w(LOG_TAG, "Could not create context for " + packageName + ": "
@@ -501,7 +503,7 @@
     }
 
     private void addIndexablesForXmlResourceUri(Context packageContext, String packageName,
-            Uri uri, String[] projection) {
+            Uri uri, String[] projection, int baseRank) {
 
         final ContentResolver resolver = packageContext.getContentResolver();
         final Cursor cursor = resolver.query(uri, projection, null, null, null);
@@ -515,7 +517,9 @@
             final int count = cursor.getCount();
             if (count > 0) {
                 while (cursor.moveToNext()) {
-                    final int rank = cursor.getInt(COLUMN_INDEX_XML_RES_RANK);
+                    final int providerRank = cursor.getInt(COLUMN_INDEX_XML_RES_RANK);
+                    final int rank = (providerRank > 0) ? baseRank + providerRank : baseRank;
+
                     final int xmlResId = cursor.getInt(COLUMN_INDEX_XML_RES_RESID);
 
                     final String className = cursor.getString(COLUMN_INDEX_XML_RES_CLASS_NAME);
@@ -546,7 +550,7 @@
     }
 
     private void addIndexablesForRawDataUri(Context packageContext, String packageName,
-            Uri uri, String[] projection) {
+            Uri uri, String[] projection, int baseRank) {
 
         final ContentResolver resolver = packageContext.getContentResolver();
         final Cursor cursor = resolver.query(uri, projection, null, null, null);
@@ -560,7 +564,9 @@
             final int count = cursor.getCount();
             if (count > 0) {
                 while (cursor.moveToNext()) {
-                    final int rank = cursor.getInt(COLUMN_INDEX_RAW_RANK);
+                    final int providerRank = cursor.getInt(COLUMN_INDEX_RAW_RANK);
+                    final int rank = (providerRank > 0) ? baseRank + providerRank : baseRank;
+
                     final String title = cursor.getString(COLUMN_INDEX_RAW_TITLE);
                     final String summaryOn = cursor.getString(COLUMN_INDEX_RAW_SUMMARY_ON);
                     final String summaryOff = cursor.getString(COLUMN_INDEX_RAW_SUMMARY_OFF);
diff --git a/src/com/android/settings/search/Ranking.java b/src/com/android/settings/search/Ranking.java
new file mode 100644
index 0000000..074a8d7
--- /dev/null
+++ b/src/com/android/settings/search/Ranking.java
@@ -0,0 +1,147 @@
+/*
+ * 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.search;
+
+import com.android.settings.ChooseLockGeneric;
+import com.android.settings.DataUsageSummary;
+import com.android.settings.DateTimeSettings;
+import com.android.settings.DevelopmentSettings;
+import com.android.settings.DeviceInfoSettings;
+import com.android.settings.DisplaySettings;
+import com.android.settings.HomeSettings;
+import com.android.settings.PrivacySettings;
+import com.android.settings.SecuritySettings;
+import com.android.settings.WallpaperTypeSettings;
+import com.android.settings.WirelessSettings;
+import com.android.settings.accessibility.AccessibilitySettings;
+import com.android.settings.bluetooth.BluetoothSettings;
+import com.android.settings.deviceinfo.Memory;
+import com.android.settings.fuelgauge.PowerUsageSummary;
+import com.android.settings.inputmethod.InputMethodAndLanguageSettings;
+import com.android.settings.location.LocationSettings;
+import com.android.settings.notification.NotificationDisplaySettings;
+import com.android.settings.notification.NotificationSettings;
+import com.android.settings.notification.OtherSoundSettings;
+import com.android.settings.notification.ZenModeSettings;
+import com.android.settings.print.PrintSettingsFragment;
+import com.android.settings.users.UserSettings;
+import com.android.settings.wifi.AdvancedWifiSettings;
+import com.android.settings.wifi.WifiSettings;
+
+import java.util.HashMap;
+
+/**
+ * Utility class for dealing with Search Ranking.
+ */
+public final class Ranking {
+
+    public static final int RANK_WIFI = 1;
+    public static final int RANK_BT = 2;
+    public static final int RANK_DATA_USAGE = 3;
+    public static final int RANK_WIRELESS = 4;
+    public static final int RANK_HOME = 5;
+    public static final int RANK_DISPLAY = 6;
+    public static final int RANK_WALLPAPER = 7;
+    public static final int RANK_NOTIFICATIONS = 8;
+    public static final int RANK_MEMORY = 9;
+    public static final int RANK_POWER_USAGE = 10;
+    public static final int RANK_USERS = 11;
+    public static final int RANK_LOCATION = 12;
+    public static final int RANK_SECURITY = 13;
+    public static final int RANK_IME = 14;
+    public static final int RANK_PRIVACY = 15;
+    public static final int RANK_DATE_TIME = 16;
+    public static final int RANK_ACCESSIBILITY = 17;
+    public static final int RANK_PRINTING = 18;
+    public static final int RANK_DEVELOPEMENT = 19;
+    public static final int RANK_DEVICE_INFO = 20;
+
+    public static final int RANK_UNDEFINED = -1;
+    public static final int RANK_OTHERS = 1024;
+    public static final int BASE_RANK_DEFAULT = 2048;
+
+    public static int sCurrentBaseRank = BASE_RANK_DEFAULT;
+
+    private static HashMap<String, Integer> sRankMap = new HashMap<String, Integer>();
+    private static HashMap<String, Integer> sBaseRankMap = new HashMap<String, Integer>();
+
+    static {
+        sRankMap.put(WifiSettings.class.getName(), RANK_WIFI);
+        sRankMap.put(AdvancedWifiSettings.class.getName(), RANK_WIFI);
+
+        sRankMap.put(BluetoothSettings.class.getName(), RANK_BT);
+
+        sRankMap.put(DataUsageSummary.class.getName(), RANK_DATA_USAGE);
+
+        sRankMap.put(WirelessSettings.class.getName(), RANK_WIRELESS);
+
+        sRankMap.put(HomeSettings.class.getName(), RANK_HOME);
+
+        sRankMap.put(DisplaySettings.class.getName(), RANK_DISPLAY);
+
+        sRankMap.put(WallpaperTypeSettings.class.getName(), RANK_WALLPAPER);
+
+        sRankMap.put(NotificationSettings.class.getName(), RANK_NOTIFICATIONS);
+        sRankMap.put(NotificationDisplaySettings.class.getName(), RANK_NOTIFICATIONS);
+        sRankMap.put(OtherSoundSettings.class.getName(), RANK_NOTIFICATIONS);
+        sRankMap.put(ZenModeSettings.class.getName(), RANK_NOTIFICATIONS);
+
+        sRankMap.put(Memory.class.getName(), RANK_MEMORY);
+
+        sRankMap.put(PowerUsageSummary.class.getName(), RANK_POWER_USAGE);
+
+        sRankMap.put(UserSettings.class.getName(), RANK_USERS);
+
+        sRankMap.put(LocationSettings.class.getName(), RANK_LOCATION);
+
+        sRankMap.put(SecuritySettings.class.getName(), RANK_SECURITY);
+        sRankMap.put(ChooseLockGeneric.ChooseLockGenericFragment.class.getName(), RANK_SECURITY);
+
+        sRankMap.put(InputMethodAndLanguageSettings.class.getName(), RANK_IME);
+
+        sRankMap.put(PrivacySettings.class.getName(), RANK_PRIVACY);
+
+        sRankMap.put(DateTimeSettings.class.getName(), RANK_DATE_TIME);
+
+        sRankMap.put(AccessibilitySettings.class.getName(), RANK_ACCESSIBILITY);
+
+        sRankMap.put(PrintSettingsFragment.class.getName(), RANK_PRINTING);
+
+        sRankMap.put(DevelopmentSettings.class.getName(), RANK_DEVELOPEMENT);
+
+        sRankMap.put(DeviceInfoSettings.class.getName(), RANK_DEVICE_INFO);
+
+        sBaseRankMap.put("com.android.settings", 0);
+    }
+
+    public static int getRankForClassName(String className) {
+        Integer rank = sRankMap.get(className);
+        return (rank != null) ? (int) rank: RANK_OTHERS;
+    }
+
+    public static int getBaseRankForAuthority(String authority) {
+        synchronized (sBaseRankMap) {
+            Integer base = sBaseRankMap.get(authority);
+            if (base != null) {
+                return base;
+            }
+            sCurrentBaseRank++;
+            sBaseRankMap.put(authority, sCurrentBaseRank);
+            return sCurrentBaseRank;
+        }
+    }
+}
diff --git a/src/com/android/settings/search/SearchIndexableResources.java b/src/com/android/settings/search/SearchIndexableResources.java
index 2d6388f..5156648 100644
--- a/src/com/android/settings/search/SearchIndexableResources.java
+++ b/src/com/android/settings/search/SearchIndexableResources.java
@@ -52,179 +52,183 @@
 
     public static int NO_DATA_RES_ID = 0;
 
-    public static final int RANK_WIFI = 1;
-    public static final int RANK_BT = 2;
-    public static final int RANK_DATA_USAGE = 3;
-    public static final int RANK_WIRELESS = 4;
-    public static final int RANK_HOME = 5;
-    public static final int RANK_DISPLAY = 7;
-    public static final int RANK_WALLPAPER = 7;
-    public static final int RANK_NOTIFICATIONS = 8;
-    public static final int RANK_MEMORY = 9;
-    public static final int RANK_POWER_USAGE = 10;
-    public static final int RANK_USERS = 11;
-    public static final int RANK_LOCATION = 12;
-    public static final int RANK_SECURITY = 13;
-    public static final int RANK_IME = 14;
-    public static final int RANK_PRIVACY = 15;
-    public static final int RANK_DATE_TIME = 16;
-    public static final int RANK_ACCESSIBILITY = 17;
-    public static final int RANK_PRINTING = 18;
-    public static final int RANK_DEVELOPEMENT = 19;
-    public static final int RANK_DEVICE_INFO = 20;
-
     private static HashMap<String, SearchIndexableResource> sResMap =
             new HashMap<String, SearchIndexableResource>();
 
-
     static {
         sResMap.put(WifiSettings.class.getName(),
-                new SearchIndexableResource(RANK_WIFI,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(WifiSettings.class.getName()),
                         NO_DATA_RES_ID,
                         WifiSettings.class.getName(),
                         R.drawable.ic_settings_wireless));
 
         sResMap.put(WifiSettings.class.getName(),
-                new SearchIndexableResource(RANK_WIFI,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(AdvancedWifiSettings.class.getName()),
                         R.xml.wifi_advanced_settings,
                         AdvancedWifiSettings.class.getName(),
                         R.drawable.ic_settings_wireless));
 
         sResMap.put(BluetoothSettings.class.getName(),
-                new SearchIndexableResource(RANK_BT,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(BluetoothSettings.class.getName()),
                         NO_DATA_RES_ID,
                         BluetoothSettings.class.getName(),
                         R.drawable.ic_settings_bluetooth2));
 
         sResMap.put(DataUsageSummary.class.getName(),
-                new SearchIndexableResource(RANK_DATA_USAGE,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(DataUsageSummary.class.getName()),
                         NO_DATA_RES_ID,
                         DataUsageSummary.class.getName(),
                         R.drawable.ic_settings_data_usage));
 
         sResMap.put(WirelessSettings.class.getName(),
-                new SearchIndexableResource(RANK_WIRELESS,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(WirelessSettings.class.getName()),
                         R.xml.wireless_settings,
                         WirelessSettings.class.getName(),
                         R.drawable.empty_icon));
 
         sResMap.put(HomeSettings.class.getName(),
-                new SearchIndexableResource(RANK_HOME,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(HomeSettings.class.getName()),
                         R.xml.home_selection,
                         HomeSettings.class.getName(),
                         R.drawable.ic_settings_home));
 
         sResMap.put(DisplaySettings.class.getName(),
-                new SearchIndexableResource(RANK_DISPLAY,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(DisplaySettings.class.getName()),
                         R.xml.display_settings,
                         DisplaySettings.class.getName(),
                         R.drawable.ic_settings_display));
 
         sResMap.put(WallpaperTypeSettings.class.getName(),
-                new SearchIndexableResource(RANK_WALLPAPER,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(WallpaperTypeSettings.class.getName()),
                         NO_DATA_RES_ID,
                         WallpaperTypeSettings.class.getName(),
                         R.drawable.ic_settings_display));
 
         sResMap.put(NotificationSettings.class.getName(),
-                new SearchIndexableResource(RANK_NOTIFICATIONS,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(NotificationSettings.class.getName()),
                         NO_DATA_RES_ID,
                         NotificationSettings.class.getName(),
                         R.drawable.ic_settings_notifications));
 
         sResMap.put(NotificationDisplaySettings.class.getName(),
-                new SearchIndexableResource(RANK_NOTIFICATIONS,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(NotificationDisplaySettings.class.getName()),
                         R.xml.notification_display_settings,
                         NotificationDisplaySettings.class.getName(),
                         R.drawable.ic_settings_notifications));
 
         sResMap.put(OtherSoundSettings.class.getName(),
-                new SearchIndexableResource(RANK_NOTIFICATIONS,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(OtherSoundSettings.class.getName()),
                         NO_DATA_RES_ID,
                         OtherSoundSettings.class.getName(),
                         R.drawable.ic_settings_notifications));
 
         sResMap.put(ZenModeSettings.class.getName(),
-                new SearchIndexableResource(RANK_NOTIFICATIONS,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(ZenModeSettings.class.getName()),
                         NO_DATA_RES_ID,
                         ZenModeSettings.class.getName(),
                         R.drawable.ic_settings_notifications));
 
         sResMap.put(Memory.class.getName(),
-                new SearchIndexableResource(RANK_MEMORY,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(Memory.class.getName()),
                         NO_DATA_RES_ID,
                         Memory.class.getName(),
                         R.drawable.ic_settings_storage));
 
         sResMap.put(PowerUsageSummary.class.getName(),
-                new SearchIndexableResource(RANK_POWER_USAGE,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(PowerUsageSummary.class.getName()),
                         R.xml.power_usage_summary,
                         PowerUsageSummary.class.getName(),
                         R.drawable.ic_settings_battery));
 
         sResMap.put(UserSettings.class.getName(),
-                new SearchIndexableResource(RANK_USERS,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(UserSettings.class.getName()),
                         R.xml.user_settings,
                         UserSettings.class.getName(),
                         R.drawable.ic_settings_multiuser));
 
         sResMap.put(LocationSettings.class.getName(),
-                new SearchIndexableResource(RANK_LOCATION,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(LocationSettings.class.getName()),
                         R.xml.location_settings,
                         LocationSettings.class.getName(),
                         R.drawable.ic_settings_location));
 
         sResMap.put(SecuritySettings.class.getName(),
-                new SearchIndexableResource(RANK_SECURITY,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(SecuritySettings.class.getName()),
                         NO_DATA_RES_ID,
                         SecuritySettings.class.getName(),
                         R.drawable.ic_settings_security));
 
         sResMap.put(ChooseLockGeneric.ChooseLockGenericFragment.class.getName(),
-                new SearchIndexableResource(RANK_SECURITY,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(
+                                ChooseLockGeneric.ChooseLockGenericFragment.class.getName()),
                         R.xml.security_settings_picker,
                         ChooseLockGeneric.ChooseLockGenericFragment.class.getName(),
                         R.drawable.ic_settings_security));
 
         sResMap.put(InputMethodAndLanguageSettings.class.getName(),
-                new SearchIndexableResource(RANK_IME,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(InputMethodAndLanguageSettings.class.getName()),
                         NO_DATA_RES_ID,
                         InputMethodAndLanguageSettings.class.getName(),
                         R.drawable.ic_settings_language));
 
         sResMap.put(PrivacySettings.class.getName(),
-                new SearchIndexableResource(RANK_PRIVACY,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(PrivacySettings.class.getName()),
                         R.xml.privacy_settings,
                         PrivacySettings.class.getName(),
                         R.drawable.ic_settings_backup));
 
         sResMap.put(DateTimeSettings.class.getName(),
-                new SearchIndexableResource(RANK_DATE_TIME,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(DateTimeSettings.class.getName()),
                         R.xml.date_time_prefs,
                         DateTimeSettings.class.getName(),
                         R.drawable.ic_settings_date_time));
 
         sResMap.put(AccessibilitySettings.class.getName(),
-                new SearchIndexableResource(RANK_ACCESSIBILITY,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(AccessibilitySettings.class.getName()),
                         NO_DATA_RES_ID,
                         AccessibilitySettings.class.getName(),
                         R.drawable.ic_settings_accessibility));
 
         sResMap.put(PrintSettingsFragment.class.getName(),
-                new SearchIndexableResource(RANK_PRINTING,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(PrintSettingsFragment.class.getName()),
                         NO_DATA_RES_ID,
                         PrintSettingsFragment.class.getName(),
                         R.drawable.ic_settings_print));
 
         sResMap.put(DevelopmentSettings.class.getName(),
-                new SearchIndexableResource(RANK_DEVELOPEMENT,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(DevelopmentSettings.class.getName()),
                         R.xml.development_prefs,
                         DevelopmentSettings.class.getName(),
                         R.drawable.ic_settings_development));
 
         sResMap.put(DeviceInfoSettings.class.getName(),
-                new SearchIndexableResource(RANK_DEVICE_INFO,
-                        R.xml.device_info_settings,
+                new SearchIndexableResource(
+                        Ranking.getRankForClassName(DeviceInfoSettings.class.getName()),
+                        NO_DATA_RES_ID,
                         DeviceInfoSettings.class.getName(),
                         R.drawable.ic_settings_about));
     }
diff --git a/src/com/android/settings/widget/ProportionalOuterFrame.java b/src/com/android/settings/widget/ProportionalOuterFrame.java
new file mode 100644
index 0000000..d23d2c4
--- /dev/null
+++ b/src/com/android/settings/widget/ProportionalOuterFrame.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2011 Google Inc.
+ *
+ * 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.widget;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.util.AttributeSet;
+import android.view.View;
+import android.widget.RelativeLayout;
+
+import com.android.settings.R;
+
+/**
+ * Used as the outer frame of all setup wizard pages that need to adjust their margins based
+ * on the total size of the available display. (e.g. side margins set to 10% of total width.)
+ */
+public class ProportionalOuterFrame extends RelativeLayout {
+    public ProportionalOuterFrame(Context context) {
+        super(context);
+    }
+
+    public ProportionalOuterFrame(Context context, AttributeSet attrs) {
+        super(context, attrs);
+    }
+
+    public ProportionalOuterFrame(Context context, AttributeSet attrs, int defStyle) {
+        super(context, attrs, defStyle);
+    }
+
+    /**
+     * Set our margins and title area height proportionally to the available display size
+     */
+    @Override
+    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+        final int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
+        final int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
+        final Resources res = getContext().getResources();
+        final float titleHeight = res.getFraction(R.dimen.setup_title_height, 1, 1);
+        final float sideMargin = res.getFraction(R.dimen.setup_border_width, 1, 1);
+        final int bottom = res.getDimensionPixelSize(R.dimen.setup_margin_bottom);
+        setPaddingRelative((int) (parentWidth * sideMargin), 0,
+                (int) (parentWidth * sideMargin), bottom);
+        final View title = findViewById(R.id.title_area);
+        if (title != null) {
+            title.setMinimumHeight((int) (parentHeight * titleHeight));
+        }
+        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
+    }
+}
diff --git a/src/com/android/settings/wifi/WifiPickerActivity.java b/src/com/android/settings/wifi/WifiPickerActivity.java
index 6dea82e..4cb78bd 100644
--- a/src/com/android/settings/wifi/WifiPickerActivity.java
+++ b/src/com/android/settings/wifi/WifiPickerActivity.java
@@ -21,22 +21,28 @@
 
 import android.content.Intent;
 
+import java.lang.Class;
+
 public class WifiPickerActivity extends SettingsActivity implements ButtonBarHandler {
 
     @Override
     public Intent getIntent() {
         Intent modIntent = new Intent(super.getIntent());
         if (!modIntent.hasExtra(EXTRA_SHOW_FRAGMENT)) {
-            modIntent.putExtra(EXTRA_SHOW_FRAGMENT, WifiSettings.class.getName());
+            modIntent.putExtra(EXTRA_SHOW_FRAGMENT, getWifiSettingsClass().getName());
         }
         return modIntent;
     }
 
     @Override
     protected boolean isValidFragment(String fragmentName) {
-        if (WifiSettings.class.getName().equals(fragmentName)
+        if (getWifiSettingsClass().getName().equals(fragmentName)
                 || WifiP2pSettings.class.getName().equals(fragmentName)
                 || AdvancedWifiSettings.class.getName().equals(fragmentName)) return true;
         return false;
     }
+
+    /* package */ Class getWifiSettingsClass() {
+        return WifiSettings.class;
+    }
 }
\ No newline at end of file
diff --git a/src/com/android/settings/wifi/WifiSettings.java b/src/com/android/settings/wifi/WifiSettings.java
index a653910..3420f36 100644
--- a/src/com/android/settings/wifi/WifiSettings.java
+++ b/src/com/android/settings/wifi/WifiSettings.java
@@ -29,7 +29,6 @@
 import com.android.settings.wifi.p2p.WifiP2pSettings;
 
 import android.app.Activity;
-import android.app.AlertDialog;
 import android.app.Dialog;
 import android.content.BroadcastReceiver;
 import android.content.Context;
@@ -40,7 +39,6 @@
 import android.content.res.Resources;
 import android.content.res.TypedArray;
 import android.location.LocationManager;
-import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
 import android.net.NetworkInfo.DetailedState;
 import android.net.wifi.ScanResult;
@@ -54,23 +52,14 @@
 import android.os.Message;
 import android.preference.Preference;
 import android.preference.PreferenceScreen;
-import android.util.AttributeSet;
 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;
 import android.view.View;
-import android.view.View.OnClickListener;
-import android.view.ViewGroup;
 import android.widget.AdapterView.AdapterContextMenuInfo;
-import android.widget.Button;
-import android.widget.ImageButton;
-import android.widget.PopupMenu;
-import android.widget.PopupMenu.OnMenuItemClickListener;
-import android.widget.RelativeLayout;
 import android.widget.TextView;
 import android.widget.Toast;
 
@@ -93,10 +82,10 @@
         implements DialogInterface.OnClickListener, Indexable  {
 
     private static final String TAG = "WifiSettings";
-    private static final int MENU_ID_WPS_PBC = Menu.FIRST;
+    /* package */ static final int MENU_ID_WPS_PBC = Menu.FIRST;
     private static final int MENU_ID_WPS_PIN = Menu.FIRST + 1;
     private static final int MENU_ID_P2P = Menu.FIRST + 2;
-    private static final int MENU_ID_ADD_NETWORK = Menu.FIRST + 3;
+    /* package */ static final int MENU_ID_ADD_NETWORK = Menu.FIRST + 3;
     private static final int MENU_ID_ADVANCED = Menu.FIRST + 4;
     private static final int MENU_ID_SCAN = Menu.FIRST + 5;
     private static final int MENU_ID_CONNECT = Menu.FIRST + 6;
@@ -105,10 +94,10 @@
     private static final int MENU_ID_WRITE_NFC = Menu.FIRST + 9;
 
     private static final int WIFI_DIALOG_ID = 1;
-    private static final int WPS_PBC_DIALOG_ID = 2;
+    /* package */ static final int WPS_PBC_DIALOG_ID = 2;
     private static final int WPS_PIN_DIALOG_ID = 3;
-    private static final int WIFI_SKIPPED_DIALOG_ID = 4;
-    private static final int WIFI_AND_MOBILE_SKIPPED_DIALOG_ID = 5;
+    /* package */ static final int WIFI_SKIPPED_DIALOG_ID = 4;
+    /* package */ static final int WIFI_AND_MOBILE_SKIPPED_DIALOG_ID = 5;
     private static final int WRITE_NFC_DIALOG_ID = 6;
 
     // Combo scans can take 5-6s to complete - set to 10s.
@@ -118,14 +107,11 @@
     private static final String SAVE_DIALOG_EDIT_MODE = "edit_mode";
     private static final String SAVE_DIALOG_ACCESS_POINT_STATE = "wifi_ap_state";
 
-    // Activity result when pressing the Skip button
-    private static final int RESULT_SKIP = Activity.RESULT_FIRST_USER;
-
     private final IntentFilter mFilter;
     private final BroadcastReceiver mReceiver;
     private final Scanner mScanner;
 
-    private WifiManager mWifiManager;
+    /* package */ WifiManager mWifiManager;
     private WifiManager.ActionListener mConnectListener;
     private WifiManager.ActionListener mSaveListener;
     private WifiManager.ActionListener mForgetListener;
@@ -145,37 +131,11 @@
 
     private TextView mEmptyView;
 
-    /* Used in Wifi Setup context */
-
-    // this boolean extra specifies whether to disable the Next button when not connected
-    private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect";
-
-    // this boolean extra specifies whether to auto finish when connection is established
-    private static final String EXTRA_AUTO_FINISH_ON_CONNECT = "wifi_auto_finish_on_connect";
-
-    // this boolean extra shows a custom button that we can control
-    protected static final String EXTRA_SHOW_CUSTOM_BUTTON = "wifi_show_custom_button";
-
-    // show a text regarding data charges when wifi connection is required during setup wizard
-    protected static final String EXTRA_SHOW_WIFI_REQUIRED_INFO = "wifi_show_wifi_required_info";
-
-    // this boolean extra is set if we are being invoked by the Setup Wizard
-    private static final String EXTRA_IS_FIRST_RUN = "firstRun";
-
-    // should Next button only be enabled when we have a connection?
-    private boolean mEnableNextOnConnection;
-
-    // should activity finish once we have a connection?
-    private boolean mAutoFinishOnConnection;
-
     // Save the dialog details
     private boolean mDlgEdit;
     private AccessPoint mDlgAccessPoint;
     private Bundle mAccessPointSavedState;
 
-    // the action bar uses a different set of controls for Setup Wizard
-    private boolean mSetupWizardMode;
-
     private SwitchBar mSwitchBar;
 
     /** verbose logging flag. this flag is set thru developer debugging options
@@ -207,93 +167,6 @@
     }
 
     @Override
-    public void onCreate(Bundle icicle) {
-        // Set this flag early, as it's needed by getHelpResource(), which is called by super
-        mSetupWizardMode = getActivity().getIntent().getBooleanExtra(EXTRA_IS_FIRST_RUN, false);
-        super.onCreate(icicle);
-    }
-
-    @Override
-    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
-            Bundle savedInstanceState) {
-
-        if (mSetupWizardMode) {
-            View view = inflater.inflate(R.layout.setup_preference, container, false);
-            View other = view.findViewById(R.id.other_network);
-            other.setOnClickListener(new OnClickListener() {
-                @Override
-                public void onClick(View v) {
-                    if (mWifiManager.isWifiEnabled()) {
-                        onAddNetworkPressed();
-                    }
-                }
-            });
-            final ImageButton b = (ImageButton) view.findViewById(R.id.more);
-            if (b != null) {
-                b.setOnClickListener(new OnClickListener() {
-                    @Override
-                    public void onClick(View v) {
-                        if (mWifiManager.isWifiEnabled()) {
-                            PopupMenu pm = new PopupMenu(inflater.getContext(), b);
-                            pm.inflate(R.menu.wifi_setup);
-                            pm.setOnMenuItemClickListener(new OnMenuItemClickListener() {
-                                @Override
-                                public boolean onMenuItemClick(MenuItem item) {
-                                    if (R.id.wifi_wps == item.getItemId()) {
-                                        showDialog(WPS_PBC_DIALOG_ID);
-                                        return true;
-                                    }
-                                    return false;
-                                }
-                            });
-                            pm.show();
-                        }
-                    }
-                });
-            }
-
-            Intent intent = getActivity().getIntent();
-            if (intent.getBooleanExtra(EXTRA_SHOW_CUSTOM_BUTTON, false)) {
-                view.findViewById(R.id.button_bar).setVisibility(View.VISIBLE);
-                view.findViewById(R.id.back_button).setVisibility(View.INVISIBLE);
-                view.findViewById(R.id.skip_button).setVisibility(View.INVISIBLE);
-                view.findViewById(R.id.next_button).setVisibility(View.INVISIBLE);
-
-                Button customButton = (Button) view.findViewById(R.id.custom_button);
-                customButton.setVisibility(View.VISIBLE);
-                customButton.setOnClickListener(new OnClickListener() {
-                    @Override
-                    public void onClick(View v) {
-                        boolean isConnected = false;
-                        Activity activity = getActivity();
-                        final ConnectivityManager connectivity = (ConnectivityManager)
-                                activity.getSystemService(Context.CONNECTIVITY_SERVICE);
-                        if (connectivity != null) {
-                            final NetworkInfo info = connectivity.getActiveNetworkInfo();
-                            isConnected = (info != null) && info.isConnected();
-                        }
-                        if (isConnected) {
-                            // Warn of possible data charges
-                            showDialog(WIFI_SKIPPED_DIALOG_ID);
-                        } else {
-                            // Warn of lack of updates
-                            showDialog(WIFI_AND_MOBILE_SKIPPED_DIALOG_ID);
-                        }
-                    }
-                });
-            }
-
-            if (intent.getBooleanExtra(EXTRA_SHOW_WIFI_REQUIRED_INFO, false)) {
-                view.findViewById(R.id.wifi_required_info).setVisibility(View.VISIBLE);
-            }
-
-            return view;
-        } else {
-            return super.onCreateView(inflater, container, savedInstanceState);
-        }
-    }
-
-    @Override
     public void onActivityCreated(Bundle savedInstanceState) {
         super.onActivityCreated(savedInstanceState);
 
@@ -351,60 +224,11 @@
             mAccessPointSavedState = savedInstanceState.getBundle(SAVE_DIALOG_ACCESS_POINT_STATE);
         }
 
-        final Activity activity = getActivity();
-        final Intent intent = activity.getIntent();
-
-        // first if we're supposed to finish once we have a connection
-        mAutoFinishOnConnection = intent.getBooleanExtra(EXTRA_AUTO_FINISH_ON_CONNECT, false);
-
-        if (mAutoFinishOnConnection) {
-            // Hide the next button
-            if (hasNextButton()) {
-                getNextButton().setVisibility(View.GONE);
-            }
-
-            final ConnectivityManager connectivity = (ConnectivityManager)
-                    activity.getSystemService(Context.CONNECTIVITY_SERVICE);
-            if (connectivity != null
-                    && connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
-                activity.setResult(Activity.RESULT_OK);
-                activity.finish();
-                return;
-            }
-        }
-
-        // if we're supposed to enable/disable the Next button based on our current connection
-        // state, start it off in the right state
-        mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false);
-
-        if (mEnableNextOnConnection) {
-            if (hasNextButton()) {
-                final ConnectivityManager connectivity = (ConnectivityManager)
-                        activity.getSystemService(Context.CONNECTIVITY_SERVICE);
-                if (connectivity != null) {
-                    NetworkInfo info = connectivity.getNetworkInfo(
-                            ConnectivityManager.TYPE_WIFI);
-                    changeNextButtonState(info.isConnected());
-                }
-            }
-        }
-
         addPreferencesFromResource(R.xml.wifi_settings);
 
-        if (mSetupWizardMode) {
-            getView().setSystemUiVisibility(
-                    View.STATUS_BAR_DISABLE_HOME |
-                    View.STATUS_BAR_DISABLE_RECENT |
-                    View.STATUS_BAR_DISABLE_NOTIFICATION_ALERTS |
-                    View.STATUS_BAR_DISABLE_CLOCK);
-        }
-
         mEmptyView = (TextView) getView().findViewById(android.R.id.empty);
         getListView().setEmptyView(mEmptyView);
-
-        if (!mSetupWizardMode) {
-            registerForContextMenu(getListView());
-        }
+        registerForContextMenu(getListView());
         setHasOptionsMenu(true);
     }
 
@@ -412,13 +236,16 @@
     public void onStart() {
         super.onStart();
 
-        // On/off switch is hidden for Setup Wizard
-        if (!mSetupWizardMode) {
-            final SettingsActivity activity = (SettingsActivity) getActivity();
+        // On/off switch is hidden for Setup Wizard (returns null)
+        mWifiEnabler = createWifiEnabler();
+    }
 
-            mSwitchBar = activity.getSwitchBar();
-            mWifiEnabler = new WifiEnabler(activity, mSwitchBar);
-        }
+    /**
+     * @return new WifiEnabler or null (as overridden by WifiSettingsForSetupWizard)
+     */
+    /* package */ WifiEnabler createWifiEnabler() {
+        final SettingsActivity activity = (SettingsActivity) getActivity();
+        return new WifiEnabler(activity, activity.getSwitchBar());
     }
 
     @Override
@@ -449,44 +276,41 @@
         // If the user is not allowed to configure wifi, do not show the menu.
         if (isRestrictedAndNotPinProtected()) return;
 
+        addOptionsMenuItems(menu);
+        super.onCreateOptionsMenu(menu, inflater);
+    }
+
+    /**
+     * @param menu
+     */
+    void addOptionsMenuItems(Menu menu) {
         final boolean wifiIsEnabled = mWifiManager.isWifiEnabled();
         TypedArray ta = getActivity().getTheme().obtainStyledAttributes(
                 new int[] {R.attr.ic_menu_add, R.attr.ic_wps});
-        if (mSetupWizardMode) {
-            menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc)
-                    .setIcon(ta.getDrawable(1))
+        menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc)
+                .setIcon(ta.getDrawable(1))
+                .setEnabled(wifiIsEnabled)
+                .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
+        menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network)
+                .setIcon(ta.getDrawable(0))
+                .setEnabled(wifiIsEnabled)
+                .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
+        menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.wifi_menu_scan)
+                //.setIcon(R.drawable.ic_menu_scan_network)
+                .setEnabled(wifiIsEnabled)
+                .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
+        menu.add(Menu.NONE, MENU_ID_WPS_PIN, 0, R.string.wifi_menu_wps_pin)
+                .setEnabled(wifiIsEnabled)
+                .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
+        if (mP2pSupported) {
+            menu.add(Menu.NONE, MENU_ID_P2P, 0, R.string.wifi_menu_p2p)
                     .setEnabled(wifiIsEnabled)
-                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
-            menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network)
-                    .setEnabled(wifiIsEnabled)
-                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
-        } else {
-            menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc)
-                    .setIcon(ta.getDrawable(1))
-                    .setEnabled(wifiIsEnabled)
-                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
-            menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network)
-                    .setIcon(ta.getDrawable(0))
-                    .setEnabled(wifiIsEnabled)
-                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
-            menu.add(Menu.NONE, MENU_ID_SCAN, 0, R.string.wifi_menu_scan)
-                    //.setIcon(R.drawable.ic_menu_scan_network)
-                    .setEnabled(wifiIsEnabled)
-                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
-            menu.add(Menu.NONE, MENU_ID_WPS_PIN, 0, R.string.wifi_menu_wps_pin)
-                    .setEnabled(wifiIsEnabled)
-                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
-            if (mP2pSupported) {
-                menu.add(Menu.NONE, MENU_ID_P2P, 0, R.string.wifi_menu_p2p)
-                        .setEnabled(wifiIsEnabled)
-                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
-            }
-            menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced)
-                    //.setIcon(android.R.drawable.ic_menu_manage)
                     .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
         }
+        menu.add(Menu.NONE, MENU_ID_ADVANCED, 0, R.string.wifi_menu_advanced)
+                //.setIcon(android.R.drawable.ic_menu_manage)
+                .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
         ta.recycle();
-        super.onCreateOptionsMenu(menu, inflater);
     }
 
     @Override
@@ -667,44 +491,6 @@
                 return new WpsDialog(getActivity(), WpsInfo.PBC);
             case WPS_PIN_DIALOG_ID:
                 return new WpsDialog(getActivity(), WpsInfo.DISPLAY);
-            case WIFI_SKIPPED_DIALOG_ID:
-                return new AlertDialog.Builder(getActivity())
-                            .setMessage(R.string.wifi_skipped_message)
-                            .setCancelable(false)
-                            .setNegativeButton(R.string.wifi_skip_anyway,
-                                    new DialogInterface.OnClickListener() {
-                                @Override
-                                public void onClick(DialogInterface dialog, int id) {
-                                    getActivity().setResult(RESULT_SKIP);
-                                    getActivity().finish();
-                                }
-                            })
-                            .setPositiveButton(R.string.wifi_dont_skip,
-                                    new DialogInterface.OnClickListener() {
-                                @Override
-                                public void onClick(DialogInterface dialog, int id) {
-                                }
-                            })
-                            .create();
-            case WIFI_AND_MOBILE_SKIPPED_DIALOG_ID:
-                return new AlertDialog.Builder(getActivity())
-                            .setMessage(R.string.wifi_and_mobile_skipped_message)
-                            .setCancelable(false)
-                            .setNegativeButton(R.string.wifi_skip_anyway,
-                                    new DialogInterface.OnClickListener() {
-                                @Override
-                                public void onClick(DialogInterface dialog, int id) {
-                                    getActivity().setResult(RESULT_SKIP);
-                                    getActivity().finish();
-                                }
-                            })
-                            .setPositiveButton(R.string.wifi_dont_skip,
-                                    new DialogInterface.OnClickListener() {
-                                @Override
-                                public void onClick(DialogInterface dialog, int id) {
-                                }
-                            })
-                            .create();
             case WRITE_NFC_DIALOG_ID:
                 if (mSelectedAccessPoint != null) {
                     mWifiToNfcDialog = new WriteWifiConfigToNfcDialog(
@@ -717,7 +503,7 @@
     }
 
     /**
-     * Shows the latest access points available with supplimental information like
+     * Shows the latest access points available with supplemental information like
      * the strength of network and the security for it.
      */
     private void updateAccessPoints() {
@@ -882,17 +668,8 @@
             NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(
                     WifiManager.EXTRA_NETWORK_INFO);
             mConnected.set(info.isConnected());
-            changeNextButtonState(info.isConnected());
             updateAccessPoints();
             updateConnectionState(info.getDetailedState());
-            if (mAutoFinishOnConnection && info.isConnected()) {
-                Activity activity = getActivity();
-                if (activity != null) {
-                    activity.setResult(Activity.RESULT_OK);
-                    activity.finish();
-                }
-                return;
-            }
         } else if (WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
             updateConnectionState(null);
         }
@@ -986,18 +763,6 @@
         }
     }
 
-    /**
-     * Renames/replaces "Next" button when appropriate. "Next" button usually exists in
-     * Wifi setup screens, not in usual wifi settings screen.
-     *
-     * @param connected true when the device is connected to a wifi network.
-     */
-    private void changeNextButtonState(boolean connected) {
-        if (mEnableNextOnConnection && hasNextButton()) {
-            getNextButton().setEnabled(connected);
-        }
-    }
-
     @Override
     public void onClick(DialogInterface dialogInterface, int button) {
         if (button == WifiDialog.BUTTON_FORGET && mSelectedAccessPoint != null) {
@@ -1039,7 +804,7 @@
 
     /* package */ void forget() {
         if (mSelectedAccessPoint.networkId == INVALID_NETWORK_ID) {
-            // Should not happen, but a monkey seems to triger it
+            // Should not happen, but a monkey seems to trigger it
             Log.e(TAG, "Failed to forget invalid network " + mSelectedAccessPoint.getConfig());
             return;
         }
@@ -1050,9 +815,6 @@
             mScanner.resume();
         }
         updateAccessPoints();
-
-        // We need to rename/replace "Next" button in wifi setup context.
-        changeNextButtonState(false);
     }
 
     /**
@@ -1104,51 +866,9 @@
 
     @Override
     protected int getHelpResource() {
-        if (mSetupWizardMode) {
-            return 0;
-        }
         return R.string.help_url_wifi;
     }
 
-    /**
-     * Used as the outer frame of all setup wizard pages that need to adjust their margins based
-     * on the total size of the available display. (e.g. side margins set to 10% of total width.)
-     */
-    public static class ProportionalOuterFrame extends RelativeLayout {
-        public ProportionalOuterFrame(Context context) {
-            super(context);
-        }
-        public ProportionalOuterFrame(Context context, AttributeSet attrs) {
-            super(context, attrs);
-        }
-        public ProportionalOuterFrame(Context context, AttributeSet attrs, int defStyle) {
-            super(context, attrs, defStyle);
-        }
-
-        /**
-         * Set our margins and title area height proportionally to the available display size
-         */
-        @Override
-        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
-            int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
-            int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
-            final Resources res = getContext().getResources();
-            float titleHeight = res.getFraction(R.dimen.setup_title_height, 1, 1);
-            float sideMargin = res.getFraction(R.dimen.setup_border_width, 1, 1);
-            int bottom = res.getDimensionPixelSize(R.dimen.setup_margin_bottom);
-            setPaddingRelative(
-                    (int) (parentWidth * sideMargin),
-                    0,
-                    (int) (parentWidth * sideMargin),
-                    bottom);
-            View title = findViewById(R.id.title_area);
-            if (title != null) {
-                title.setMinimumHeight((int) (parentHeight * titleHeight));
-            }
-            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
-        }
-    }
-
     public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
         new BaseSearchIndexProvider() {
             @Override
diff --git a/src/com/android/settings/wifi/WifiSettingsForSetupWizard.java b/src/com/android/settings/wifi/WifiSettingsForSetupWizard.java
new file mode 100644
index 0000000..25b12b9
--- /dev/null
+++ b/src/com/android/settings/wifi/WifiSettingsForSetupWizard.java
@@ -0,0 +1,390 @@
+/*
+ * 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.wifi;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.res.TypedArray;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiInfo;
+import android.net.wifi.WifiManager;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.ImageButton;
+import android.widget.PopupMenu;
+import android.widget.PopupMenu.OnMenuItemClickListener;
+
+import com.android.settings.R;
+
+/**
+ * This customized version of WifiSettings is shown to the user only during Setup Wizard. Menu
+ * selections are limited, clicking on an access point will auto-advance to the next screen (once
+ * connected), and, if the user opts to skip ahead without a wifi connection, a warning message
+ * alerts of possible carrier data charges or missing software updates.
+ */
+public class WifiSettingsForSetupWizard extends WifiSettings {
+
+    private static final String TAG = "WifiSettingsForSetupWizard";
+
+    /* Used in Wifi Setup context */
+
+    // this boolean extra specifies whether to disable the Next button when not connected
+    private static final String EXTRA_ENABLE_NEXT_ON_CONNECT = "wifi_enable_next_on_connect";
+
+    // this boolean extra specifies whether to auto finish when connection is established
+    private static final String EXTRA_AUTO_FINISH_ON_CONNECT = "wifi_auto_finish_on_connect";
+
+    // this boolean extra shows a custom button that we can control
+    protected static final String EXTRA_SHOW_CUSTOM_BUTTON = "wifi_show_custom_button";
+
+    // show a text regarding data charges when wifi connection is required during setup wizard
+    protected static final String EXTRA_SHOW_WIFI_REQUIRED_INFO = "wifi_show_wifi_required_info";
+
+    // this boolean extra is set if we are being invoked by the Setup Wizard
+    private static final String EXTRA_IS_FIRST_RUN = "firstRun";
+
+    // Activity result when pressing the Skip button
+    private static final int RESULT_SKIP = Activity.RESULT_FIRST_USER;
+
+    // From WizardManager (must match constants maintained there)
+    private static final String ACTION_NEXT = "com.android.wizard.NEXT";
+    private static final String EXTRA_SCRIPT_URI = "scriptUri";
+    private static final String EXTRA_ACTION_ID = "actionId";
+    private static final String EXTRA_RESULT_CODE = "com.android.setupwizard.ResultCode";
+    private static final int NEXT_REQUEST = 10000;
+
+    // should Next button only be enabled when we have a connection?
+    private boolean mEnableNextOnConnection;
+
+    // should activity finish once we have a connection?
+    private boolean mAutoFinishOnConnection;
+
+    private final IntentFilter mFilter;
+    private final BroadcastReceiver mReceiver;
+
+    public WifiSettingsForSetupWizard() {
+        super();
+
+        mFilter = new IntentFilter();
+        mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
+
+        mReceiver = new BroadcastReceiver() {
+            @Override
+            public void onReceive(Context context, Intent intent) {
+                NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(
+                        WifiManager.EXTRA_NETWORK_INFO);
+                changeNextButtonState(info.isConnected());
+                if (mAutoFinishOnConnection && info.isConnected()) {
+                    finishOrNext(Activity.RESULT_OK);
+                }
+            }
+        };
+    }
+
+    @Override
+    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
+            Bundle savedInstanceState) {
+
+        final View view = inflater.inflate(R.layout.setup_preference, container, false);
+        final View other = view.findViewById(R.id.other_network);
+        other.setOnClickListener(new OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                if (mWifiManager.isWifiEnabled()) {
+                    onAddNetworkPressed();
+                }
+            }
+        });
+        final ImageButton b = (ImageButton) view.findViewById(R.id.more);
+        if (b != null) {
+            b.setOnClickListener(new OnClickListener() {
+                @Override
+                public void onClick(View v) {
+                    if (mWifiManager.isWifiEnabled()) {
+                        PopupMenu pm = new PopupMenu(inflater.getContext(), b);
+                        pm.inflate(R.menu.wifi_setup);
+                        pm.setOnMenuItemClickListener(new OnMenuItemClickListener() {
+                            @Override
+                            public boolean onMenuItemClick(MenuItem item) {
+                                if (R.id.wifi_wps == item.getItemId()) {
+                                    showDialog(WPS_PBC_DIALOG_ID);
+                                    return true;
+                                }
+                                return false;
+                            }
+                        });
+                        pm.show();
+                    }
+                }
+            });
+        }
+
+        final Intent intent = getActivity().getIntent();
+        if (intent.getBooleanExtra(EXTRA_SHOW_CUSTOM_BUTTON, false)) {
+            view.findViewById(R.id.button_bar).setVisibility(View.VISIBLE);
+            view.findViewById(R.id.back_button).setVisibility(View.INVISIBLE);
+            view.findViewById(R.id.skip_button).setVisibility(View.INVISIBLE);
+            view.findViewById(R.id.next_button).setVisibility(View.INVISIBLE);
+
+            Button customButton = (Button) view.findViewById(R.id.custom_button);
+            customButton.setVisibility(View.VISIBLE);
+            customButton.setOnClickListener(new OnClickListener() {
+                @Override
+                public void onClick(View v) {
+                    boolean isConnected = false;
+                    Activity activity = getActivity();
+                    final ConnectivityManager connectivity = (ConnectivityManager)
+                            activity.getSystemService(Context.CONNECTIVITY_SERVICE);
+                    if (connectivity != null) {
+                        final NetworkInfo info = connectivity.getActiveNetworkInfo();
+                        isConnected = (info != null) && info.isConnected();
+                    }
+                    if (isConnected) {
+                        // Warn of possible data charges
+                        showDialog(WIFI_SKIPPED_DIALOG_ID);
+                    } else {
+                        // Warn of lack of updates
+                        showDialog(WIFI_AND_MOBILE_SKIPPED_DIALOG_ID);
+                    }
+                }
+            });
+        }
+
+        if (intent.getBooleanExtra(EXTRA_SHOW_WIFI_REQUIRED_INFO, false)) {
+            view.findViewById(R.id.wifi_required_info).setVisibility(View.VISIBLE);
+        }
+
+        return view;
+    }
+
+    @Override
+    public void onActivityCreated(Bundle savedInstanceState) {
+        super.onActivityCreated(savedInstanceState);
+
+        getView().setSystemUiVisibility(
+                View.STATUS_BAR_DISABLE_HOME |
+                View.STATUS_BAR_DISABLE_RECENT |
+                View.STATUS_BAR_DISABLE_NOTIFICATION_ALERTS |
+                View.STATUS_BAR_DISABLE_CLOCK);
+
+        final Activity activity = getActivity();
+        final Intent intent = activity.getIntent();
+
+        // first if we're supposed to finish once we have a connection
+        mAutoFinishOnConnection = intent.getBooleanExtra(EXTRA_AUTO_FINISH_ON_CONNECT, false);
+
+        if (mAutoFinishOnConnection) {
+            // Hide the next button
+            if (hasNextButton()) {
+                getNextButton().setVisibility(View.GONE);
+            }
+
+            final ConnectivityManager connectivity = (ConnectivityManager)
+                    activity.getSystemService(Context.CONNECTIVITY_SERVICE);
+            if (connectivity != null
+                    && connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
+                finishOrNext(Activity.RESULT_OK);
+                return;
+            }
+        }
+
+        // if we're supposed to enable/disable the Next button based on our current connection
+        // state, start it off in the right state
+        mEnableNextOnConnection = intent.getBooleanExtra(EXTRA_ENABLE_NEXT_ON_CONNECT, false);
+
+        if (mEnableNextOnConnection) {
+            if (hasNextButton()) {
+                final ConnectivityManager connectivity = (ConnectivityManager)
+                        activity.getSystemService(Context.CONNECTIVITY_SERVICE);
+                if (connectivity != null) {
+                    NetworkInfo info = connectivity.getNetworkInfo(
+                            ConnectivityManager.TYPE_WIFI);
+                    changeNextButtonState(info.isConnected());
+                }
+            }
+        }
+    }
+
+    @Override
+    public Dialog onCreateDialog(int dialogId) {
+        switch (dialogId) {
+            case WIFI_SKIPPED_DIALOG_ID:
+                return new AlertDialog.Builder(getActivity())
+                            .setMessage(R.string.wifi_skipped_message)
+                            .setCancelable(false)
+                            .setNegativeButton(R.string.wifi_skip_anyway,
+                                    new DialogInterface.OnClickListener() {
+                                @Override
+                                public void onClick(DialogInterface dialog, int id) {
+                                    finishOrNext(RESULT_SKIP);
+                                }
+                            })
+                            .setPositiveButton(R.string.wifi_dont_skip,
+                                    new DialogInterface.OnClickListener() {
+                                @Override
+                                public void onClick(DialogInterface dialog, int id) {
+                                }
+                            })
+                            .create();
+            case WIFI_AND_MOBILE_SKIPPED_DIALOG_ID:
+                return new AlertDialog.Builder(getActivity())
+                            .setMessage(R.string.wifi_and_mobile_skipped_message)
+                            .setCancelable(false)
+                            .setNegativeButton(R.string.wifi_skip_anyway,
+                                    new DialogInterface.OnClickListener() {
+                                @Override
+                                public void onClick(DialogInterface dialog, int id) {
+                                    finishOrNext(RESULT_SKIP);
+                                }
+                            })
+                            .setPositiveButton(R.string.wifi_dont_skip,
+                                    new DialogInterface.OnClickListener() {
+                                @Override
+                                public void onClick(DialogInterface dialog, int id) {
+                                }
+                            })
+                            .create();
+        }
+        return super.onCreateDialog(dialogId);
+    }
+
+    @Override
+    public void onResume() {
+        super.onResume();
+        getActivity().registerReceiver(mReceiver, mFilter);
+    }
+
+    @Override
+    public void onPause() {
+        super.onPause();
+        getActivity().unregisterReceiver(mReceiver);
+    }
+
+    @Override
+    public void onActivityResult(int requestCode, int resultCode, Intent data) {
+        if (resultCode == Activity.RESULT_CANCELED) {
+            // Before returning to the settings panel, forget any current access point so it will
+            // not attempt to automatically reconnect and advance
+            // FIXME: when coming back, it would be better to keep the current connection and
+            // override the auto-advance feature
+            final WifiInfo info = mWifiManager.getConnectionInfo();
+            if (null != info) {
+                int netId = info.getNetworkId();
+                if (netId != WifiConfiguration.INVALID_NETWORK_ID) {
+                    mWifiManager.forget(netId, null);
+                }
+            }
+        }
+        super.onActivityResult(requestCode, resultCode, data);
+    }
+
+    @Override
+    public void registerForContextMenu(View view) {
+        // Suppressed during setup wizard
+    }
+
+    @Override
+    /* package */ WifiEnabler createWifiEnabler() {
+        // Not shown during setup wizard
+        return null;
+    }
+
+    @Override
+    /* package */ void addOptionsMenuItems(Menu menu) {
+        final boolean wifiIsEnabled = mWifiManager.isWifiEnabled();
+        final TypedArray ta = getActivity().getTheme()
+                .obtainStyledAttributes(new int[] {R.attr.ic_wps});
+        menu.add(Menu.NONE, MENU_ID_WPS_PBC, 0, R.string.wifi_menu_wps_pbc)
+                .setIcon(ta.getDrawable(0))
+                .setEnabled(wifiIsEnabled)
+                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
+        menu.add(Menu.NONE, MENU_ID_ADD_NETWORK, 0, R.string.wifi_add_network)
+                .setEnabled(wifiIsEnabled)
+                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
+        ta.recycle();
+    }
+
+    @Override
+    /* package */ void forget() {
+        super.forget();
+
+        // We need to rename/replace "Next" button in wifi setup context.
+        changeNextButtonState(false);
+    }
+
+    /**
+     * Renames/replaces "Next" button when appropriate. "Next" button usually exists in
+     * Wifi setup screens, not in usual wifi settings screen.
+     *
+     * @param enabled true when the device is connected to a wifi network.
+     */
+    private void changeNextButtonState(boolean enabled) {
+        if (mEnableNextOnConnection && hasNextButton()) {
+            getNextButton().setEnabled(enabled);
+        }
+    }
+
+    /**
+     * Complete this activity and return the results to the caller. If using WizardManager, this
+     * will invoke the next scripted action; otherwise, we simply finish.
+     */
+    private void finishOrNext(int resultCode) {
+        Log.d(TAG, "finishOrNext resultCode=" + resultCode
+                + " isUsingWizardManager=" + isUsingWizardManager());
+        if (isUsingWizardManager()) {
+            sendResultsToSetupWizard(resultCode);
+        } else {
+            Activity activity = getActivity();
+            activity.setResult(resultCode);
+            activity.finish();
+        }
+    }
+
+    private boolean isUsingWizardManager() {
+        return getActivity().getIntent().hasExtra(EXTRA_SCRIPT_URI);
+    }
+
+    /**
+     * Send the results of this activity to WizardManager, which will then send out the next
+     * scripted activity. WizardManager does not actually return an activity result, but if we
+     * invoke WizardManager without requesting a result, the framework will choose not to issue a
+     * call to onActivityResult with RESULT_CANCELED when navigating backward.
+     */
+    private void sendResultsToSetupWizard(int resultCode) {
+        final Intent intent = getActivity().getIntent();
+        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_RESULT_CODE, resultCode);
+        startActivityForResult(nextIntent, NEXT_REQUEST);
+    }
+}
diff --git a/src/com/android/settings/wifi/WifiSetupActivity.java b/src/com/android/settings/wifi/WifiSetupActivity.java
index 70ee56d..d4811ed 100644
--- a/src/com/android/settings/wifi/WifiSetupActivity.java
+++ b/src/com/android/settings/wifi/WifiSetupActivity.java
@@ -19,6 +19,8 @@
 
 import android.content.res.Resources;
 
+import java.lang.Class;
+
 public class WifiSetupActivity extends WifiPickerActivity implements ButtonBarHandler {
     // Extra containing the resource name of the theme to be used
     private static final String EXTRA_THEME = "theme";
@@ -41,4 +43,9 @@
         }
         super.onApplyThemeResource(theme, resid, first);
     }
+
+    @Override
+    /* package */ Class getWifiSettingsClass() {
+        return WifiSettingsForSetupWizard.class;
+    }
 }