Merge "Add subId while launching MMI dialog"
diff --git a/assets/eri_311480.xml b/assets/eri_311480.xml
index 750b200..c5e8624 100644
--- a/assets/eri_311480.xml
+++ b/assets/eri_311480.xml
@@ -58,7 +58,7 @@
          <EriInfo RoamingIndicator="64"
                   IconIndex="1"
                   IconMode="0"
-                  EriText="Verizon Wireless"
+                  EriText="Verizon"
                   CallPromptId="0"
                   AlertId="0"
                   DataServiceSupport="1"/>
@@ -154,7 +154,7 @@
          <EriInfo RoamingIndicator="76"
                   IconIndex="0"
                   IconMode="0"
-                  EriText="Verizon Wireless"
+                  EriText="Verizon"
                   CallPromptId="0"
                   AlertId="0"
                   DataServiceSupport="1"/>
@@ -162,7 +162,7 @@
          <EriInfo RoamingIndicator="77"
                   IconIndex="2"
                   IconMode="0"
-                  EriText="Verizon Wireless"
+                  EriText="Verizon"
                   CallPromptId="0"
                   AlertId="0"
                   DataServiceSupport="1"/>
diff --git a/res/layout/network_setting.xml b/res/layout/network_setting.xml
new file mode 100644
index 0000000..bfc16dc
--- /dev/null
+++ b/res/layout/network_setting.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2008 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+             android:id="@+id/network_setting_content"
+             android:layout_height="match_parent"
+             android:layout_width="match_parent"/>
diff --git a/res/values/config.xml b/res/values/config.xml
index 1f23c6b..bd0ed10 100644
--- a/res/values/config.xml
+++ b/res/values/config.xml
@@ -218,4 +218,7 @@
 
     <!-- Whether the emergency only account can make emergency calls -->
     <bool name="config_pstnCanPlaceEmergencyCalls">true</bool>
+
+    <!-- The package name for the platform carrier config app, bundled with system image. -->
+    <string name="platform_carrier_config_package" translatable="false">com.android.carrierconfig</string>
 </resources>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index ec7d761..ab01a0e 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -20,7 +20,7 @@
          and other settings UIs.  This is the version of the label for
          tablet devices, where the phone app handles mobile data but not
          actual phone calls. -->
-    <string name="phoneAppLabel" product="tablet">Cellular Data</string>
+    <string name="phoneAppLabel" product="tablet">Mobile Data</string>
 
     <!-- Official label of the phone app, as seen in "Manage Applications"
          and other settings UIs. -->
@@ -95,6 +95,8 @@
     <string name="no_vm_number_msg">No voicemail number is stored on the SIM card.</string>
     <!-- Button label on the "Missing voicemail number" dialog -->
     <string name="add_vm_number_str">Add number</string>
+    <!--Toast in Call settings when asked to launch voicemail for a guest user -->
+    <string name="voice_number_setting_primary_user_only">Voicemail Settings can only be modified by the Primary User.</string>
 
     <!-- Status message displayed on SIM PIN unlock panel -->
     <string name="puk_unlocked">Your SIM card has been unblocked. Your phone is unlocking\u2026</string>
@@ -115,7 +117,7 @@
     <!-- settings strings -->
 
     <!-- Error message for users that aren't allowed to modify Mobile Network settings [CHAR LIMIT=none] -->
-    <string name="mobile_network_settings_not_available">Cellular network settings are not available for this user</string>
+    <string name="mobile_network_settings_not_available">Mobile network settings are not available for this user</string>
     <!-- GSM Call settings screen, setting option name. [CHAR LIMIT=40] -->
     <string name="labelGSMMore">GSM call settings</string>
     <!-- GSM Call settings screen, setting option name with label indicating the SIM the settings
@@ -253,7 +255,7 @@
     <!-- Call forwarding settings screen, setting summary text when forwarding to a specific number when unreachable-->
     <string name="sum_cfnrc_enabled">Forwarding to <xliff:g id="phonenumber" example="555-1212">{0}</xliff:g></string>
     <!-- Call forwarding settings screen, setting summary text when Forward when unreachable is disabled -->
-    <string name="sum_cfnrc_disabled">Disabled</string>
+    <string name="sum_cfnrc_disabled">Off</string>
     <!-- Error message displayed after failing to disable forwarding calls when the phone is unreachable -->
     <string name="disable_cfnrc_forbidden">Your carrier doesn\'t support disabling call forwarding when your phone is unreachable.</string>
 
@@ -354,7 +356,7 @@
 
     <!-- networks setting strings --><skip/>
     <!-- Mobile network settings screen title -->
-    <string name="mobile_networks">Cellular network settings</string>
+    <string name="mobile_networks">Mobile network settings</string>
     <!-- Available networks screen title/heading -->
     <string name="label_available">Available networks</string>
     <!-- Mobile network settings screen, toast when searching for available networks -->
@@ -450,11 +452,11 @@
         <item>"1"</item>
         <item>"0"</item>
     </string-array>
-    <!-- Cellular network 4G title [CHAR LIMIT=30] -->
+    <!-- Mobile network 4G title [CHAR LIMIT=30] -->
     <string name="enhanced_4g_lte_mode_title">Enhanced 4G LTE Mode</string>
     <!-- Carrier variant of Enhaced 4G LTE Mode title.  [CHAR LIMIT=50] -->
     <string name="enhanced_4g_lte_mode_title_variant">Advanced Calling</string>
-    <!-- Cellular network 4G summary [CHAR LIMIT=80] -->
+    <!-- Mobile network 4G summary [CHAR LIMIT=80] -->
     <string name="enhanced_4g_lte_mode_summary">Use LTE services to improve voice and other communications (recommended)</string>
 
     <!-- Mobile network settings screen, data enabling checkbox name -->
@@ -505,7 +507,7 @@
 
     <string name="throttle_rate_subtext">Data rate reduced to <xliff:g id="used">%1$d</xliff:g> Kb/s if data use limit is exceeded</string>
 
-    <string name="throttle_help_subtext">More information about your carrier\'s cellular network data use policy</string>
+    <string name="throttle_help_subtext">More information about your carrier\'s mobile network data use policy</string>
 
     <string name="cell_broadcast_sms">Cell Broadcast SMS</string>
 
@@ -838,7 +840,7 @@
     <!-- FDN settings: error message displayed in a popup (toast) -->
     <string name="pin2_invalid">FDN wasn\'t updated because you typed an incorrect PIN.</string>
     <!-- FDN settings: error message displayed in a popup (toast) -->
-    <string name="fdn_invalid_number">FDN wasn\'t updated because the number can\'t exceed 20 digits.</string>
+    <string name="fdn_invalid_number">FDN wasn\'t updated because the number is empty or exceeds 20 digits.</string>
     <!-- FDN settings: error message displayed in a popup (toast), when the entered
          FDN number was inappropriate, OR, PIN2 the user entered was incorrect.
          Because of API restriction, there's no way to determine which is the exact
@@ -990,9 +992,9 @@
          This string is currently unused (see comments in InCallScreen.java.) -->
     <string name="incall_error_emergency_only">Not registered on network.</string>
     <!-- In-call screen: call failure message displayed in an error dialog -->
-    <string name="incall_error_out_of_service">Cellular network not available.</string>
+    <string name="incall_error_out_of_service">Mobile network not available.</string>
     <!-- In-call screen: call failure message displayed in an error dialog -->
-    <string name="incall_error_out_of_service_wfc">Cellular network is not available. Connect to a wireless network to make a call.</string>
+    <string name="incall_error_out_of_service_wfc">Mobile network is not available. Connect to a wireless network to make a call.</string>
     <!-- In-call screen: call failure message displayed in an error dialog -->
     <string name="incall_error_no_phone_number_supplied">To place a call, enter a valid number.</string>
     <!-- In-call screen: call failure message displayed in an error dialog -->
diff --git a/res/xml/network_setting.xml b/res/xml/network_setting_fragment.xml
similarity index 100%
rename from res/xml/network_setting.xml
rename to res/xml/network_setting_fragment.xml
diff --git a/src/com/android/phone/CallFeaturesSetting.java b/src/com/android/phone/CallFeaturesSetting.java
index 111e263..47833ea 100644
--- a/src/com/android/phone/CallFeaturesSetting.java
+++ b/src/com/android/phone/CallFeaturesSetting.java
@@ -249,6 +249,8 @@
 
         Preference cdmaOptions = prefSet.findPreference(BUTTON_CDMA_OPTIONS);
         Preference gsmOptions = prefSet.findPreference(BUTTON_GSM_UMTS_OPTIONS);
+        Preference fdnButton = prefSet.findPreference(BUTTON_FDN_KEY);
+        fdnButton.setIntent(mSubscriptionInfoHelper.getIntent(FdnSetting.class));
         if (carrierConfig.getBoolean(CarrierConfigManager.KEY_WORLD_PHONE_BOOL)) {
             cdmaOptions.setIntent(mSubscriptionInfoHelper.getIntent(CdmaCallOptions.class));
             gsmOptions.setIntent(mSubscriptionInfoHelper.getIntent(GsmUmtsCallOptions.class));
@@ -257,7 +259,6 @@
             prefSet.removePreference(gsmOptions);
 
             int phoneType = mPhone.getPhoneType();
-            Preference fdnButton = prefSet.findPreference(BUTTON_FDN_KEY);
             if (carrierConfig.getBoolean(CarrierConfigManager.KEY_HIDE_CARRIER_NETWORK_SETTINGS_BOOL)) {
                 prefSet.removePreference(fdnButton);
             } else {
@@ -269,7 +270,6 @@
                         addPreferencesFromResource(R.xml.cdma_call_privacy);
                     }
                 } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
-                    fdnButton.setIntent(mSubscriptionInfoHelper.getIntent(FdnSetting.class));
 
                     if (carrierConfig.getBoolean(
                             CarrierConfigManager.KEY_ADDITIONAL_CALL_SETTING_BOOL)) {
diff --git a/src/com/android/phone/CarrierConfigLoader.java b/src/com/android/phone/CarrierConfigLoader.java
index 47bb064..357b470 100644
--- a/src/com/android/phone/CarrierConfigLoader.java
+++ b/src/com/android/phone/CarrierConfigLoader.java
@@ -83,8 +83,9 @@
 
 public class CarrierConfigLoader extends ICarrierConfigLoader.Stub {
     private static final String LOG_TAG = "CarrierConfigLoader";
-    // Package name for default carrier config app, bundled with system image.
-    private static final String DEFAULT_CARRIER_CONFIG_PACKAGE = "com.android.carrierconfig";
+
+    // Package name for platform carrier config app, bundled with system image.
+    private final String mPlatformCarrierConfigPackage;
 
     /** The singleton instance. */
     private static CarrierConfigLoader sInstance;
@@ -196,16 +197,16 @@
 
                 case EVENT_FETCH_DEFAULT:
                     iccid = getIccIdForPhoneId(phoneId);
-                    config = restoreConfigFromXml(DEFAULT_CARRIER_CONFIG_PACKAGE, iccid);
+                    config = restoreConfigFromXml(mPlatformCarrierConfigPackage, iccid);
                     if (config != null) {
-                        log("Loaded config from XML. package=" + DEFAULT_CARRIER_CONFIG_PACKAGE
+                        log("Loaded config from XML. package=" + mPlatformCarrierConfigPackage
                                 + " phoneId=" + phoneId);
                         mConfigFromDefaultApp[phoneId] = config;
                         Message newMsg = obtainMessage(EVENT_LOADED_FROM_DEFAULT, phoneId, -1);
                         newMsg.getData().putBoolean("loaded_from_xml", true);
                         mHandler.sendMessage(newMsg);
                     } else {
-                        if (bindToConfigPackage(DEFAULT_CARRIER_CONFIG_PACKAGE,
+                        if (bindToConfigPackage(mPlatformCarrierConfigPackage,
                                 phoneId, EVENT_CONNECTED_TO_DEFAULT)) {
                             sendMessageDelayed(obtainMessage(EVENT_BIND_DEFAULT_TIMEOUT, phoneId, -1),
                                     BIND_TIMEOUT_MILLIS);
@@ -230,7 +231,7 @@
                                 .asInterface(conn.service);
                         config = carrierService.getCarrierConfig(carrierId);
                         iccid = getIccIdForPhoneId(phoneId);
-                        saveConfigToXml(DEFAULT_CARRIER_CONFIG_PACKAGE, iccid, config);
+                        saveConfigToXml(mPlatformCarrierConfigPackage, iccid, config);
                         mConfigFromDefaultApp[phoneId] = config;
                         sendMessage(obtainMessage(EVENT_LOADED_FROM_DEFAULT, phoneId, -1));
                     } catch (Exception ex) {
@@ -349,6 +350,8 @@
      */
     private CarrierConfigLoader(Context context) {
         mContext = context;
+        mPlatformCarrierConfigPackage =
+                mContext.getString(R.string.platform_carrier_config_package);
 
         IntentFilter bootFilter = new IntentFilter();
         bootFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
diff --git a/src/com/android/phone/CdmaOptions.java b/src/com/android/phone/CdmaOptions.java
index a02d3df..a760cda 100644
--- a/src/com/android/phone/CdmaOptions.java
+++ b/src/com/android/phone/CdmaOptions.java
@@ -16,18 +16,14 @@
 
 package com.android.phone;
 
-import android.content.Context;
 import android.content.Intent;
-import android.content.res.Resources;
-import android.net.Uri;
 import android.os.PersistableBundle;
 import android.os.SystemProperties;
 import android.preference.Preference;
-import android.preference.PreferenceActivity;
+import android.preference.PreferenceFragment;
 import android.preference.PreferenceScreen;
 import android.provider.Settings;
 import android.telephony.CarrierConfigManager;
-import android.telephony.TelephonyManager;
 import android.text.TextUtils;
 
 import com.android.internal.telephony.Phone;
@@ -48,19 +44,19 @@
     private static final String BUTTON_CARRIER_SETTINGS_KEY = "carrier_settings_key";
     private static final String BUTTON_APN_EXPAND_KEY = "button_apn_key_cdma";
 
-    private PreferenceActivity mPrefActivity;
+    private PreferenceFragment mPrefFragment;
     private PreferenceScreen mPrefScreen;
     private Phone mPhone;
 
-    public CdmaOptions(PreferenceActivity prefActivity, PreferenceScreen prefScreen, Phone phone) {
-        mPrefActivity = prefActivity;
+    public CdmaOptions(PreferenceFragment prefFragment, PreferenceScreen prefScreen, Phone phone) {
+        mPrefFragment = prefFragment;
         mPrefScreen = prefScreen;
         mPhone = phone;
         create();
     }
 
     protected void create() {
-        mPrefActivity.addPreferencesFromResource(R.xml.cdma_options);
+        mPrefFragment.addPreferencesFromResource(R.xml.cdma_options);
 
         mButtonAPNExpand = (PreferenceScreen) mPrefScreen.findPreference(BUTTON_APN_EXPAND_KEY);
         boolean removedAPNExpand = false;
@@ -84,7 +80,7 @@
                             // This will setup the Home and Search affordance
                             intent.putExtra(":settings:show_fragment_as_subsetting", true);
                             intent.putExtra("sub_id", mPhone.getSubId());
-                            mPrefActivity.startActivity(intent);
+                            mPrefFragment.startActivity(intent);
                             return true;
                         }
             });
diff --git a/src/com/android/phone/GsmUmtsOptions.java b/src/com/android/phone/GsmUmtsOptions.java
index 2e9d88a..70ba4af 100644
--- a/src/com/android/phone/GsmUmtsOptions.java
+++ b/src/com/android/phone/GsmUmtsOptions.java
@@ -16,12 +16,11 @@
 
 package com.android.phone;
 
-import android.content.Context;
 import android.content.Intent;
 import android.content.res.Resources;
 import android.os.PersistableBundle;
 import android.preference.Preference;
-import android.preference.PreferenceActivity;
+import android.preference.PreferenceFragment;
 import android.preference.PreferenceScreen;
 import android.provider.Settings;
 import android.telephony.CarrierConfigManager;
@@ -43,20 +42,20 @@
     private static final String BUTTON_OPERATOR_SELECTION_EXPAND_KEY = "button_carrier_sel_key";
     private static final String BUTTON_CARRIER_SETTINGS_KEY = "carrier_settings_key";
     public static final String EXTRA_SUB_ID = "sub_id";
-    private PreferenceActivity mPrefActivity;
+    private PreferenceFragment mPrefFragment;
     private PreferenceScreen mPrefScreen;
     private int mSubId;
 
-    public GsmUmtsOptions(PreferenceActivity prefActivity, PreferenceScreen prefScreen,
+    public GsmUmtsOptions(PreferenceFragment prefFragment, PreferenceScreen prefScreen,
             final int subId) {
-        mPrefActivity = prefActivity;
+        mPrefFragment = prefFragment;
         mPrefScreen = prefScreen;
         mSubId = subId;
         create();
     }
 
     protected void create() {
-        mPrefActivity.addPreferencesFromResource(R.xml.gsm_umts_options);
+        mPrefFragment.addPreferencesFromResource(R.xml.gsm_umts_options);
         mButtonAPNExpand = (PreferenceScreen) mPrefScreen.findPreference(BUTTON_APN_EXPAND_KEY);
         boolean removedAPNExpand = false;
         mButtonOperatorSelectionExpand =
@@ -67,7 +66,7 @@
             mButtonOperatorSelectionExpand.setEnabled(false);
         } else {
             log("Not a CDMA phone");
-            Resources res = mPrefActivity.getResources();
+            Resources res = mPrefFragment.getResources();
             PersistableBundle carrierConfig =
                     PhoneGlobals.getInstance().getCarrierConfigForSubId(mSubId);
 
@@ -120,7 +119,7 @@
                             // This will setup the Home and Search affordance
                             intent.putExtra(":settings:show_fragment_as_subsetting", true);
                             intent.putExtra(EXTRA_SUB_ID, mSubId);
-                            mPrefActivity.startActivity(intent);
+                            mPrefFragment.startActivity(intent);
                             return true;
                         }
             });
@@ -134,7 +133,7 @@
                             intent.setComponent(new ComponentName("com.android.phone",
                                     "com.android.phone.NetworkSetting"));
                             intent.putExtra(EXTRA_SUB_ID, mSubId);
-                            mPrefActivity.startActivity(intent);
+                            mPrefFragment.startActivity(intent);
                             return true;
                         }
             });
diff --git a/src/com/android/phone/MobileNetworkSettings.java b/src/com/android/phone/MobileNetworkSettings.java
index 56b6390..b8c2fb3 100644
--- a/src/com/android/phone/MobileNetworkSettings.java
+++ b/src/com/android/phone/MobileNetworkSettings.java
@@ -16,6 +16,41 @@
 
 package com.android.phone;
 
+import android.app.ActionBar;
+import android.app.DialogFragment;
+import android.app.Fragment;
+import android.app.FragmentManager;
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageManager;
+import android.net.Uri;
+import android.os.AsyncResult;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.os.PersistableBundle;
+import android.os.SystemProperties;
+import android.os.UserHandle;
+import android.os.UserManager;
+import android.preference.ListPreference;
+import android.preference.Preference;
+import android.preference.PreferenceFragment;
+import android.preference.PreferenceScreen;
+import android.preference.SwitchPreference;
+import android.telephony.CarrierConfigManager;
+import android.telephony.PhoneStateListener;
+import android.telephony.SubscriptionInfo;
+import android.telephony.SubscriptionManager;
+import android.telephony.TelephonyManager;
+import android.text.TextUtils;
+import android.util.Log;
+import android.view.MenuItem;
+import android.view.View;
+import android.widget.TabHost;
+
 import com.android.ims.ImsManager;
 import com.android.internal.telephony.Phone;
 import com.android.internal.telephony.PhoneConstants;
@@ -28,1330 +63,1324 @@
 import java.util.Iterator;
 import java.util.List;
 
-import android.app.ActionBar;
-import android.app.AlertDialog;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.net.Uri;
-import android.os.AsyncResult;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.os.PersistableBundle;
-import android.os.SystemProperties;
-import android.os.UserHandle;
-import android.os.UserManager;
-import android.preference.ListPreference;
-import android.preference.Preference;
-import android.preference.PreferenceActivity;
-import android.preference.PreferenceScreen;
-import android.preference.SwitchPreference;
-import android.telephony.CarrierConfigManager;
-import android.telephony.PhoneStateListener;
-import android.telephony.SubscriptionInfo;
-import android.telephony.SubscriptionManager;
-import android.telephony.TelephonyManager;
-import android.text.TextUtils;
-import android.util.Log;
-import android.view.MenuItem;
-import android.view.View;
-import android.widget.TabHost.OnTabChangeListener;
-import android.widget.TabHost.TabContentFactory;
-import android.widget.TabHost.TabSpec;
-import android.widget.TabHost;
-
 /**
- * "Mobile network settings" screen.  This preference screen lets you
+ * "Mobile network settings" screen.  This screen lets you
  * enable/disable mobile data, and control data roaming and other
  * network-specific mobile data features.  It's used on non-voice-capable
  * tablets as well as regular phone devices.
  *
- * Note that this PreferenceActivity is part of the phone app, even though
+ * Note that this Activity is part of the phone app, even though
  * you reach it from the "Wireless & Networks" section of the main
  * Settings app.  It's not part of the "Call settings" hierarchy that's
  * available from the Phone app (see CallFeaturesSetting for that.)
  */
-public class MobileNetworkSettings extends PreferenceActivity
-        implements DialogInterface.OnClickListener,
-        DialogInterface.OnDismissListener, Preference.OnPreferenceChangeListener{
 
-    // debug data
-    private static final String LOG_TAG = "NetworkSettings";
-    private static final boolean DBG = true;
-    public static final int REQUEST_CODE_EXIT_ECM = 17;
-
-    // Number of active Subscriptions to show tabs
-    private static final int TAB_THRESHOLD = 2;
-
-    //String keys for preference lookup
-    private static final String BUTTON_PREFERED_NETWORK_MODE = "preferred_network_mode_key";
-    private static final String BUTTON_ROAMING_KEY = "button_roaming_key";
-    private static final String BUTTON_CDMA_LTE_DATA_SERVICE_KEY = "cdma_lte_data_service_key";
-    private static final String BUTTON_ENABLED_NETWORKS_KEY = "enabled_networks_key";
-    private static final String BUTTON_4G_LTE_KEY = "enhanced_4g_lte";
-    private static final String BUTTON_CELL_BROADCAST_SETTINGS = "cell_broadcast_settings";
-    private static final String BUTTON_APN_EXPAND_KEY = "button_apn_key";
-    private static final String BUTTON_OPERATOR_SELECTION_EXPAND_KEY = "button_carrier_sel_key";
-    private static final String BUTTON_CARRIER_SETTINGS_KEY = "carrier_settings_key";
-    private static final String BUTTON_CDMA_SYSTEM_SELECT_KEY = "cdma_system_select_key";
-
-    static final int preferredNetworkMode = Phone.PREFERRED_NT_MODE;
-
-    //Information about logical "up" Activity
-    private static final String UP_ACTIVITY_PACKAGE = "com.android.settings";
-    private static final String UP_ACTIVITY_CLASS =
-            "com.android.settings.Settings$WirelessSettingsActivity";
-
-    private SubscriptionManager mSubscriptionManager;
-
-    //UI objects
-    private ListPreference mButtonPreferredNetworkMode;
-    private ListPreference mButtonEnabledNetworks;
-    private RestrictedSwitchPreference mButtonDataRoam;
-    private SwitchPreference mButton4glte;
-    private Preference mLteDataServicePref;
-
-    private static final String iface = "rmnet0"; //TODO: this will go away
-    private List<SubscriptionInfo> mActiveSubInfos;
-
-    private UserManager mUm;
-    private Phone mPhone;
-    private MyHandler mHandler;
-    private boolean mOkClicked;
-
-    // We assume the the value returned by mTabHost.getCurrentTab() == slotId
-    private TabHost mTabHost;
-
-    //GsmUmts options and Cdma options
-    GsmUmtsOptions mGsmUmtsOptions;
-    CdmaOptions mCdmaOptions;
-
-    private Preference mClickedPreference;
-    private boolean mShow4GForLTE;
-    private boolean mIsGlobalCdma;
-    private boolean mUnavailable;
-
-    private final PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
-        /*
-         * Enable/disable the 'Enhanced 4G LTE Mode' when in/out of a call
-         * and depending on TTY mode and TTY support over VoLTE.
-         * @see android.telephony.PhoneStateListener#onCallStateChanged(int,
-         * java.lang.String)
-         */
-        @Override
-        public void onCallStateChanged(int state, String incomingNumber) {
-            if (DBG) log("PhoneStateListener.onCallStateChanged: state=" + state);
-            boolean enabled = (state == TelephonyManager.CALL_STATE_IDLE) &&
-                    ImsManager.isNonTtyOrTtyOnVolteEnabled(getApplicationContext());
-            Preference pref = getPreferenceScreen().findPreference(BUTTON_4G_LTE_KEY);
-            if (pref != null) pref.setEnabled(enabled && hasActiveSubscriptions());
-        }
-    };
-
-    private final BroadcastReceiver mPhoneChangeReceiver = new PhoneChangeReceiver();
-
-    private class PhoneChangeReceiver extends BroadcastReceiver {
-        @Override
-        public void onReceive(Context context, Intent intent) {
-            if (DBG) log("onReceive:");
-            // When the radio changes (ex: CDMA->GSM), refresh all options.
-            mGsmUmtsOptions = null;
-            mCdmaOptions = null;
-            updateBody();
-        }
-    }
-
-    //This is a method implemented for DialogInterface.OnClickListener.
-    //  Used to dismiss the dialogs when they come up.
-    public void onClick(DialogInterface dialog, int which) {
-        if (which == DialogInterface.BUTTON_POSITIVE) {
-            mPhone.setDataRoamingEnabled(true);
-            mOkClicked = true;
-        } else {
-            // Reset the toggle
-            mButtonDataRoam.setChecked(false);
-        }
-    }
-
-    @Override
-    public void onDismiss(DialogInterface dialog) {
-        // Assuming that onClick gets called first
-        mButtonDataRoam.setChecked(mOkClicked);
-    }
-
-    /**
-     * Invoked on each preference click in this hierarchy, overrides
-     * PreferenceActivity's implementation.  Used to make sure we track the
-     * preference click events.
-     */
-    @Override
-    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
-        /** TODO: Refactor and get rid of the if's using subclasses */
-        final int phoneSubId = mPhone.getSubId();
-        if (preference.getKey().equals(BUTTON_4G_LTE_KEY)) {
-            return true;
-        } else if (mGsmUmtsOptions != null &&
-                mGsmUmtsOptions.preferenceTreeClick(preference) == true) {
-            return true;
-        } else if (mCdmaOptions != null &&
-                   mCdmaOptions.preferenceTreeClick(preference) == true) {
-            if (Boolean.parseBoolean(
-                    SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE))) {
-
-                mClickedPreference = preference;
-
-                // In ECM mode launch ECM app dialog
-                startActivityForResult(
-                    new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, null),
-                    REQUEST_CODE_EXIT_ECM);
-            }
-            return true;
-        } else if (preference == mButtonPreferredNetworkMode) {
-            //displays the value taken from the Settings.System
-            int settingsNetworkMode = android.provider.Settings.Global.getInt(mPhone.getContext().
-                    getContentResolver(),
-                    android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
-                    preferredNetworkMode);
-            mButtonPreferredNetworkMode.setValue(Integer.toString(settingsNetworkMode));
-            return true;
-        } else if (preference == mLteDataServicePref) {
-            String tmpl = android.provider.Settings.Global.getString(getContentResolver(),
-                        android.provider.Settings.Global.SETUP_PREPAID_DATA_SERVICE_URL);
-            if (!TextUtils.isEmpty(tmpl)) {
-                TelephonyManager tm = (TelephonyManager) getSystemService(
-                        Context.TELEPHONY_SERVICE);
-                String imsi = tm.getSubscriberId();
-                if (imsi == null) {
-                    imsi = "";
-                }
-                final String url = TextUtils.isEmpty(tmpl) ? null
-                        : TextUtils.expandTemplate(tmpl, imsi).toString();
-                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
-                startActivity(intent);
-            } else {
-                android.util.Log.e(LOG_TAG, "Missing SETUP_PREPAID_DATA_SERVICE_URL");
-            }
-            return true;
-        }  else if (preference == mButtonEnabledNetworks) {
-            int settingsNetworkMode = android.provider.Settings.Global.getInt(mPhone.getContext().
-                            getContentResolver(),
-                    android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
-                    preferredNetworkMode);
-            mButtonEnabledNetworks.setValue(Integer.toString(settingsNetworkMode));
-            return true;
-        } else if (preference == mButtonDataRoam) {
-            // Do not disable the preference screen if the user clicks Data roaming.
-            return true;
-        } else {
-            // if the button is anything but the simple toggle preference,
-            // we'll need to disable all preferences to reject all click
-            // events until the sub-activity's UI comes up.
-            preferenceScreen.setEnabled(false);
-            // Let the intents be launched by the Preference manager
-            return false;
-        }
-    }
-
-    private final SubscriptionManager.OnSubscriptionsChangedListener mOnSubscriptionsChangeListener
-            = new SubscriptionManager.OnSubscriptionsChangedListener() {
-        @Override
-        public void onSubscriptionsChanged() {
-            if (DBG) log("onSubscriptionsChanged:");
-            initializeSubscriptions();
-        }
-    };
-
-    private void initializeSubscriptions() {
-        if (isDestroyed()) { // Process preferences in activity only if its not destroyed
-            return;
-        }
-        int currentTab = 0;
-        if (DBG) log("initializeSubscriptions:+");
-
-        // Before updating the the active subscription list check
-        // if tab updating is needed as the list is changing.
-        List<SubscriptionInfo> sil = mSubscriptionManager.getActiveSubscriptionInfoList();
-        TabState state = isUpdateTabsNeeded(sil);
-
-        // Update to the active subscription list
-        mActiveSubInfos.clear();
-        if (sil != null) {
-            mActiveSubInfos.addAll(sil);
-            // If there is only 1 sim then currenTab should represent slot no. of the sim.
-            if (sil.size() == 1) {
-                currentTab = sil.get(0).getSimSlotIndex();
-            }
-        }
-
-        switch (state) {
-            case UPDATE: {
-                if (DBG) log("initializeSubscriptions: UPDATE");
-                currentTab = mTabHost != null ? mTabHost.getCurrentTab() : 0;
-
-                setContentView(com.android.internal.R.layout.common_tab_settings);
-
-                mTabHost = (TabHost) findViewById(android.R.id.tabhost);
-                mTabHost.setup();
-
-                // Update the tabName. Since the mActiveSubInfos are in slot order
-                // we can iterate though the tabs and subscription info in one loop. But
-                // we need to handle the case where a slot may be empty.
-
-                Iterator<SubscriptionInfo> siIterator = mActiveSubInfos.listIterator();
-                SubscriptionInfo si = siIterator.hasNext() ? siIterator.next() : null;
-                for (int simSlotIndex = 0; simSlotIndex  < mActiveSubInfos.size(); simSlotIndex++) {
-                    String tabName;
-                    if (si != null && si.getSimSlotIndex() == simSlotIndex) {
-                        // Slot is not empty and we match
-                        tabName = String.valueOf(si.getDisplayName());
-                        si = siIterator.hasNext() ? siIterator.next() : null;
-                    } else {
-                        // Slot is empty, set name to unknown
-                        tabName = getResources().getString(R.string.unknown);
-                    }
-                    if (DBG) {
-                        log("initializeSubscriptions: tab=" + simSlotIndex + " name=" + tabName);
-                    }
-
-                    mTabHost.addTab(buildTabSpec(String.valueOf(simSlotIndex), tabName));
-                }
-
-                mTabHost.setOnTabChangedListener(mTabListener);
-                mTabHost.setCurrentTab(currentTab);
-                break;
-            }
-            case NO_TABS: {
-                if (DBG) log("initializeSubscriptions: NO_TABS");
-
-                if (mTabHost != null) {
-                    mTabHost.clearAllTabs();
-                    mTabHost = null;
-                }
-                setContentView(com.android.internal.R.layout.common_tab_settings);
-                break;
-            }
-            case DO_NOTHING: {
-                if (DBG) log("initializeSubscriptions: DO_NOTHING");
-                if (mTabHost != null) {
-                    currentTab = mTabHost.getCurrentTab();
-                }
-                break;
-            }
-        }
-        updatePhone(currentTab);
-        updateBody();
-        if (DBG) log("initializeSubscriptions:-");
-    }
+public class MobileNetworkSettings extends Activity  {
 
     private enum TabState {
         NO_TABS, UPDATE, DO_NOTHING
     }
-    private TabState isUpdateTabsNeeded(List<SubscriptionInfo> newSil) {
-        TabState state = TabState.DO_NOTHING;
-        if (newSil == null) {
-            if (mActiveSubInfos.size() >= TAB_THRESHOLD) {
-                if (DBG) log("isUpdateTabsNeeded: NO_TABS, size unknown and was tabbed");
-                state = TabState.NO_TABS;
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setContentView(R.layout.network_setting);
+
+        FragmentManager fragmentManager = getFragmentManager();
+        Fragment fragment = fragmentManager.findFragmentById(R.id.network_setting_content);
+        if (fragment == null) {
+            fragmentManager.beginTransaction()
+                    .add(R.id.network_setting_content, new MobileNetworkFragment())
+                    .commit();
+        }
+    }
+
+    public static class MobileNetworkFragment extends PreferenceFragment implements
+            Preference.OnPreferenceChangeListener, RoamingDialogFragment.RoamingDialogListener {
+
+        // debug data
+        private static final String LOG_TAG = "NetworkSettings";
+        private static final boolean DBG = true;
+        public static final int REQUEST_CODE_EXIT_ECM = 17;
+
+        // Number of active Subscriptions to show tabs
+        private static final int TAB_THRESHOLD = 2;
+
+        // fragment tag for roaming data dialog
+        private static final String ROAMING_TAG = "RoamingDialogFragment";
+
+        //String keys for preference lookup
+        private static final String BUTTON_PREFERED_NETWORK_MODE = "preferred_network_mode_key";
+        private static final String BUTTON_ROAMING_KEY = "button_roaming_key";
+        private static final String BUTTON_CDMA_LTE_DATA_SERVICE_KEY = "cdma_lte_data_service_key";
+        private static final String BUTTON_ENABLED_NETWORKS_KEY = "enabled_networks_key";
+        private static final String BUTTON_4G_LTE_KEY = "enhanced_4g_lte";
+        private static final String BUTTON_CELL_BROADCAST_SETTINGS = "cell_broadcast_settings";
+        private static final String BUTTON_APN_EXPAND_KEY = "button_apn_key";
+        private static final String BUTTON_OPERATOR_SELECTION_EXPAND_KEY = "button_carrier_sel_key";
+        private static final String BUTTON_CARRIER_SETTINGS_KEY = "carrier_settings_key";
+        private static final String BUTTON_CDMA_SYSTEM_SELECT_KEY = "cdma_system_select_key";
+
+        private final BroadcastReceiver mPhoneChangeReceiver = new PhoneChangeReceiver();
+
+        static final int preferredNetworkMode = Phone.PREFERRED_NT_MODE;
+
+        //Information about logical "up" Activity
+        private static final String UP_ACTIVITY_PACKAGE = "com.android.settings";
+        private static final String UP_ACTIVITY_CLASS =
+                "com.android.settings.Settings$WirelessSettingsActivity";
+
+        private SubscriptionManager mSubscriptionManager;
+
+        //UI objects
+        private ListPreference mButtonPreferredNetworkMode;
+        private ListPreference mButtonEnabledNetworks;
+        private RestrictedSwitchPreference mButtonDataRoam;
+        private SwitchPreference mButton4glte;
+        private Preference mLteDataServicePref;
+
+        private static final String iface = "rmnet0"; //TODO: this will go away
+        private List<SubscriptionInfo> mActiveSubInfos;
+
+        private UserManager mUm;
+        private Phone mPhone;
+        private MyHandler mHandler;
+        private boolean mOkClicked;
+
+        // We assume the the value returned by mTabHost.getCurrentTab() == slotId
+        private TabHost mTabHost;
+
+        //GsmUmts options and Cdma options
+        GsmUmtsOptions mGsmUmtsOptions;
+        CdmaOptions mCdmaOptions;
+
+        private Preference mClickedPreference;
+        private boolean mShow4GForLTE;
+        private boolean mIsGlobalCdma;
+        private boolean mUnavailable;
+
+        private final PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
+            /*
+             * Enable/disable the 'Enhanced 4G LTE Mode' when in/out of a call
+             * and depending on TTY mode and TTY support over VoLTE.
+             * @see android.telephony.PhoneStateListener#onCallStateChanged(int,
+             * java.lang.String)
+             */
+            @Override
+            public void onCallStateChanged(int state, String incomingNumber) {
+                if (DBG) log("PhoneStateListener.onCallStateChanged: state=" + state);
+                boolean enabled = (state == TelephonyManager.CALL_STATE_IDLE) &&
+                        ImsManager.isNonTtyOrTtyOnVolteEnabled
+                                (getActivity().getApplicationContext());
+                Preference pref = getPreferenceScreen().findPreference(BUTTON_4G_LTE_KEY);
+                if (pref != null) pref.setEnabled(enabled && hasActiveSubscriptions());
+
             }
-        } else if (newSil.size() < TAB_THRESHOLD && mActiveSubInfos.size() >= TAB_THRESHOLD) {
-            if (DBG) log("isUpdateTabsNeeded: NO_TABS, size went to small");
-            state = TabState.NO_TABS;
-        } else if (newSil.size() >= TAB_THRESHOLD && mActiveSubInfos.size() < TAB_THRESHOLD) {
-            if (DBG) log("isUpdateTabsNeeded: UPDATE, size changed");
-            state = TabState.UPDATE;
-        } else if (newSil.size() >= TAB_THRESHOLD) {
-            Iterator<SubscriptionInfo> siIterator = mActiveSubInfos.iterator();
-            for(SubscriptionInfo newSi : newSil) {
-                SubscriptionInfo curSi = siIterator.next();
-                if (!newSi.getDisplayName().equals(curSi.getDisplayName())) {
-                    if (DBG) log("isUpdateTabsNeeded: UPDATE, new name=" + newSi.getDisplayName());
-                    state = TabState.UPDATE;
+        };
+
+        @Override
+        public void onPositiveButtonClick(DialogFragment dialog) {
+            mPhone.setDataRoamingEnabled(true);
+            mButtonDataRoam.setChecked(true);
+        }
+
+        /**
+         * Invoked on each preference click in this hierarchy, overrides
+         * PreferenceActivity's implementation.  Used to make sure we track the
+         * preference click events.
+         */
+        @Override
+        public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
+                                             Preference preference) {
+            /** TODO: Refactor and get rid of the if's using subclasses */
+            final int phoneSubId = mPhone.getSubId();
+            if (preference.getKey().equals(BUTTON_4G_LTE_KEY)) {
+                return true;
+            } else if (mGsmUmtsOptions != null &&
+                    mGsmUmtsOptions.preferenceTreeClick(preference) == true) {
+                return true;
+            } else if (mCdmaOptions != null &&
+                    mCdmaOptions.preferenceTreeClick(preference) == true) {
+                if (Boolean.parseBoolean(
+                        SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE))) {
+
+                    mClickedPreference = preference;
+
+                    // In ECM mode launch ECM app dialog
+                    startActivityForResult(
+                            new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, null),
+                            REQUEST_CODE_EXIT_ECM);
+                }
+                return true;
+            } else if (preference == mButtonPreferredNetworkMode) {
+                //displays the value taken from the Settings.System
+                int settingsNetworkMode = android.provider.Settings.Global.getInt(
+                        mPhone.getContext().getContentResolver(),
+                        android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
+                        preferredNetworkMode);
+                mButtonPreferredNetworkMode.setValue(Integer.toString(settingsNetworkMode));
+                return true;
+            } else if (preference == mLteDataServicePref) {
+                String tmpl = android.provider.Settings.Global.getString(
+                        getActivity().getContentResolver(),
+                        android.provider.Settings.Global.SETUP_PREPAID_DATA_SERVICE_URL);
+                if (!TextUtils.isEmpty(tmpl)) {
+                    TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(
+                            Context.TELEPHONY_SERVICE);
+                    String imsi = tm.getSubscriberId();
+                    if (imsi == null) {
+                        imsi = "";
+                    }
+                    final String url = TextUtils.isEmpty(tmpl) ? null
+                            : TextUtils.expandTemplate(tmpl, imsi).toString();
+                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
+                    startActivity(intent);
+                } else {
+                    android.util.Log.e(LOG_TAG, "Missing SETUP_PREPAID_DATA_SERVICE_URL");
+                }
+                return true;
+            }  else if (preference == mButtonEnabledNetworks) {
+                int settingsNetworkMode = android.provider.Settings.Global.getInt(
+                        mPhone.getContext().getContentResolver(),
+                        android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
+                        preferredNetworkMode);
+                mButtonEnabledNetworks.setValue(Integer.toString(settingsNetworkMode));
+                return true;
+            } else if (preference == mButtonDataRoam) {
+                // Do not disable the preference screen if the user clicks Data roaming.
+                return true;
+            } else {
+                // if the button is anything but the simple toggle preference,
+                // we'll need to disable all preferences to reject all click
+                // events until the sub-activity's UI comes up.
+                preferenceScreen.setEnabled(false);
+                // Let the intents be launched by the Preference manager
+                return false;
+            }
+        }
+
+        private final SubscriptionManager.OnSubscriptionsChangedListener
+                mOnSubscriptionsChangeListener
+                = new SubscriptionManager.OnSubscriptionsChangedListener() {
+            @Override
+            public void onSubscriptionsChanged() {
+                if (DBG) log("onSubscriptionsChanged:");
+                initializeSubscriptions();
+            }
+        };
+
+        private void initializeSubscriptions() {
+            if (getActivity().isDestroyed()) {
+                // Process preferences in activity only if its not destroyed
+                return;
+            }
+            int currentTab = 0;
+            if (DBG) log("initializeSubscriptions:+");
+
+            // Before updating the the active subscription list check
+            // if tab updating is needed as the list is changing.
+            List<SubscriptionInfo> sil = mSubscriptionManager.getActiveSubscriptionInfoList();
+            MobileNetworkSettings.TabState state = isUpdateTabsNeeded(sil);
+
+            // Update to the active subscription list
+            mActiveSubInfos.clear();
+            if (sil != null) {
+                mActiveSubInfos.addAll(sil);
+                // If there is only 1 sim then currenTab should represent slot no. of the sim.
+                if (sil.size() == 1) {
+                    currentTab = sil.get(0).getSimSlotIndex();
+                }
+            }
+
+            switch (state) {
+                case UPDATE: {
+                    if (DBG) log("initializeSubscriptions: UPDATE");
+                    currentTab = mTabHost != null ? mTabHost.getCurrentTab() : 0;
+
+                    getActivity().setContentView(com.android.internal.R.layout.common_tab_settings);
+
+                    mTabHost = (TabHost) getActivity().findViewById(android.R.id.tabhost);
+                    mTabHost.setup();
+
+                    // Update the tabName. Since the mActiveSubInfos are in slot order
+                    // we can iterate though the tabs and subscription info in one loop. But
+                    // we need to handle the case where a slot may be empty.
+
+                    Iterator<SubscriptionInfo> siIterator = mActiveSubInfos.listIterator();
+                    SubscriptionInfo si = siIterator.hasNext() ? siIterator.next() : null;
+                    for (int simSlotIndex = 0; simSlotIndex  < mActiveSubInfos.size();
+                         simSlotIndex++) {
+                        String tabName;
+                        if (si != null && si.getSimSlotIndex() == simSlotIndex) {
+                            // Slot is not empty and we match
+                            tabName = String.valueOf(si.getDisplayName());
+                            si = siIterator.hasNext() ? siIterator.next() : null;
+                        } else {
+                            // Slot is empty, set name to unknown
+                            tabName = getResources().getString(R.string.unknown);
+                        }
+                        if (DBG) {
+                            log("initializeSubscriptions:tab=" + simSlotIndex + " name=" + tabName);
+                        }
+
+                        mTabHost.addTab(buildTabSpec(String.valueOf(simSlotIndex), tabName));
+                    }
+
+                    mTabHost.setOnTabChangedListener(mTabListener);
+                    mTabHost.setCurrentTab(currentTab);
+                    break;
+                }
+                case NO_TABS: {
+                    if (DBG) log("initializeSubscriptions: NO_TABS");
+
+                    if (mTabHost != null) {
+                        mTabHost.clearAllTabs();
+                        mTabHost = null;
+                    }
+                    getActivity().setContentView(com.android.internal.R.layout.common_tab_settings);
+                    break;
+                }
+                case DO_NOTHING: {
+                    if (DBG) log("initializeSubscriptions: DO_NOTHING");
+                    if (mTabHost != null) {
+                        currentTab = mTabHost.getCurrentTab();
+                    }
                     break;
                 }
             }
-        }
-        if (DBG) {
-            log("isUpdateTabsNeeded:- " + state
-                + " newSil.size()=" + ((newSil != null) ? newSil.size() : 0)
-                + " mActiveSubInfos.size()=" + mActiveSubInfos.size());
-        }
-        return state;
-    }
-
-    private OnTabChangeListener mTabListener = new OnTabChangeListener() {
-        @Override
-        public void onTabChanged(String tabId) {
-            if (DBG) log("onTabChanged:");
-            // The User has changed tab; update the body.
-            updatePhone(Integer.parseInt(tabId));
+            updatePhone(currentTab);
             updateBody();
-        }
-    };
-
-    private void updatePhone(int slotId) {
-        final SubscriptionInfo sir = mSubscriptionManager
-                .getActiveSubscriptionInfoForSimSlotIndex(slotId);
-        if (sir != null) {
-            mPhone = PhoneFactory.getPhone(
-                    SubscriptionManager.getPhoneId(sir.getSubscriptionId()));
-        }
-        if (mPhone == null) {
-            // Do the best we can
-            mPhone = PhoneGlobals.getPhone();
-        }
-        if (DBG) log("updatePhone:- slotId=" + slotId + " sir=" + sir);
-    }
-
-    private TabContentFactory mEmptyTabContent = new TabContentFactory() {
-        @Override
-        public View createTabContent(String tag) {
-            return new View(mTabHost.getContext());
-        }
-    };
-
-    private TabSpec buildTabSpec(String tag, String title) {
-        return mTabHost.newTabSpec(tag).setIndicator(title).setContent(
-                mEmptyTabContent);
-    }
-
-    @Override
-    protected void onCreate(Bundle icicle) {
-        if (DBG) log("onCreate:+");
-        super.onCreate(icicle);
-
-        mHandler = new MyHandler();
-        mUm = (UserManager) getSystemService(Context.USER_SERVICE);
-        mSubscriptionManager = SubscriptionManager.from(this);
-
-        if (mUm.hasUserRestriction(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
-            mUnavailable = true;
-            setContentView(R.layout.telephony_disallowed_preference_screen);
-            return;
+            if (DBG) log("initializeSubscriptions:-");
         }
 
-        addPreferencesFromResource(R.xml.network_setting);
-
-        mButton4glte = (SwitchPreference)findPreference(BUTTON_4G_LTE_KEY);
-        mButton4glte.setOnPreferenceChangeListener(this);
-
-        try {
-            Context con = createPackageContext("com.android.systemui", 0);
-            int id = con.getResources().getIdentifier("config_show4GForLTE",
-                    "bool", "com.android.systemui");
-            mShow4GForLTE = con.getResources().getBoolean(id);
-        } catch (NameNotFoundException e) {
-            loge("NameNotFoundException for show4GFotLTE");
-            mShow4GForLTE = false;
-        }
-
-        //get UI object references
-        PreferenceScreen prefSet = getPreferenceScreen();
-
-        mButtonDataRoam = (RestrictedSwitchPreference) prefSet.findPreference(BUTTON_ROAMING_KEY);
-        mButtonPreferredNetworkMode = (ListPreference) prefSet.findPreference(
-                BUTTON_PREFERED_NETWORK_MODE);
-        mButtonEnabledNetworks = (ListPreference) prefSet.findPreference(
-                BUTTON_ENABLED_NETWORKS_KEY);
-        mButtonDataRoam.setOnPreferenceChangeListener(this);
-
-        mLteDataServicePref = prefSet.findPreference(BUTTON_CDMA_LTE_DATA_SERVICE_KEY);
-
-        // Initialize mActiveSubInfo
-        int max = mSubscriptionManager.getActiveSubscriptionInfoCountMax();
-        mActiveSubInfos = new ArrayList<SubscriptionInfo>(max);
-
-        initializeSubscriptions();
-
-        IntentFilter intentFilter = new IntentFilter(
-                TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED);
-        registerReceiver(mPhoneChangeReceiver, intentFilter);
-        if (DBG) log("onCreate:-");
-    }
-
-    @Override
-    protected void onDestroy() {
-        super.onDestroy();
-        unregisterReceiver(mPhoneChangeReceiver);
-    }
-
-    @Override
-    protected void onResume() {
-        super.onResume();
-        if (DBG) log("onResume:+");
-
-        if (mUnavailable) {
-            if (DBG) log("onResume:- ignore mUnavailable == false");
-            return;
-        }
-
-        // upon resumption from the sub-activity, make sure we re-enable the
-        // preferences.
-        getPreferenceScreen().setEnabled(true);
-
-        // Set UI state in onResume because a user could go home, launch some
-        // app to change this setting's backend, and re-launch this settings app
-        // and the UI state would be inconsistent with actual state
-        mButtonDataRoam.setChecked(mPhone.getDataRoamingEnabled());
-
-        if (getPreferenceScreen().findPreference(BUTTON_PREFERED_NETWORK_MODE) != null
-                || getPreferenceScreen().findPreference(BUTTON_ENABLED_NETWORKS_KEY) != null)  {
-            updatePreferredNetworkUIFromDb();
-        }
-
-        if (ImsManager.isVolteEnabledByPlatform(this)
-                && ImsManager.isVolteProvisionedOnDevice(this)) {
-            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
-            tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
-        }
-
-        // NOTE: Buttons will be enabled/disabled in mPhoneStateListener
-        boolean enh4glteMode = ImsManager.isEnhanced4gLteModeSettingEnabledByUser(this)
-                && ImsManager.isNonTtyOrTtyOnVolteEnabled(this);
-        mButton4glte.setChecked(enh4glteMode);
-
-        mSubscriptionManager.addOnSubscriptionsChangedListener(mOnSubscriptionsChangeListener);
-
-        if (DBG) log("onResume:-");
-
-    }
-
-    private boolean hasActiveSubscriptions() {
-        return mActiveSubInfos.size() > 0;
-    }
-
-    private void updateBody() {
-        final Context context = getApplicationContext();
-        PreferenceScreen prefSet = getPreferenceScreen();
-        boolean isLteOnCdma = mPhone.getLteOnCdmaMode() == PhoneConstants.LTE_ON_CDMA_TRUE;
-        final int phoneSubId = mPhone.getSubId();
-
-        if (DBG) {
-            log("updateBody: isLteOnCdma=" + isLteOnCdma + " phoneSubId=" + phoneSubId);
-        }
-
-        if (prefSet != null) {
-            prefSet.removeAll();
-            prefSet.addPreference(mButtonDataRoam);
-            prefSet.addPreference(mButtonPreferredNetworkMode);
-            prefSet.addPreference(mButtonEnabledNetworks);
-            prefSet.addPreference(mButton4glte);
-        }
-
-        int settingsNetworkMode = android.provider.Settings.Global.getInt(
-                mPhone.getContext().getContentResolver(),
-                android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
-                preferredNetworkMode);
-
-        PersistableBundle carrierConfig =
-                PhoneGlobals.getInstance().getCarrierConfigForSubId(mPhone.getSubId());
-        mIsGlobalCdma = isLteOnCdma
-                && carrierConfig.getBoolean(CarrierConfigManager.KEY_SHOW_CDMA_CHOICES_BOOL);
-        if (carrierConfig.getBoolean(CarrierConfigManager.KEY_HIDE_CARRIER_NETWORK_SETTINGS_BOOL)) {
-            prefSet.removePreference(mButtonPreferredNetworkMode);
-            prefSet.removePreference(mButtonEnabledNetworks);
-            prefSet.removePreference(mLteDataServicePref);
-        } else if (carrierConfig.getBoolean(CarrierConfigManager
-                    .KEY_HIDE_PREFERRED_NETWORK_TYPE_BOOL)
-                && !mPhone.getServiceState().getRoaming()) {
-            prefSet.removePreference(mButtonPreferredNetworkMode);
-            prefSet.removePreference(mButtonEnabledNetworks);
-
-            final int phoneType = mPhone.getPhoneType();
-            if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
-                mCdmaOptions = new CdmaOptions(this, prefSet, mPhone);
-                // In World mode force a refresh of GSM Options.
-                if (isWorldMode()) {
-                    mGsmUmtsOptions = null;
+        private MobileNetworkSettings.TabState isUpdateTabsNeeded(List<SubscriptionInfo> newSil) {
+            TabState state = MobileNetworkSettings.TabState.DO_NOTHING;
+            if (newSil == null) {
+                if (mActiveSubInfos.size() >= TAB_THRESHOLD) {
+                    if (DBG) log("isUpdateTabsNeeded: NO_TABS, size unknown and was tabbed");
+                    state = MobileNetworkSettings.TabState.NO_TABS;
                 }
-            } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
+            } else if (newSil.size() < TAB_THRESHOLD && mActiveSubInfos.size() >= TAB_THRESHOLD) {
+                if (DBG) log("isUpdateTabsNeeded: NO_TABS, size went to small");
+                state = MobileNetworkSettings.TabState.NO_TABS;
+            } else if (newSil.size() >= TAB_THRESHOLD && mActiveSubInfos.size() < TAB_THRESHOLD) {
+                if (DBG) log("isUpdateTabsNeeded: UPDATE, size changed");
+                state = MobileNetworkSettings.TabState.UPDATE;
+            } else if (newSil.size() >= TAB_THRESHOLD) {
+                Iterator<SubscriptionInfo> siIterator = mActiveSubInfos.iterator();
+                for(SubscriptionInfo newSi : newSil) {
+                    SubscriptionInfo curSi = siIterator.next();
+                    if (!newSi.getDisplayName().equals(curSi.getDisplayName())) {
+                        if (DBG) log("isUpdateTabsNeeded: UPDATE, new name="
+                                + newSi.getDisplayName());
+                        state = MobileNetworkSettings.TabState.UPDATE;
+                        break;
+                    }
+                }
+            }
+            if (DBG) {
+                Log.i(LOG_TAG, "isUpdateTabsNeeded:- " + state
+                        + " newSil.size()=" + ((newSil != null) ? newSil.size() : 0)
+                        + " mActiveSubInfos.size()=" + mActiveSubInfos.size());
+            }
+            return state;
+        }
+
+        private TabHost.OnTabChangeListener mTabListener = new TabHost.OnTabChangeListener() {
+            @Override
+            public void onTabChanged(String tabId) {
+                if (DBG) log("onTabChanged:");
+                // The User has changed tab; update the body.
+                updatePhone(Integer.parseInt(tabId));
+                updateBody();
+            }
+        };
+
+        private void updatePhone(int slotId) {
+            final SubscriptionInfo sir = mSubscriptionManager
+                    .getActiveSubscriptionInfoForSimSlotIndex(slotId);
+            if (sir != null) {
+                mPhone = PhoneFactory.getPhone(
+                        SubscriptionManager.getPhoneId(sir.getSubscriptionId()));
+            }
+            if (mPhone == null) {
+                // Do the best we can
+                mPhone = PhoneGlobals.getPhone();
+            }
+            Log.i(LOG_TAG, "updatePhone:- slotId=" + slotId + " sir=" + sir);
+        }
+
+        private TabHost.TabContentFactory mEmptyTabContent = new TabHost.TabContentFactory() {
+            @Override
+            public View createTabContent(String tag) {
+                return new View(mTabHost.getContext());
+            }
+        };
+
+        private TabHost.TabSpec buildTabSpec(String tag, String title) {
+            return mTabHost.newTabSpec(tag).setIndicator(title).setContent(
+                    mEmptyTabContent);
+        }
+
+        @Override
+        public void onCreate(Bundle icicle) {
+            Log.i(LOG_TAG, "onCreate:+");
+            super.onCreate(icicle);
+            mHandler = new MyHandler();
+            mUm = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
+            mSubscriptionManager = SubscriptionManager.from(getActivity());
+
+            if (mUm.hasUserRestriction(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS)) {
+                mUnavailable = true;
+                getActivity().setContentView(R.layout.telephony_disallowed_preference_screen);
+                return;
+            }
+
+            addPreferencesFromResource(R.xml.network_setting_fragment);
+
+            mButton4glte = (SwitchPreference)findPreference(BUTTON_4G_LTE_KEY);
+            mButton4glte.setOnPreferenceChangeListener(this);
+
+            try {
+                Context con = getActivity().createPackageContext("com.android.systemui", 0);
+                int id = con.getResources().getIdentifier("config_show4GForLTE",
+                        "bool", "com.android.systemui");
+                mShow4GForLTE = con.getResources().getBoolean(id);
+            } catch (PackageManager.NameNotFoundException e) {
+                Log.e(LOG_TAG, "NameNotFoundException for show4GFotLTE");
+                mShow4GForLTE = false;
+            }
+
+            //get UI object references
+            PreferenceScreen prefSet = getPreferenceScreen();
+
+            mButtonDataRoam = (RestrictedSwitchPreference) prefSet.findPreference(
+                    BUTTON_ROAMING_KEY);
+            mButtonPreferredNetworkMode = (ListPreference) prefSet.findPreference(
+                    BUTTON_PREFERED_NETWORK_MODE);
+            mButtonEnabledNetworks = (ListPreference) prefSet.findPreference(
+                    BUTTON_ENABLED_NETWORKS_KEY);
+            mButtonDataRoam.setOnPreferenceChangeListener(this);
+
+            mLteDataServicePref = prefSet.findPreference(BUTTON_CDMA_LTE_DATA_SERVICE_KEY);
+
+            // Initialize mActiveSubInfo
+            int max = mSubscriptionManager.getActiveSubscriptionInfoCountMax();
+            mActiveSubInfos = new ArrayList<SubscriptionInfo>(max);
+
+            IntentFilter intentFilter = new IntentFilter(
+                    TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED);
+            getActivity().registerReceiver(mPhoneChangeReceiver, intentFilter);
+
+            initializeSubscriptions();
+            Log.i(LOG_TAG, "onCreate:-");
+        }
+
+        private class PhoneChangeReceiver extends BroadcastReceiver {
+            @Override
+            public void onReceive(Context context, Intent intent) {
+                Log.i(LOG_TAG, "onReceive:");
+                // When the radio changes (ex: CDMA->GSM), refresh all options.
+                mGsmUmtsOptions = null;
+                mCdmaOptions = null;
+                updateBody();
+            }
+        }
+
+        @Override
+        public void onDestroy() {
+            super.onDestroy();
+            getActivity().unregisterReceiver(mPhoneChangeReceiver);
+        }
+
+        @Override
+        public void onResume() {
+            super.onResume();
+            Log.i(LOG_TAG, "onResume:+");
+
+            if (mUnavailable) {
+                Log.i(LOG_TAG, "onResume:- ignore mUnavailable == false");
+                return;
+            }
+
+            // upon resumption from the sub-activity, make sure we re-enable the
+            // preferences.
+            getPreferenceScreen().setEnabled(true);
+
+            // Set UI state in onResume because a user could go home, launch some
+            // app to change this setting's backend, and re-launch this settings app
+            // and the UI state would be inconsistent with actual state
+            mButtonDataRoam.setChecked(mPhone.getDataRoamingEnabled());
+
+            if (getPreferenceScreen().findPreference(BUTTON_PREFERED_NETWORK_MODE) != null
+                    || getPreferenceScreen().findPreference(BUTTON_ENABLED_NETWORKS_KEY) != null)  {
+                updatePreferredNetworkUIFromDb();
+            }
+
+            if (ImsManager.isVolteEnabledByPlatform(getActivity())
+                    && ImsManager.isVolteProvisionedOnDevice(getActivity())) {
+                TelephonyManager tm =
+                        (TelephonyManager) getActivity().getSystemService(
+                                Context.TELEPHONY_SERVICE);
+                tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
+            }
+
+            // NOTE: Buttons will be enabled/disabled in mPhoneStateListener
+            boolean enh4glteMode = ImsManager.isEnhanced4gLteModeSettingEnabledByUser(getActivity())
+                    && ImsManager.isNonTtyOrTtyOnVolteEnabled(getActivity());
+            mButton4glte.setChecked(enh4glteMode);
+
+            mSubscriptionManager.addOnSubscriptionsChangedListener(mOnSubscriptionsChangeListener);
+
+            Log.i(LOG_TAG, "onResume:-");
+
+        }
+
+        private boolean hasActiveSubscriptions() {
+            return mActiveSubInfos.size() > 0;
+        }
+
+        private void updateBody() {
+            Context context = getActivity().getApplicationContext();
+            PreferenceScreen prefSet = getPreferenceScreen();
+            boolean isLteOnCdma = mPhone.getLteOnCdmaMode() == PhoneConstants.LTE_ON_CDMA_TRUE;
+            final int phoneSubId = mPhone.getSubId();
+
+            if (DBG) {
+                log("updateBody: isLteOnCdma=" + isLteOnCdma + " phoneSubId=" + phoneSubId);
+            }
+
+            if (prefSet != null) {
+                prefSet.removeAll();
+                prefSet.addPreference(mButtonDataRoam);
+                prefSet.addPreference(mButtonPreferredNetworkMode);
+                prefSet.addPreference(mButtonEnabledNetworks);
+                prefSet.addPreference(mButton4glte);
+            }
+
+            int settingsNetworkMode = android.provider.Settings.Global.getInt(
+                    mPhone.getContext().getContentResolver(),
+                    android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
+                    preferredNetworkMode);
+
+            PersistableBundle carrierConfig =
+                    PhoneGlobals.getInstance().getCarrierConfigForSubId(mPhone.getSubId());
+            mIsGlobalCdma = isLteOnCdma
+                    && carrierConfig.getBoolean(CarrierConfigManager.KEY_SHOW_CDMA_CHOICES_BOOL);
+            if (carrierConfig.getBoolean(
+                    CarrierConfigManager.KEY_HIDE_CARRIER_NETWORK_SETTINGS_BOOL)) {
+                prefSet.removePreference(mButtonPreferredNetworkMode);
+                prefSet.removePreference(mButtonEnabledNetworks);
+                prefSet.removePreference(mLteDataServicePref);
+            } else if (carrierConfig.getBoolean(CarrierConfigManager
+                    .KEY_HIDE_PREFERRED_NETWORK_TYPE_BOOL)
+                    && !mPhone.getServiceState().getRoaming()) {
+                prefSet.removePreference(mButtonPreferredNetworkMode);
+                prefSet.removePreference(mButtonEnabledNetworks);
+
+                final int phoneType = mPhone.getPhoneType();
+                if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
+                    mCdmaOptions = new CdmaOptions(this, prefSet, mPhone);
+                    // In World mode force a refresh of GSM Options.
+                    if (isWorldMode()) {
+                        mGsmUmtsOptions = null;
+                    }
+                } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
+                    mGsmUmtsOptions = new GsmUmtsOptions(this, prefSet, phoneSubId);
+                } else {
+                    throw new IllegalStateException("Unexpected phone type: " + phoneType);
+                }
+                // Since pref is being hidden from user, set network mode to default
+                // in case it is currently something else. That is possible if user
+                // changed the setting while roaming and is now back to home network.
+                settingsNetworkMode = preferredNetworkMode;
+            } else if (carrierConfig.getBoolean(
+                    CarrierConfigManager.KEY_WORLD_PHONE_BOOL) == true) {
+                prefSet.removePreference(mButtonEnabledNetworks);
+                // set the listener for the mButtonPreferredNetworkMode list preference so we can issue
+                // change Preferred Network Mode.
+                mButtonPreferredNetworkMode.setOnPreferenceChangeListener(this);
+
+                mCdmaOptions = new CdmaOptions(this, prefSet, mPhone);
                 mGsmUmtsOptions = new GsmUmtsOptions(this, prefSet, phoneSubId);
             } else {
-                throw new IllegalStateException("Unexpected phone type: " + phoneType);
-            }
-            // Since pref is being hidden from user, set network mode to default
-            // in case it is currently something else. That is possible if user
-            // changed the setting while roaming and is now back to home network.
-            settingsNetworkMode = preferredNetworkMode;
-        } else if (carrierConfig.getBoolean(CarrierConfigManager.KEY_WORLD_PHONE_BOOL) == true) {
-            prefSet.removePreference(mButtonEnabledNetworks);
-            // set the listener for the mButtonPreferredNetworkMode list preference so we can issue
-            // change Preferred Network Mode.
-            mButtonPreferredNetworkMode.setOnPreferenceChangeListener(this);
+                prefSet.removePreference(mButtonPreferredNetworkMode);
+                final int phoneType = mPhone.getPhoneType();
+                if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
+                    int lteForced = android.provider.Settings.Global.getInt(
+                            mPhone.getContext().getContentResolver(),
+                            android.provider.Settings.Global.LTE_SERVICE_FORCED + mPhone.getSubId(),
+                            0);
 
-            mCdmaOptions = new CdmaOptions(this, prefSet, mPhone);
-            mGsmUmtsOptions = new GsmUmtsOptions(this, prefSet, phoneSubId);
-        } else {
-            prefSet.removePreference(mButtonPreferredNetworkMode);
-            final int phoneType = mPhone.getPhoneType();
-            if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
-                int lteForced = android.provider.Settings.Global.getInt(
-                        mPhone.getContext().getContentResolver(),
-                        android.provider.Settings.Global.LTE_SERVICE_FORCED + mPhone.getSubId(),
-                        0);
+                    if (isLteOnCdma) {
+                        if (lteForced == 0) {
+                            mButtonEnabledNetworks.setEntries(
+                                    R.array.enabled_networks_cdma_choices);
+                            mButtonEnabledNetworks.setEntryValues(
+                                    R.array.enabled_networks_cdma_values);
+                        } else {
+                            switch (settingsNetworkMode) {
+                                case Phone.NT_MODE_CDMA:
+                                case Phone.NT_MODE_CDMA_NO_EVDO:
+                                case Phone.NT_MODE_EVDO_NO_CDMA:
+                                    mButtonEnabledNetworks.setEntries(
+                                            R.array.enabled_networks_cdma_no_lte_choices);
+                                    mButtonEnabledNetworks.setEntryValues(
+                                            R.array.enabled_networks_cdma_no_lte_values);
+                                    break;
+                                case Phone.NT_MODE_GLOBAL:
+                                case Phone.NT_MODE_LTE_CDMA_AND_EVDO:
+                                case Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
+                                case Phone.NT_MODE_LTE_ONLY:
+                                    mButtonEnabledNetworks.setEntries(
+                                            R.array.enabled_networks_cdma_only_lte_choices);
+                                    mButtonEnabledNetworks.setEntryValues(
+                                            R.array.enabled_networks_cdma_only_lte_values);
+                                    break;
+                                default:
+                                    mButtonEnabledNetworks.setEntries(
+                                            R.array.enabled_networks_cdma_choices);
+                                    mButtonEnabledNetworks.setEntryValues(
+                                            R.array.enabled_networks_cdma_values);
+                                    break;
+                            }
+                        }
+                    }
+                    mCdmaOptions = new CdmaOptions(this, prefSet, mPhone);
 
-                if (isLteOnCdma) {
-                    if (lteForced == 0) {
+                    // In World mode force a refresh of GSM Options.
+                    if (isWorldMode()) {
+                        mGsmUmtsOptions = null;
+                    }
+                } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
+                    if (isSupportTdscdma()) {
+                        mButtonEnabledNetworks.setEntries(
+                                R.array.enabled_networks_tdscdma_choices);
+                        mButtonEnabledNetworks.setEntryValues(
+                                R.array.enabled_networks_tdscdma_values);
+                    } else if (!carrierConfig.getBoolean(CarrierConfigManager.KEY_PREFER_2G_BOOL)
+                            && !getResources().getBoolean(R.bool.config_enabled_lte)) {
+                        mButtonEnabledNetworks.setEntries(
+                                R.array.enabled_networks_except_gsm_lte_choices);
+                        mButtonEnabledNetworks.setEntryValues(
+                                R.array.enabled_networks_except_gsm_lte_values);
+                    } else if (!carrierConfig.getBoolean(CarrierConfigManager.KEY_PREFER_2G_BOOL)) {
+                        int select = (mShow4GForLTE == true) ?
+                                R.array.enabled_networks_except_gsm_4g_choices
+                                : R.array.enabled_networks_except_gsm_choices;
+                        mButtonEnabledNetworks.setEntries(select);
+                        mButtonEnabledNetworks.setEntryValues(
+                                R.array.enabled_networks_except_gsm_values);
+                    } else if (!getResources().getBoolean(R.bool.config_enabled_lte)) {
+                        mButtonEnabledNetworks.setEntries(
+                                R.array.enabled_networks_except_lte_choices);
+                        mButtonEnabledNetworks.setEntryValues(
+                                R.array.enabled_networks_except_lte_values);
+                    } else if (mIsGlobalCdma) {
                         mButtonEnabledNetworks.setEntries(
                                 R.array.enabled_networks_cdma_choices);
                         mButtonEnabledNetworks.setEntryValues(
                                 R.array.enabled_networks_cdma_values);
                     } else {
-                        switch (settingsNetworkMode) {
-                            case Phone.NT_MODE_CDMA:
-                            case Phone.NT_MODE_CDMA_NO_EVDO:
-                            case Phone.NT_MODE_EVDO_NO_CDMA:
-                                mButtonEnabledNetworks.setEntries(
-                                        R.array.enabled_networks_cdma_no_lte_choices);
-                                mButtonEnabledNetworks.setEntryValues(
-                                        R.array.enabled_networks_cdma_no_lte_values);
-                                break;
-                            case Phone.NT_MODE_GLOBAL:
-                            case Phone.NT_MODE_LTE_CDMA_AND_EVDO:
-                            case Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
-                            case Phone.NT_MODE_LTE_ONLY:
-                                mButtonEnabledNetworks.setEntries(
-                                        R.array.enabled_networks_cdma_only_lte_choices);
-                                mButtonEnabledNetworks.setEntryValues(
-                                        R.array.enabled_networks_cdma_only_lte_values);
-                                break;
-                            default:
-                                mButtonEnabledNetworks.setEntries(
-                                        R.array.enabled_networks_cdma_choices);
-                                mButtonEnabledNetworks.setEntryValues(
-                                        R.array.enabled_networks_cdma_values);
-                                break;
-                        }
+                        int select = (mShow4GForLTE == true) ? R.array.enabled_networks_4g_choices
+                                : R.array.enabled_networks_choices;
+                        mButtonEnabledNetworks.setEntries(select);
+                        mButtonEnabledNetworks.setEntryValues(
+                                R.array.enabled_networks_values);
                     }
-                }
-                mCdmaOptions = new CdmaOptions(this, prefSet, mPhone);
-
-                // In World mode force a refresh of GSM Options.
-                if (isWorldMode()) {
-                    mGsmUmtsOptions = null;
-                }
-            } else if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
-                if (isSupportTdscdma()) {
-                    mButtonEnabledNetworks.setEntries(
-                            R.array.enabled_networks_tdscdma_choices);
-                    mButtonEnabledNetworks.setEntryValues(
-                            R.array.enabled_networks_tdscdma_values);
-                } else if (!carrierConfig.getBoolean(CarrierConfigManager.KEY_PREFER_2G_BOOL)
-                        && !getResources().getBoolean(R.bool.config_enabled_lte)) {
-                    mButtonEnabledNetworks.setEntries(
-                            R.array.enabled_networks_except_gsm_lte_choices);
-                    mButtonEnabledNetworks.setEntryValues(
-                            R.array.enabled_networks_except_gsm_lte_values);
-                } else if (!carrierConfig.getBoolean(CarrierConfigManager.KEY_PREFER_2G_BOOL)) {
-                    int select = (mShow4GForLTE == true) ?
-                            R.array.enabled_networks_except_gsm_4g_choices
-                            : R.array.enabled_networks_except_gsm_choices;
-                    mButtonEnabledNetworks.setEntries(select);
-                    mButtonEnabledNetworks.setEntryValues(
-                            R.array.enabled_networks_except_gsm_values);
-                } else if (!getResources().getBoolean(R.bool.config_enabled_lte)) {
-                    mButtonEnabledNetworks.setEntries(
-                            R.array.enabled_networks_except_lte_choices);
-                    mButtonEnabledNetworks.setEntryValues(
-                            R.array.enabled_networks_except_lte_values);
-                } else if (mIsGlobalCdma) {
-                    mButtonEnabledNetworks.setEntries(
-                            R.array.enabled_networks_cdma_choices);
-                    mButtonEnabledNetworks.setEntryValues(
-                            R.array.enabled_networks_cdma_values);
+                    mGsmUmtsOptions = new GsmUmtsOptions(this, prefSet, phoneSubId);
                 } else {
-                    int select = (mShow4GForLTE == true) ? R.array.enabled_networks_4g_choices
-                            : R.array.enabled_networks_choices;
-                    mButtonEnabledNetworks.setEntries(select);
-                    mButtonEnabledNetworks.setEntryValues(
-                            R.array.enabled_networks_values);
+                    throw new IllegalStateException("Unexpected phone type: " + phoneType);
                 }
-                mGsmUmtsOptions = new GsmUmtsOptions(this, prefSet, phoneSubId);
+                if (isWorldMode()) {
+                    mButtonEnabledNetworks.setEntries(
+                            R.array.preferred_network_mode_choices_world_mode);
+                    mButtonEnabledNetworks.setEntryValues(
+                            R.array.preferred_network_mode_values_world_mode);
+                }
+                mButtonEnabledNetworks.setOnPreferenceChangeListener(this);
+                if (DBG) log("settingsNetworkMode: " + settingsNetworkMode);
+            }
+
+            final boolean missingDataServiceUrl = TextUtils.isEmpty(
+                    android.provider.Settings.Global.getString(getActivity().getContentResolver(),
+                            android.provider.Settings.Global.SETUP_PREPAID_DATA_SERVICE_URL));
+            if (!isLteOnCdma || missingDataServiceUrl) {
+                prefSet.removePreference(mLteDataServicePref);
             } else {
-                throw new IllegalStateException("Unexpected phone type: " + phoneType);
+                android.util.Log.d(LOG_TAG, "keep ltePref");
             }
-            if (isWorldMode()) {
-                mButtonEnabledNetworks.setEntries(
-                        R.array.preferred_network_mode_choices_world_mode);
-                mButtonEnabledNetworks.setEntryValues(
-                        R.array.preferred_network_mode_values_world_mode);
+
+            // Enable enhanced 4G LTE mode settings depending on whether exists on platform
+            if (!(ImsManager.isVolteEnabledByPlatform(getActivity())
+                    && ImsManager.isVolteProvisionedOnDevice(getActivity()))) {
+                Preference pref = prefSet.findPreference(BUTTON_4G_LTE_KEY);
+                if (pref != null) {
+                    prefSet.removePreference(pref);
+                }
             }
-            mButtonEnabledNetworks.setOnPreferenceChangeListener(this);
-            if (DBG) log("settingsNetworkMode: " + settingsNetworkMode);
-        }
 
-        final boolean missingDataServiceUrl = TextUtils.isEmpty(
-                android.provider.Settings.Global.getString(getContentResolver(),
-                        android.provider.Settings.Global.SETUP_PREPAID_DATA_SERVICE_URL));
-        if (!isLteOnCdma || missingDataServiceUrl) {
-            prefSet.removePreference(mLteDataServicePref);
-        } else {
-            android.util.Log.d(LOG_TAG, "keep ltePref");
-        }
-
-        // Enable enhanced 4G LTE mode settings depending on whether exists on platform
-        if (!(ImsManager.isVolteEnabledByPlatform(this)
-                && ImsManager.isVolteProvisionedOnDevice(this))) {
-            Preference pref = prefSet.findPreference(BUTTON_4G_LTE_KEY);
-            if (pref != null) {
-                prefSet.removePreference(pref);
+            ActionBar actionBar = getActivity().getActionBar();
+            if (actionBar != null) {
+                // android.R.id.home will be triggered in onOptionsItemSelected()
+                actionBar.setDisplayHomeAsUpEnabled(true);
             }
-        }
 
-        ActionBar actionBar = getActionBar();
-        if (actionBar != null) {
-            // android.R.id.home will be triggered in onOptionsItemSelected()
-            actionBar.setDisplayHomeAsUpEnabled(true);
-        }
+            // Enable link to CMAS app settings depending on the value in config.xml.
+            final boolean isCellBroadcastAppLinkEnabled = getActivity().getResources().getBoolean(
+                    com.android.internal.R.bool.config_cellBroadcastAppLinks);
+            if (!mUm.isAdminUser() || !isCellBroadcastAppLinkEnabled
+                    || mUm.hasUserRestriction(UserManager.DISALLOW_CONFIG_CELL_BROADCASTS)) {
+                PreferenceScreen root = getPreferenceScreen();
+                Preference ps = findPreference(BUTTON_CELL_BROADCAST_SETTINGS);
+                if (ps != null) {
+                    root.removePreference(ps);
+                }
+            }
 
-        // Enable link to CMAS app settings depending on the value in config.xml.
-        final boolean isCellBroadcastAppLinkEnabled = this.getResources().getBoolean(
-                com.android.internal.R.bool.config_cellBroadcastAppLinks);
-        if (!mUm.isAdminUser() || !isCellBroadcastAppLinkEnabled
-                || mUm.hasUserRestriction(UserManager.DISALLOW_CONFIG_CELL_BROADCASTS)) {
+            // Get the networkMode from Settings.System and displays it
+            mButtonDataRoam.setChecked(mPhone.getDataRoamingEnabled());
+            mButtonEnabledNetworks.setValue(Integer.toString(settingsNetworkMode));
+            mButtonPreferredNetworkMode.setValue(Integer.toString(settingsNetworkMode));
+            UpdatePreferredNetworkModeSummary(settingsNetworkMode);
+            UpdateEnabledNetworksValueAndSummary(settingsNetworkMode);
+            // Display preferred network type based on what modem returns b/18676277
+            mPhone.setPreferredNetworkType(settingsNetworkMode, mHandler
+                    .obtainMessage(MyHandler.MESSAGE_SET_PREFERRED_NETWORK_TYPE));
+
+            /**
+             * Enable/disable depending upon if there are any active subscriptions.
+             *
+             * I've decided to put this enable/disable code at the bottom as the
+             * code above works even when there are no active subscriptions, thus
+             * putting it afterwards is a smaller change. This can be refined later,
+             * but you do need to remember that this all needs to work when subscriptions
+             * change dynamically such as when hot swapping sims.
+             */
+            boolean hasActiveSubscriptions = hasActiveSubscriptions();
+            TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(
+                    Context.TELEPHONY_SERVICE);
+            boolean canChange4glte = (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) &&
+                    ImsManager.isNonTtyOrTtyOnVolteEnabled(getActivity().getApplicationContext()) &&
+                    carrierConfig.getBoolean(
+                            CarrierConfigManager.KEY_EDITABLE_ENHANCED_4G_LTE_BOOL);
+            boolean useVariant4glteTitle = carrierConfig.getBoolean(
+                    CarrierConfigManager.KEY_ENHANCED_4G_LTE_TITLE_VARIANT_BOOL);
+            int enhanced4glteModeTitleId = useVariant4glteTitle ?
+                    R.string.enhanced_4g_lte_mode_title_variant :
+                    R.string.enhanced_4g_lte_mode_title;
+            mButtonDataRoam.setDisabledByAdmin(false);
+            mButtonDataRoam.setEnabled(hasActiveSubscriptions);
+            if (mButtonDataRoam.isEnabled()) {
+                if (RestrictedLockUtils.hasBaseUserRestriction(context,
+                        UserManager.DISALLOW_DATA_ROAMING, UserHandle.myUserId())) {
+                    mButtonDataRoam.setEnabled(false);
+                } else {
+                    mButtonDataRoam.checkRestrictionAndSetDisabled(
+                            UserManager.DISALLOW_DATA_ROAMING);
+                }
+            }
+            mButtonPreferredNetworkMode.setEnabled(hasActiveSubscriptions);
+            mButtonEnabledNetworks.setEnabled(hasActiveSubscriptions);
+            mButton4glte.setTitle(enhanced4glteModeTitleId);
+            mButton4glte.setEnabled(hasActiveSubscriptions && canChange4glte);
+            mLteDataServicePref.setEnabled(hasActiveSubscriptions);
+            Preference ps;
             PreferenceScreen root = getPreferenceScreen();
-            Preference ps = findPreference(BUTTON_CELL_BROADCAST_SETTINGS);
+            ps = findPreference(BUTTON_CELL_BROADCAST_SETTINGS);
             if (ps != null) {
-                root.removePreference(ps);
+                ps.setEnabled(hasActiveSubscriptions);
+            }
+            ps = findPreference(BUTTON_APN_EXPAND_KEY);
+            if (ps != null) {
+                ps.setEnabled(hasActiveSubscriptions);
+            }
+            ps = findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY);
+            if (ps != null) {
+                ps.setEnabled(hasActiveSubscriptions);
+            }
+            ps = findPreference(BUTTON_CARRIER_SETTINGS_KEY);
+            if (ps != null) {
+                ps.setEnabled(hasActiveSubscriptions);
+            }
+            ps = findPreference(BUTTON_CDMA_SYSTEM_SELECT_KEY);
+            if (ps != null) {
+                ps.setEnabled(hasActiveSubscriptions);
             }
         }
 
-        // Get the networkMode from Settings.System and displays it
-        mButtonDataRoam.setChecked(mPhone.getDataRoamingEnabled());
-        mButtonEnabledNetworks.setValue(Integer.toString(settingsNetworkMode));
-        mButtonPreferredNetworkMode.setValue(Integer.toString(settingsNetworkMode));
-        UpdatePreferredNetworkModeSummary(settingsNetworkMode);
-        UpdateEnabledNetworksValueAndSummary(settingsNetworkMode);
-        // Display preferred network type based on what modem returns b/18676277
-        mPhone.setPreferredNetworkType(settingsNetworkMode, mHandler
-                .obtainMessage(MyHandler.MESSAGE_SET_PREFERRED_NETWORK_TYPE));
+        @Override
+        public void onPause() {
+            super.onPause();
+            if (DBG) log("onPause:+");
+
+            if (ImsManager.isVolteEnabledByPlatform(getActivity())
+                    && ImsManager.isVolteProvisionedOnDevice(getActivity())) {
+                TelephonyManager tm =
+                        (TelephonyManager) getActivity().getSystemService(
+                                Context.TELEPHONY_SERVICE);
+                tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
+            }
+
+            mSubscriptionManager
+                    .removeOnSubscriptionsChangedListener(mOnSubscriptionsChangeListener);
+            if (DBG) log("onPause:-");
+        }
 
         /**
-         * Enable/disable depending upon if there are any active subscriptions.
+         * Implemented to support onPreferenceChangeListener to look for preference
+         * changes specifically on CLIR.
          *
-         * I've decided to put this enable/disable code at the bottom as the
-         * code above works even when there are no active subscriptions, thus
-         * putting it afterwards is a smaller change. This can be refined later,
-         * but you do need to remember that this all needs to work when subscriptions
-         * change dynamically such as when hot swapping sims.
+         * @param preference is the preference to be changed, should be mButtonCLIR.
+         * @param objValue should be the value of the selection, NOT its localized
+         * display value.
          */
-        boolean hasActiveSubscriptions = hasActiveSubscriptions();
-        TelephonyManager tm = (TelephonyManager) getSystemService(
-                Context.TELEPHONY_SERVICE);
-        boolean canChange4glte = (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) &&
-                ImsManager.isNonTtyOrTtyOnVolteEnabled(getApplicationContext()) &&
-                carrierConfig.getBoolean(CarrierConfigManager.KEY_EDITABLE_ENHANCED_4G_LTE_BOOL);
-        boolean useVariant4glteTitle = carrierConfig.getBoolean(
-                CarrierConfigManager.KEY_ENHANCED_4G_LTE_TITLE_VARIANT_BOOL);
-        int enhanced4glteModeTitleId = useVariant4glteTitle ?
-                R.string.enhanced_4g_lte_mode_title_variant :
-                R.string.enhanced_4g_lte_mode_title;
-        mButtonDataRoam.setDisabledByAdmin(false);
-        mButtonDataRoam.setEnabled(hasActiveSubscriptions);
-        if (mButtonDataRoam.isEnabled()) {
-            if (RestrictedLockUtils.hasBaseUserRestriction(context,
-                    UserManager.DISALLOW_DATA_ROAMING, UserHandle.myUserId())) {
-                mButtonDataRoam.setEnabled(false);
-            } else {
-                mButtonDataRoam.checkRestrictionAndSetDisabled(UserManager.DISALLOW_DATA_ROAMING);
-            }
-        }
-        mButtonPreferredNetworkMode.setEnabled(hasActiveSubscriptions);
-        mButtonEnabledNetworks.setEnabled(hasActiveSubscriptions);
-        mButton4glte.setTitle(enhanced4glteModeTitleId);
-        mButton4glte.setEnabled(hasActiveSubscriptions && canChange4glte);
-        mLteDataServicePref.setEnabled(hasActiveSubscriptions);
-        Preference ps;
-        PreferenceScreen root = getPreferenceScreen();
-        ps = findPreference(BUTTON_CELL_BROADCAST_SETTINGS);
-        if (ps != null) {
-            ps.setEnabled(hasActiveSubscriptions);
-        }
-        ps = findPreference(BUTTON_APN_EXPAND_KEY);
-        if (ps != null) {
-            ps.setEnabled(hasActiveSubscriptions);
-        }
-        ps = findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY);
-        if (ps != null) {
-            ps.setEnabled(hasActiveSubscriptions);
-        }
-        ps = findPreference(BUTTON_CARRIER_SETTINGS_KEY);
-        if (ps != null) {
-            ps.setEnabled(hasActiveSubscriptions);
-        }
-        ps = findPreference(BUTTON_CDMA_SYSTEM_SELECT_KEY);
-        if (ps != null) {
-            ps.setEnabled(hasActiveSubscriptions);
-        }
-    }
-
-    @Override
-    protected void onPause() {
-        super.onPause();
-        if (DBG) log("onPause:+");
-
-        if (ImsManager.isVolteEnabledByPlatform(this)
-                && ImsManager.isVolteProvisionedOnDevice(this)) {
-            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
-            tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
-        }
-
-        mSubscriptionManager
-            .removeOnSubscriptionsChangedListener(mOnSubscriptionsChangeListener);
-        if (DBG) log("onPause:-");
-    }
-
-    /**
-     * Implemented to support onPreferenceChangeListener to look for preference
-     * changes specifically on CLIR.
-     *
-     * @param preference is the preference to be changed, should be mButtonCLIR.
-     * @param objValue should be the value of the selection, NOT its localized
-     * display value.
-     */
-    public boolean onPreferenceChange(Preference preference, Object objValue) {
-        final int phoneSubId = mPhone.getSubId();
-        if (preference == mButtonPreferredNetworkMode) {
-            //NOTE onPreferenceChange seems to be called even if there is no change
-            //Check if the button value is changed from the System.Setting
-            mButtonPreferredNetworkMode.setValue((String) objValue);
-            int buttonNetworkMode;
-            buttonNetworkMode = Integer.parseInt((String) objValue);
-            int settingsNetworkMode = android.provider.Settings.Global.getInt(
-                    mPhone.getContext().getContentResolver(),
-                    android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
-                    preferredNetworkMode);
-            if (buttonNetworkMode != settingsNetworkMode) {
-                int modemNetworkMode;
-                // if new mode is invalid ignore it
-                switch (buttonNetworkMode) {
-                    case Phone.NT_MODE_WCDMA_PREF:
-                    case Phone.NT_MODE_GSM_ONLY:
-                    case Phone.NT_MODE_WCDMA_ONLY:
-                    case Phone.NT_MODE_GSM_UMTS:
-                    case Phone.NT_MODE_CDMA:
-                    case Phone.NT_MODE_CDMA_NO_EVDO:
-                    case Phone.NT_MODE_EVDO_NO_CDMA:
-                    case Phone.NT_MODE_GLOBAL:
-                    case Phone.NT_MODE_LTE_CDMA_AND_EVDO:
-                    case Phone.NT_MODE_LTE_GSM_WCDMA:
-                    case Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
-                    case Phone.NT_MODE_LTE_ONLY:
-                    case Phone.NT_MODE_LTE_WCDMA:
-                    case Phone.NT_MODE_TDSCDMA_ONLY:
-                    case Phone.NT_MODE_TDSCDMA_WCDMA:
-                    case Phone.NT_MODE_LTE_TDSCDMA:
-                    case Phone.NT_MODE_TDSCDMA_GSM:
-                    case Phone.NT_MODE_LTE_TDSCDMA_GSM:
-                    case Phone.NT_MODE_TDSCDMA_GSM_WCDMA:
-                    case Phone.NT_MODE_LTE_TDSCDMA_WCDMA:
-                    case Phone.NT_MODE_LTE_TDSCDMA_GSM_WCDMA:
-                    case Phone.NT_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
-                    case Phone.NT_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
-                        // This is one of the modes we recognize
-                        modemNetworkMode = buttonNetworkMode;
-                        break;
-                    default:
-                        loge("Invalid Network Mode (" + buttonNetworkMode + ") chosen. Ignore.");
-                        return true;
-                }
-
-                android.provider.Settings.Global.putInt(mPhone.getContext().getContentResolver(),
+        public boolean onPreferenceChange(Preference preference, Object objValue) {
+            final int phoneSubId = mPhone.getSubId();
+            if (preference == mButtonPreferredNetworkMode) {
+                //NOTE onPreferenceChange seems to be called even if there is no change
+                //Check if the button value is changed from the System.Setting
+                mButtonPreferredNetworkMode.setValue((String) objValue);
+                int buttonNetworkMode;
+                buttonNetworkMode = Integer.parseInt((String) objValue);
+                int settingsNetworkMode = android.provider.Settings.Global.getInt(
+                        mPhone.getContext().getContentResolver(),
                         android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
-                        buttonNetworkMode );
-                //Set the modem network mode
-                mPhone.setPreferredNetworkType(modemNetworkMode, mHandler
-                        .obtainMessage(MyHandler.MESSAGE_SET_PREFERRED_NETWORK_TYPE));
-            }
-        } else if (preference == mButtonEnabledNetworks) {
-            mButtonEnabledNetworks.setValue((String) objValue);
-            int buttonNetworkMode;
-            buttonNetworkMode = Integer.parseInt((String) objValue);
-            if (DBG) log("buttonNetworkMode: " + buttonNetworkMode);
-            int settingsNetworkMode = android.provider.Settings.Global.getInt(
-                    mPhone.getContext().getContentResolver(),
-                    android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
-                    preferredNetworkMode);
-            if (buttonNetworkMode != settingsNetworkMode) {
-                int modemNetworkMode;
-                // if new mode is invalid ignore it
-                switch (buttonNetworkMode) {
-                    case Phone.NT_MODE_WCDMA_PREF:
-                    case Phone.NT_MODE_GSM_ONLY:
-                    case Phone.NT_MODE_LTE_GSM_WCDMA:
-                    case Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
-                    case Phone.NT_MODE_CDMA:
-                    case Phone.NT_MODE_CDMA_NO_EVDO:
-                    case Phone.NT_MODE_LTE_CDMA_AND_EVDO:
-                    case Phone.NT_MODE_TDSCDMA_ONLY:
-                    case Phone.NT_MODE_TDSCDMA_WCDMA:
-                    case Phone.NT_MODE_LTE_TDSCDMA:
-                    case Phone.NT_MODE_TDSCDMA_GSM:
-                    case Phone.NT_MODE_LTE_TDSCDMA_GSM:
-                    case Phone.NT_MODE_TDSCDMA_GSM_WCDMA:
-                    case Phone.NT_MODE_LTE_TDSCDMA_WCDMA:
-                    case Phone.NT_MODE_LTE_TDSCDMA_GSM_WCDMA:
-                    case Phone.NT_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
-                    case Phone.NT_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
-                        // This is one of the modes we recognize
-                        modemNetworkMode = buttonNetworkMode;
-                        break;
-                    default:
-                        loge("Invalid Network Mode (" + buttonNetworkMode + ") chosen. Ignore.");
-                        return true;
+                        preferredNetworkMode);
+                if (buttonNetworkMode != settingsNetworkMode) {
+                    int modemNetworkMode;
+                    // if new mode is invalid ignore it
+                    switch (buttonNetworkMode) {
+                        case Phone.NT_MODE_WCDMA_PREF:
+                        case Phone.NT_MODE_GSM_ONLY:
+                        case Phone.NT_MODE_WCDMA_ONLY:
+                        case Phone.NT_MODE_GSM_UMTS:
+                        case Phone.NT_MODE_CDMA:
+                        case Phone.NT_MODE_CDMA_NO_EVDO:
+                        case Phone.NT_MODE_EVDO_NO_CDMA:
+                        case Phone.NT_MODE_GLOBAL:
+                        case Phone.NT_MODE_LTE_CDMA_AND_EVDO:
+                        case Phone.NT_MODE_LTE_GSM_WCDMA:
+                        case Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
+                        case Phone.NT_MODE_LTE_ONLY:
+                        case Phone.NT_MODE_LTE_WCDMA:
+                        case Phone.NT_MODE_TDSCDMA_ONLY:
+                        case Phone.NT_MODE_TDSCDMA_WCDMA:
+                        case Phone.NT_MODE_LTE_TDSCDMA:
+                        case Phone.NT_MODE_TDSCDMA_GSM:
+                        case Phone.NT_MODE_LTE_TDSCDMA_GSM:
+                        case Phone.NT_MODE_TDSCDMA_GSM_WCDMA:
+                        case Phone.NT_MODE_LTE_TDSCDMA_WCDMA:
+                        case Phone.NT_MODE_LTE_TDSCDMA_GSM_WCDMA:
+                        case Phone.NT_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
+                        case Phone.NT_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
+                            // This is one of the modes we recognize
+                            modemNetworkMode = buttonNetworkMode;
+                            break;
+                        default:
+                            loge("Invalid Network Mode (" +buttonNetworkMode+ ") chosen. Ignore.");
+                            return true;
+                    }
+
+                    android.provider.Settings.Global.putInt(
+                            mPhone.getContext().getContentResolver(),
+                            android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
+                            buttonNetworkMode );
+                    //Set the modem network mode
+                    mPhone.setPreferredNetworkType(modemNetworkMode, mHandler
+                            .obtainMessage(MyHandler.MESSAGE_SET_PREFERRED_NETWORK_TYPE));
                 }
-
-                UpdateEnabledNetworksValueAndSummary(buttonNetworkMode);
-
-                android.provider.Settings.Global.putInt(mPhone.getContext().getContentResolver(),
+            } else if (preference == mButtonEnabledNetworks) {
+                mButtonEnabledNetworks.setValue((String) objValue);
+                int buttonNetworkMode;
+                buttonNetworkMode = Integer.parseInt((String) objValue);
+                if (DBG) log("buttonNetworkMode: " + buttonNetworkMode);
+                int settingsNetworkMode = android.provider.Settings.Global.getInt(
+                        mPhone.getContext().getContentResolver(),
                         android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
-                        buttonNetworkMode );
-                //Set the modem network mode
-                mPhone.setPreferredNetworkType(modemNetworkMode, mHandler
-                        .obtainMessage(MyHandler.MESSAGE_SET_PREFERRED_NETWORK_TYPE));
-            }
-        } else if (preference == mButton4glte) {
-            SwitchPreference enhanced4gModePref = (SwitchPreference) preference;
-            boolean enhanced4gMode = !enhanced4gModePref.isChecked();
-            enhanced4gModePref.setChecked(enhanced4gMode);
-            ImsManager.setEnhanced4gLteModeSetting(this, enhanced4gModePref.isChecked());
-        } else if (preference == mButtonDataRoam) {
-            if (DBG) log("onPreferenceTreeClick: preference == mButtonDataRoam.");
+                        preferredNetworkMode);
+                if (buttonNetworkMode != settingsNetworkMode) {
+                    int modemNetworkMode;
+                    // if new mode is invalid ignore it
+                    switch (buttonNetworkMode) {
+                        case Phone.NT_MODE_WCDMA_PREF:
+                        case Phone.NT_MODE_GSM_ONLY:
+                        case Phone.NT_MODE_LTE_GSM_WCDMA:
+                        case Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
+                        case Phone.NT_MODE_CDMA:
+                        case Phone.NT_MODE_CDMA_NO_EVDO:
+                        case Phone.NT_MODE_LTE_CDMA_AND_EVDO:
+                        case Phone.NT_MODE_TDSCDMA_ONLY:
+                        case Phone.NT_MODE_TDSCDMA_WCDMA:
+                        case Phone.NT_MODE_LTE_TDSCDMA:
+                        case Phone.NT_MODE_TDSCDMA_GSM:
+                        case Phone.NT_MODE_LTE_TDSCDMA_GSM:
+                        case Phone.NT_MODE_TDSCDMA_GSM_WCDMA:
+                        case Phone.NT_MODE_LTE_TDSCDMA_WCDMA:
+                        case Phone.NT_MODE_LTE_TDSCDMA_GSM_WCDMA:
+                        case Phone.NT_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
+                        case Phone.NT_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
+                            // This is one of the modes we recognize
+                            modemNetworkMode = buttonNetworkMode;
+                            break;
+                        default:
+                            loge("Invalid Network Mode (" +buttonNetworkMode+ ") chosen. Ignore.");
+                            return true;
+                    }
 
-            //normally called on the toggle click
-            if (!mButtonDataRoam.isChecked()) {
-                // First confirm with a warning dialog about charges
-                mOkClicked = false;
-                new AlertDialog.Builder(this).setMessage(
-                        getResources().getString(R.string.roaming_warning))
-                        .setTitle(R.string.roaming_alert_title)
-                        .setIconAttribute(android.R.attr.alertDialogIcon)
-                        .setPositiveButton(android.R.string.yes, this)
-                        .setNegativeButton(android.R.string.no, this)
-                        .show()
-                        .setOnDismissListener(this);
-            } else {
-                mPhone.setDataRoamingEnabled(false);
+                    UpdateEnabledNetworksValueAndSummary(buttonNetworkMode);
+
+                    android.provider.Settings.Global.putInt(
+                            mPhone.getContext().getContentResolver(),
+                            android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
+                            buttonNetworkMode );
+                    //Set the modem network mode
+                    mPhone.setPreferredNetworkType(modemNetworkMode, mHandler
+                            .obtainMessage(MyHandler.MESSAGE_SET_PREFERRED_NETWORK_TYPE));
+                }
+            } else if (preference == mButton4glte) {
+                SwitchPreference enhanced4gModePref = (SwitchPreference) preference;
+                boolean enhanced4gMode = !enhanced4gModePref.isChecked();
+                enhanced4gModePref.setChecked(enhanced4gMode);
+                ImsManager.setEnhanced4gLteModeSetting(getActivity(),
+                        enhanced4gModePref.isChecked());
+            } else if (preference == mButtonDataRoam) {
+                if (DBG) log("onPreferenceTreeClick: preference == mButtonDataRoam.");
+
+                //normally called on the toggle click
+                if (!mButtonDataRoam.isChecked()) {
+                    // First confirm with a warning dialog about charges
+                    mOkClicked = false;
+                    RoamingDialogFragment fragment = new RoamingDialogFragment();
+                    fragment.show(getFragmentManager(), ROAMING_TAG);
+                    // Don't update the toggle unless the confirm button is actually pressed.
+                    return false;
+                } else {
+                    mPhone.setDataRoamingEnabled(false);
+                }
+                return true;
             }
+
+            updateBody();
+            // always let the preference setting proceed.
             return true;
         }
 
-        updateBody();
-        // always let the preference setting proceed.
-        return true;
-    }
+        private class MyHandler extends Handler {
 
-    private class MyHandler extends Handler {
+            static final int MESSAGE_SET_PREFERRED_NETWORK_TYPE = 0;
 
-        static final int MESSAGE_SET_PREFERRED_NETWORK_TYPE = 0;
-
-        @Override
-        public void handleMessage(Message msg) {
-            switch (msg.what) {
-                case MESSAGE_SET_PREFERRED_NETWORK_TYPE:
-                    handleSetPreferredNetworkTypeResponse(msg);
-                    break;
-            }
-        }
-
-        private void handleSetPreferredNetworkTypeResponse(Message msg) {
-            if (isDestroyed()) { // Access preferences of activity only if it is not destroyed
-                return;
-            }
-
-            AsyncResult ar = (AsyncResult) msg.obj;
-            final int phoneSubId = mPhone.getSubId();
-
-            if (ar.exception == null) {
-                int networkMode;
-                if (getPreferenceScreen().findPreference(BUTTON_PREFERED_NETWORK_MODE) != null)  {
-                    networkMode =  Integer.parseInt(mButtonPreferredNetworkMode.getValue());
-                    android.provider.Settings.Global.putInt(mPhone.getContext().getContentResolver(),
-                            android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
-                            networkMode );
-                }
-                if (getPreferenceScreen().findPreference(BUTTON_ENABLED_NETWORKS_KEY) != null)  {
-                    networkMode = Integer.parseInt(mButtonEnabledNetworks.getValue());
-                    android.provider.Settings.Global.putInt(mPhone.getContext().getContentResolver(),
-                            android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
-                            networkMode );
-                }
-            } else {
-                if (DBG) {
-                    log("handleSetPreferredNetworkTypeResponse: exception in setting network mode.");
-                }
-                updatePreferredNetworkUIFromDb();
-            }
-        }
-    }
-
-    private void updatePreferredNetworkUIFromDb() {
-        final int phoneSubId = mPhone.getSubId();
-
-        int settingsNetworkMode = android.provider.Settings.Global.getInt(
-                mPhone.getContext().getContentResolver(),
-                android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
-                preferredNetworkMode);
-
-        if (DBG) {
-            log("updatePreferredNetworkUIFromDb: settingsNetworkMode = " +
-                    settingsNetworkMode);
-        }
-
-        UpdatePreferredNetworkModeSummary(settingsNetworkMode);
-        UpdateEnabledNetworksValueAndSummary(settingsNetworkMode);
-        // changes the mButtonPreferredNetworkMode accordingly to settingsNetworkMode
-        mButtonPreferredNetworkMode.setValue(Integer.toString(settingsNetworkMode));
-    }
-
-    private void UpdatePreferredNetworkModeSummary(int NetworkMode) {
-        switch(NetworkMode) {
-            case Phone.NT_MODE_TDSCDMA_GSM_WCDMA:
-            case Phone.NT_MODE_TDSCDMA_GSM:
-            case Phone.NT_MODE_WCDMA_PREF:
-                mButtonPreferredNetworkMode.setSummary(
-                        R.string.preferred_network_mode_wcdma_perf_summary);
-                break;
-            case Phone.NT_MODE_GSM_ONLY:
-                mButtonPreferredNetworkMode.setSummary(
-                        R.string.preferred_network_mode_gsm_only_summary);
-                break;
-            case Phone.NT_MODE_TDSCDMA_WCDMA:
-            case Phone.NT_MODE_WCDMA_ONLY:
-                mButtonPreferredNetworkMode.setSummary(
-                        R.string.preferred_network_mode_wcdma_only_summary);
-                break;
-            case Phone.NT_MODE_GSM_UMTS:
-                mButtonPreferredNetworkMode.setSummary(
-                        R.string.preferred_network_mode_gsm_wcdma_summary);
-                break;
-            case Phone.NT_MODE_CDMA:
-                switch (mPhone.getLteOnCdmaMode()) {
-                    case PhoneConstants.LTE_ON_CDMA_TRUE:
-                        mButtonPreferredNetworkMode.setSummary(
-                            R.string.preferred_network_mode_cdma_summary);
-                    break;
-                    case PhoneConstants.LTE_ON_CDMA_FALSE:
-                    default:
-                        mButtonPreferredNetworkMode.setSummary(
-                            R.string.preferred_network_mode_cdma_evdo_summary);
+            @Override
+            public void handleMessage(Message msg) {
+                switch (msg.what) {
+                    case MESSAGE_SET_PREFERRED_NETWORK_TYPE:
+                        handleSetPreferredNetworkTypeResponse(msg);
                         break;
                 }
-                break;
-            case Phone.NT_MODE_CDMA_NO_EVDO:
-                mButtonPreferredNetworkMode.setSummary(
-                        R.string.preferred_network_mode_cdma_only_summary);
-                break;
-            case Phone.NT_MODE_EVDO_NO_CDMA:
-                mButtonPreferredNetworkMode.setSummary(
-                        R.string.preferred_network_mode_evdo_only_summary);
-                break;
-            case Phone.NT_MODE_LTE_TDSCDMA:
-            case Phone.NT_MODE_LTE_ONLY:
-                mButtonPreferredNetworkMode.setSummary(
-                        R.string.preferred_network_mode_lte_summary);
-                break;
-            case Phone.NT_MODE_LTE_TDSCDMA_GSM:
-            case Phone.NT_MODE_LTE_TDSCDMA_GSM_WCDMA:
-            case Phone.NT_MODE_LTE_GSM_WCDMA:
-                mButtonPreferredNetworkMode.setSummary(
-                        R.string.preferred_network_mode_lte_gsm_wcdma_summary);
-                break;
-            case Phone.NT_MODE_LTE_CDMA_AND_EVDO:
-                mButtonPreferredNetworkMode.setSummary(
-                        R.string.preferred_network_mode_lte_cdma_evdo_summary);
-                break;
-            case Phone.NT_MODE_TDSCDMA_ONLY:
-                mButtonPreferredNetworkMode.setSummary(
-                        R.string.preferred_network_mode_tdscdma_summary);
-                break;
-            case Phone.NT_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
-            case Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
-                if (mPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA ||
-                        mIsGlobalCdma ||
-                        isWorldMode()) {
-                    mButtonPreferredNetworkMode.setSummary(
-                            R.string.preferred_network_mode_global_summary);
+            }
+
+            private void handleSetPreferredNetworkTypeResponse(Message msg) {
+                if (getActivity().isDestroyed()) {
+                    // Access preferences of activity only if it is not destroyed
+                    return;
+                }
+
+                AsyncResult ar = (AsyncResult) msg.obj;
+                final int phoneSubId = mPhone.getSubId();
+
+                if (ar.exception == null) {
+                    int networkMode;
+                    if (getPreferenceScreen().findPreference(
+                            BUTTON_PREFERED_NETWORK_MODE) != null)  {
+                        networkMode =  Integer.parseInt(mButtonPreferredNetworkMode.getValue());
+                        android.provider.Settings.Global.putInt(
+                                mPhone.getContext().getContentResolver(),
+                                android.provider.Settings.Global.PREFERRED_NETWORK_MODE
+                                        + phoneSubId,
+                                networkMode );
+                    }
+                    if (getPreferenceScreen().findPreference(BUTTON_ENABLED_NETWORKS_KEY) != null) {
+                        networkMode = Integer.parseInt(mButtonEnabledNetworks.getValue());
+                        android.provider.Settings.Global.putInt(
+                                mPhone.getContext().getContentResolver(),
+                                android.provider.Settings.Global.PREFERRED_NETWORK_MODE
+                                        + phoneSubId,
+                                networkMode );
+                    }
                 } else {
+                    Log.i(LOG_TAG, "handleSetPreferredNetworkTypeResponse:" +
+                            "exception in setting network mode.");
+                    updatePreferredNetworkUIFromDb();
+                }
+            }
+        }
+
+        private void updatePreferredNetworkUIFromDb() {
+            final int phoneSubId = mPhone.getSubId();
+
+            int settingsNetworkMode = android.provider.Settings.Global.getInt(
+                    mPhone.getContext().getContentResolver(),
+                    android.provider.Settings.Global.PREFERRED_NETWORK_MODE + phoneSubId,
+                    preferredNetworkMode);
+
+            if (DBG) {
+                log("updatePreferredNetworkUIFromDb: settingsNetworkMode = " +
+                        settingsNetworkMode);
+            }
+
+            UpdatePreferredNetworkModeSummary(settingsNetworkMode);
+            UpdateEnabledNetworksValueAndSummary(settingsNetworkMode);
+            // changes the mButtonPreferredNetworkMode accordingly to settingsNetworkMode
+            mButtonPreferredNetworkMode.setValue(Integer.toString(settingsNetworkMode));
+        }
+
+        private void UpdatePreferredNetworkModeSummary(int NetworkMode) {
+            switch(NetworkMode) {
+                case Phone.NT_MODE_TDSCDMA_GSM_WCDMA:
+                case Phone.NT_MODE_TDSCDMA_GSM:
+                case Phone.NT_MODE_WCDMA_PREF:
+                    mButtonPreferredNetworkMode.setSummary(
+                            R.string.preferred_network_mode_wcdma_perf_summary);
+                    break;
+                case Phone.NT_MODE_GSM_ONLY:
+                    mButtonPreferredNetworkMode.setSummary(
+                            R.string.preferred_network_mode_gsm_only_summary);
+                    break;
+                case Phone.NT_MODE_TDSCDMA_WCDMA:
+                case Phone.NT_MODE_WCDMA_ONLY:
+                    mButtonPreferredNetworkMode.setSummary(
+                            R.string.preferred_network_mode_wcdma_only_summary);
+                    break;
+                case Phone.NT_MODE_GSM_UMTS:
+                    mButtonPreferredNetworkMode.setSummary(
+                            R.string.preferred_network_mode_gsm_wcdma_summary);
+                    break;
+                case Phone.NT_MODE_CDMA:
+                    switch (mPhone.getLteOnCdmaMode()) {
+                        case PhoneConstants.LTE_ON_CDMA_TRUE:
+                            mButtonPreferredNetworkMode.setSummary(
+                                    R.string.preferred_network_mode_cdma_summary);
+                            break;
+                        case PhoneConstants.LTE_ON_CDMA_FALSE:
+                        default:
+                            mButtonPreferredNetworkMode.setSummary(
+                                    R.string.preferred_network_mode_cdma_evdo_summary);
+                            break;
+                    }
+                    break;
+                case Phone.NT_MODE_CDMA_NO_EVDO:
+                    mButtonPreferredNetworkMode.setSummary(
+                            R.string.preferred_network_mode_cdma_only_summary);
+                    break;
+                case Phone.NT_MODE_EVDO_NO_CDMA:
+                    mButtonPreferredNetworkMode.setSummary(
+                            R.string.preferred_network_mode_evdo_only_summary);
+                    break;
+                case Phone.NT_MODE_LTE_TDSCDMA:
+                case Phone.NT_MODE_LTE_ONLY:
                     mButtonPreferredNetworkMode.setSummary(
                             R.string.preferred_network_mode_lte_summary);
-                }
-                break;
-            case Phone.NT_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
-            case Phone.NT_MODE_GLOBAL:
-                mButtonPreferredNetworkMode.setSummary(
-                        R.string.preferred_network_mode_cdma_evdo_gsm_wcdma_summary);
-                break;
-            case Phone.NT_MODE_LTE_TDSCDMA_WCDMA:
-            case Phone.NT_MODE_LTE_WCDMA:
-                mButtonPreferredNetworkMode.setSummary(
-                        R.string.preferred_network_mode_lte_wcdma_summary);
-                break;
-            default:
-                mButtonPreferredNetworkMode.setSummary(
-                        R.string.preferred_network_mode_global_summary);
-        }
-    }
-
-    private void UpdateEnabledNetworksValueAndSummary(int NetworkMode) {
-        switch (NetworkMode) {
-            case Phone.NT_MODE_TDSCDMA_WCDMA:
-            case Phone.NT_MODE_TDSCDMA_GSM_WCDMA:
-            case Phone.NT_MODE_TDSCDMA_GSM:
-                mButtonEnabledNetworks.setValue(
-                        Integer.toString(Phone.NT_MODE_TDSCDMA_GSM_WCDMA));
-                mButtonEnabledNetworks.setSummary(R.string.network_3G);
-                break;
-            case Phone.NT_MODE_WCDMA_ONLY:
-            case Phone.NT_MODE_GSM_UMTS:
-            case Phone.NT_MODE_WCDMA_PREF:
-                if (!mIsGlobalCdma) {
-                    mButtonEnabledNetworks.setValue(
-                            Integer.toString(Phone.NT_MODE_WCDMA_PREF));
-                    mButtonEnabledNetworks.setSummary(R.string.network_3G);
-                } else {
-                    mButtonEnabledNetworks.setValue(
-                            Integer.toString(Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA));
-                    mButtonEnabledNetworks.setSummary(R.string.network_global);
-                }
-                break;
-            case Phone.NT_MODE_GSM_ONLY:
-                if (!mIsGlobalCdma) {
-                    mButtonEnabledNetworks.setValue(
-                            Integer.toString(Phone.NT_MODE_GSM_ONLY));
-                    mButtonEnabledNetworks.setSummary(R.string.network_2G);
-                } else {
-                    mButtonEnabledNetworks.setValue(
-                            Integer.toString(Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA));
-                    mButtonEnabledNetworks.setSummary(R.string.network_global);
-                }
-                break;
-            case Phone.NT_MODE_LTE_GSM_WCDMA:
-                if (isWorldMode()) {
-                    mButtonEnabledNetworks.setSummary(
-                            R.string.preferred_network_mode_lte_gsm_umts_summary);
-                    controlCdmaOptions(false);
-                    controlGsmOptions(true);
                     break;
-                }
-            case Phone.NT_MODE_LTE_ONLY:
-            case Phone.NT_MODE_LTE_WCDMA:
-                if (!mIsGlobalCdma) {
-                    mButtonEnabledNetworks.setValue(
-                            Integer.toString(Phone.NT_MODE_LTE_GSM_WCDMA));
-                    mButtonEnabledNetworks.setSummary((mShow4GForLTE == true)
-                            ? R.string.network_4G : R.string.network_lte);
-                } else {
-                    mButtonEnabledNetworks.setValue(
-                            Integer.toString(Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA));
-                    mButtonEnabledNetworks.setSummary(R.string.network_global);
-                }
-                break;
-            case Phone.NT_MODE_LTE_CDMA_AND_EVDO:
-                if (isWorldMode()) {
-                    mButtonEnabledNetworks.setSummary(
-                            R.string.preferred_network_mode_lte_cdma_summary);
-                    controlCdmaOptions(true);
-                    controlGsmOptions(false);
-                } else {
-                    mButtonEnabledNetworks.setValue(
-                            Integer.toString(Phone.NT_MODE_LTE_CDMA_AND_EVDO));
-                    mButtonEnabledNetworks.setSummary(R.string.network_lte);
-                }
-                break;
-            case Phone.NT_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
-                mButtonEnabledNetworks.setValue(
-                        Integer.toString(Phone.NT_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA));
-                mButtonEnabledNetworks.setSummary(R.string.network_3G);
-                break;
-            case Phone.NT_MODE_CDMA:
-            case Phone.NT_MODE_EVDO_NO_CDMA:
-            case Phone.NT_MODE_GLOBAL:
-                mButtonEnabledNetworks.setValue(
-                        Integer.toString(Phone.NT_MODE_CDMA));
-                mButtonEnabledNetworks.setSummary(R.string.network_3G);
-                break;
-            case Phone.NT_MODE_CDMA_NO_EVDO:
-                mButtonEnabledNetworks.setValue(
-                        Integer.toString(Phone.NT_MODE_CDMA_NO_EVDO));
-                mButtonEnabledNetworks.setSummary(R.string.network_1x);
-                break;
-            case Phone.NT_MODE_TDSCDMA_ONLY:
-                mButtonEnabledNetworks.setValue(
-                        Integer.toString(Phone.NT_MODE_TDSCDMA_ONLY));
-                mButtonEnabledNetworks.setSummary(R.string.network_3G);
-                break;
-            case Phone.NT_MODE_LTE_TDSCDMA_GSM:
-            case Phone.NT_MODE_LTE_TDSCDMA_GSM_WCDMA:
-            case Phone.NT_MODE_LTE_TDSCDMA:
-            case Phone.NT_MODE_LTE_TDSCDMA_WCDMA:
-            case Phone.NT_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
-            case Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
-                if (isSupportTdscdma()) {
-                    mButtonEnabledNetworks.setValue(
-                            Integer.toString(Phone.NT_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA));
-                    mButtonEnabledNetworks.setSummary(R.string.network_lte);
-                } else {
-                    if (isWorldMode()) {
-                        controlCdmaOptions(true);
-                        controlGsmOptions(false);
-                    }
-                    mButtonEnabledNetworks.setValue(
-                            Integer.toString(Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA));
+                case Phone.NT_MODE_LTE_TDSCDMA_GSM:
+                case Phone.NT_MODE_LTE_TDSCDMA_GSM_WCDMA:
+                case Phone.NT_MODE_LTE_GSM_WCDMA:
+                    mButtonPreferredNetworkMode.setSummary(
+                            R.string.preferred_network_mode_lte_gsm_wcdma_summary);
+                    break;
+                case Phone.NT_MODE_LTE_CDMA_AND_EVDO:
+                    mButtonPreferredNetworkMode.setSummary(
+                            R.string.preferred_network_mode_lte_cdma_evdo_summary);
+                    break;
+                case Phone.NT_MODE_TDSCDMA_ONLY:
+                    mButtonPreferredNetworkMode.setSummary(
+                            R.string.preferred_network_mode_tdscdma_summary);
+                    break;
+                case Phone.NT_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
+                case Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
                     if (mPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA ||
                             mIsGlobalCdma ||
                             isWorldMode()) {
-                        mButtonEnabledNetworks.setSummary(R.string.network_global);
+                        mButtonPreferredNetworkMode.setSummary(
+                                R.string.preferred_network_mode_global_summary);
                     } else {
+                        mButtonPreferredNetworkMode.setSummary(
+                                R.string.preferred_network_mode_lte_summary);
+                    }
+                    break;
+                case Phone.NT_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
+                case Phone.NT_MODE_GLOBAL:
+                    mButtonPreferredNetworkMode.setSummary(
+                            R.string.preferred_network_mode_cdma_evdo_gsm_wcdma_summary);
+                    break;
+                case Phone.NT_MODE_LTE_TDSCDMA_WCDMA:
+                case Phone.NT_MODE_LTE_WCDMA:
+                    mButtonPreferredNetworkMode.setSummary(
+                            R.string.preferred_network_mode_lte_wcdma_summary);
+                    break;
+                default:
+                    mButtonPreferredNetworkMode.setSummary(
+                            R.string.preferred_network_mode_global_summary);
+            }
+        }
+
+        private void UpdateEnabledNetworksValueAndSummary(int NetworkMode) {
+            switch (NetworkMode) {
+                case Phone.NT_MODE_TDSCDMA_WCDMA:
+                case Phone.NT_MODE_TDSCDMA_GSM_WCDMA:
+                case Phone.NT_MODE_TDSCDMA_GSM:
+                    mButtonEnabledNetworks.setValue(
+                            Integer.toString(Phone.NT_MODE_TDSCDMA_GSM_WCDMA));
+                    mButtonEnabledNetworks.setSummary(R.string.network_3G);
+                    break;
+                case Phone.NT_MODE_WCDMA_ONLY:
+                case Phone.NT_MODE_GSM_UMTS:
+                case Phone.NT_MODE_WCDMA_PREF:
+                    if (!mIsGlobalCdma) {
+                        mButtonEnabledNetworks.setValue(
+                                Integer.toString(Phone.NT_MODE_WCDMA_PREF));
+                        mButtonEnabledNetworks.setSummary(R.string.network_3G);
+                    } else {
+                        mButtonEnabledNetworks.setValue(
+                                Integer.toString(Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA));
+                        mButtonEnabledNetworks.setSummary(R.string.network_global);
+                    }
+                    break;
+                case Phone.NT_MODE_GSM_ONLY:
+                    if (!mIsGlobalCdma) {
+                        mButtonEnabledNetworks.setValue(
+                                Integer.toString(Phone.NT_MODE_GSM_ONLY));
+                        mButtonEnabledNetworks.setSummary(R.string.network_2G);
+                    } else {
+                        mButtonEnabledNetworks.setValue(
+                                Integer.toString(Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA));
+                        mButtonEnabledNetworks.setSummary(R.string.network_global);
+                    }
+                    break;
+                case Phone.NT_MODE_LTE_GSM_WCDMA:
+                    if (isWorldMode()) {
+                        mButtonEnabledNetworks.setSummary(
+                                R.string.preferred_network_mode_lte_gsm_umts_summary);
+                        controlCdmaOptions(false);
+                        controlGsmOptions(true);
+                        break;
+                    }
+                case Phone.NT_MODE_LTE_ONLY:
+                case Phone.NT_MODE_LTE_WCDMA:
+                    if (!mIsGlobalCdma) {
+                        mButtonEnabledNetworks.setValue(
+                                Integer.toString(Phone.NT_MODE_LTE_GSM_WCDMA));
                         mButtonEnabledNetworks.setSummary((mShow4GForLTE == true)
                                 ? R.string.network_4G : R.string.network_lte);
+                    } else {
+                        mButtonEnabledNetworks.setValue(
+                                Integer.toString(Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA));
+                        mButtonEnabledNetworks.setSummary(R.string.network_global);
                     }
-                }
-                break;
-            default:
-                String errMsg = "Invalid Network Mode (" + NetworkMode + "). Ignore.";
-                loge(errMsg);
-                mButtonEnabledNetworks.setSummary(errMsg);
-        }
-    }
-
-    @Override
-    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
-        switch(requestCode) {
-        case REQUEST_CODE_EXIT_ECM:
-            Boolean isChoiceYes =
-                data.getBooleanExtra(EmergencyCallbackModeExitDialog.EXTRA_EXIT_ECM_RESULT, false);
-            if (isChoiceYes) {
-                // If the phone exits from ECM mode, show the CDMA Options
-                mCdmaOptions.showDialog(mClickedPreference);
-            } else {
-                // do nothing
+                    break;
+                case Phone.NT_MODE_LTE_CDMA_AND_EVDO:
+                    if (isWorldMode()) {
+                        mButtonEnabledNetworks.setSummary(
+                                R.string.preferred_network_mode_lte_cdma_summary);
+                        controlCdmaOptions(true);
+                        controlGsmOptions(false);
+                    } else {
+                        mButtonEnabledNetworks.setValue(
+                                Integer.toString(Phone.NT_MODE_LTE_CDMA_AND_EVDO));
+                        mButtonEnabledNetworks.setSummary(R.string.network_lte);
+                    }
+                    break;
+                case Phone.NT_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
+                    mButtonEnabledNetworks.setValue(
+                            Integer.toString(Phone.NT_MODE_TDSCDMA_CDMA_EVDO_GSM_WCDMA));
+                    mButtonEnabledNetworks.setSummary(R.string.network_3G);
+                    break;
+                case Phone.NT_MODE_CDMA:
+                case Phone.NT_MODE_EVDO_NO_CDMA:
+                case Phone.NT_MODE_GLOBAL:
+                    mButtonEnabledNetworks.setValue(
+                            Integer.toString(Phone.NT_MODE_CDMA));
+                    mButtonEnabledNetworks.setSummary(R.string.network_3G);
+                    break;
+                case Phone.NT_MODE_CDMA_NO_EVDO:
+                    mButtonEnabledNetworks.setValue(
+                            Integer.toString(Phone.NT_MODE_CDMA_NO_EVDO));
+                    mButtonEnabledNetworks.setSummary(R.string.network_1x);
+                    break;
+                case Phone.NT_MODE_TDSCDMA_ONLY:
+                    mButtonEnabledNetworks.setValue(
+                            Integer.toString(Phone.NT_MODE_TDSCDMA_ONLY));
+                    mButtonEnabledNetworks.setSummary(R.string.network_3G);
+                    break;
+                case Phone.NT_MODE_LTE_TDSCDMA_GSM:
+                case Phone.NT_MODE_LTE_TDSCDMA_GSM_WCDMA:
+                case Phone.NT_MODE_LTE_TDSCDMA:
+                case Phone.NT_MODE_LTE_TDSCDMA_WCDMA:
+                case Phone.NT_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA:
+                case Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA:
+                    if (isSupportTdscdma()) {
+                        mButtonEnabledNetworks.setValue(
+                                Integer.toString(Phone.NT_MODE_LTE_TDSCDMA_CDMA_EVDO_GSM_WCDMA));
+                        mButtonEnabledNetworks.setSummary(R.string.network_lte);
+                    } else {
+                        if (isWorldMode()) {
+                            controlCdmaOptions(true);
+                            controlGsmOptions(false);
+                        }
+                        mButtonEnabledNetworks.setValue(
+                                Integer.toString(Phone.NT_MODE_LTE_CDMA_EVDO_GSM_WCDMA));
+                        if (mPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA ||
+                                mIsGlobalCdma ||
+                                isWorldMode()) {
+                            mButtonEnabledNetworks.setSummary(R.string.network_global);
+                        } else {
+                            mButtonEnabledNetworks.setSummary((mShow4GForLTE == true)
+                                    ? R.string.network_4G : R.string.network_lte);
+                        }
+                    }
+                    break;
+                default:
+                    String errMsg = "Invalid Network Mode (" + NetworkMode + "). Ignore.";
+                    loge(errMsg);
+                    mButtonEnabledNetworks.setSummary(errMsg);
             }
-            break;
-
-        default:
-            break;
         }
-    }
 
-    private static void log(String msg) {
-        Log.d(LOG_TAG, msg);
-    }
+        @Override
+        public void onActivityResult(int requestCode, int resultCode, Intent data) {
+            switch(requestCode) {
+                case REQUEST_CODE_EXIT_ECM:
+                    Boolean isChoiceYes = data.getBooleanExtra(
+                            EmergencyCallbackModeExitDialog.EXTRA_EXIT_ECM_RESULT, false);
+                    if (isChoiceYes) {
+                        // If the phone exits from ECM mode, show the CDMA Options
+                        mCdmaOptions.showDialog(mClickedPreference);
+                    } else {
+                        // do nothing
+                    }
+                    break;
 
-    private static void loge(String msg) {
-        Log.e(LOG_TAG, msg);
-    }
+                default:
+                    break;
+            }
+        }
 
-    @Override
-    public boolean onOptionsItemSelected(MenuItem item) {
-        final int itemId = item.getItemId();
-        if (itemId == android.R.id.home) {  // See ActionBar#setDisplayHomeAsUpEnabled()
-            // Commenting out "logical up" capability. This is a workaround for issue 5278083.
-            //
-            // Settings app may not launch this activity via UP_ACTIVITY_CLASS but the other
-            // Activity that looks exactly same as UP_ACTIVITY_CLASS ("SubSettings" Activity).
-            // At that moment, this Activity launches UP_ACTIVITY_CLASS on top of the Activity.
-            // which confuses users.
-            // TODO: introduce better mechanism for "up" capability here.
+        private static void log(String msg) {
+            Log.d(LOG_TAG, msg);
+        }
+
+        private static void loge(String msg) {
+            Log.e(LOG_TAG, msg);
+        }
+
+        @Override
+        public boolean onOptionsItemSelected(MenuItem item) {
+            final int itemId = item.getItemId();
+            if (itemId == android.R.id.home) {  // See ActionBar#setDisplayHomeAsUpEnabled()
+                // Commenting out "logical up" capability. This is a workaround for issue 5278083.
+                //
+                // Settings app may not launch this activity via UP_ACTIVITY_CLASS but the other
+                // Activity that looks exactly same as UP_ACTIVITY_CLASS ("SubSettings" Activity).
+                // At that moment, this Activity launches UP_ACTIVITY_CLASS on top of the Activity.
+                // which confuses users.
+                // TODO: introduce better mechanism for "up" capability here.
             /*Intent intent = new Intent(Intent.ACTION_MAIN);
             intent.setClassName(UP_ACTIVITY_PACKAGE, UP_ACTIVITY_CLASS);
             intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
             startActivity(intent);*/
-            finish();
-            return true;
-        }
-        return super.onOptionsItemSelected(item);
-    }
-
-    private boolean isWorldMode() {
-        boolean worldModeOn = false;
-        final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
-        final String configString = getResources().getString(R.string.config_world_mode);
-
-        if (!TextUtils.isEmpty(configString)) {
-            String[] configArray = configString.split(";");
-            // Check if we have World mode configuration set to True only or config is set to True
-            // and SIM GID value is also set and matches to the current SIM GID.
-            if (configArray != null &&
-                   ((configArray.length == 1 && configArray[0].equalsIgnoreCase("true")) ||
-                       (configArray.length == 2 && !TextUtils.isEmpty(configArray[1]) &&
-                           tm != null && configArray[1].equalsIgnoreCase(tm.getGroupIdLevel1())))) {
-                               worldModeOn = true;
-            }
-        }
-
-        if (DBG) {
-            log("isWorldMode=" + worldModeOn);
-        }
-
-        return worldModeOn;
-    }
-
-    private void controlGsmOptions(boolean enable) {
-        PreferenceScreen prefSet = getPreferenceScreen();
-        if (prefSet == null) {
-            return;
-        }
-
-        if (mGsmUmtsOptions == null) {
-            mGsmUmtsOptions = new GsmUmtsOptions(this, prefSet, mPhone.getSubId());
-        }
-        PreferenceScreen apnExpand =
-                (PreferenceScreen) prefSet.findPreference(BUTTON_APN_EXPAND_KEY);
-        PreferenceScreen operatorSelectionExpand =
-                (PreferenceScreen) prefSet.findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY);
-        PreferenceScreen carrierSettings =
-                (PreferenceScreen) prefSet.findPreference(BUTTON_CARRIER_SETTINGS_KEY);
-        if (apnExpand != null) {
-            apnExpand.setEnabled(isWorldMode() || enable);
-        }
-        if (operatorSelectionExpand != null) {
-            if (enable) {
-                operatorSelectionExpand.setEnabled(true);
-            } else {
-                prefSet.removePreference(operatorSelectionExpand);
-            }
-        }
-        if (carrierSettings != null) {
-            prefSet.removePreference(carrierSettings);
-        }
-    }
-
-    private void controlCdmaOptions(boolean enable) {
-        PreferenceScreen prefSet = getPreferenceScreen();
-        if (prefSet == null) {
-            return;
-        }
-        if (enable && mCdmaOptions == null) {
-            mCdmaOptions = new CdmaOptions(this, prefSet, mPhone);
-        }
-        CdmaSystemSelectListPreference systemSelect =
-                (CdmaSystemSelectListPreference)prefSet.findPreference
-                        (BUTTON_CDMA_SYSTEM_SELECT_KEY);
-        if (systemSelect != null) {
-            systemSelect.setEnabled(enable);
-        }
-    }
-
-    private boolean isSupportTdscdma() {
-        if (getResources().getBoolean(R.bool.config_support_tdscdma)) {
-            return true;
-        }
-
-        String operatorNumeric = mPhone.getServiceState().getOperatorNumeric();
-        String[] numericArray = getResources().getStringArray(
-                R.array.config_support_tdscdma_roaming_on_networks);
-        if (numericArray.length == 0 || operatorNumeric == null) {
-            return false;
-        }
-        for (String numeric : numericArray) {
-            if (operatorNumeric.equals(numeric)) {
+                getActivity().finish();
                 return true;
             }
+            return super.onOptionsItemSelected(item);
         }
-        return false;
+
+        private boolean isWorldMode() {
+            boolean worldModeOn = false;
+            final TelephonyManager tm =
+                    (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
+            final String configString = getResources().getString(R.string.config_world_mode);
+
+            if (!TextUtils.isEmpty(configString)) {
+                String[] configArray = configString.split(";");
+                // Check if we have World mode configuration set to True only or config is set to True
+                // and SIM GID value is also set and matches to the current SIM GID.
+                if (configArray != null &&
+                        ((configArray.length == 1 && configArray[0].equalsIgnoreCase("true"))
+                                || (configArray.length == 2 && !TextUtils.isEmpty(configArray[1])
+                                && tm != null
+                                && configArray[1].equalsIgnoreCase(tm.getGroupIdLevel1())))) {
+                    worldModeOn = true;
+                }
+            }
+
+            Log.d(LOG_TAG, "isWorldMode=" + worldModeOn);
+
+            return worldModeOn;
+        }
+
+        private void controlGsmOptions(boolean enable) {
+            PreferenceScreen prefSet = getPreferenceScreen();
+            if (prefSet == null) {
+                return;
+            }
+
+            if (mGsmUmtsOptions == null) {
+                mGsmUmtsOptions = new GsmUmtsOptions(this, prefSet, mPhone.getSubId());
+            }
+            PreferenceScreen apnExpand =
+                    (PreferenceScreen) prefSet.findPreference(BUTTON_APN_EXPAND_KEY);
+            PreferenceScreen operatorSelectionExpand =
+                    (PreferenceScreen) prefSet.findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY);
+            PreferenceScreen carrierSettings =
+                    (PreferenceScreen) prefSet.findPreference(BUTTON_CARRIER_SETTINGS_KEY);
+            if (apnExpand != null) {
+                apnExpand.setEnabled(isWorldMode() || enable);
+            }
+            if (operatorSelectionExpand != null) {
+                if (enable) {
+                    operatorSelectionExpand.setEnabled(true);
+                } else {
+                    prefSet.removePreference(operatorSelectionExpand);
+                }
+            }
+            if (carrierSettings != null) {
+                prefSet.removePreference(carrierSettings);
+            }
+        }
+
+        private void controlCdmaOptions(boolean enable) {
+            PreferenceScreen prefSet = getPreferenceScreen();
+            if (prefSet == null) {
+                return;
+            }
+            if (enable && mCdmaOptions == null) {
+                mCdmaOptions = new CdmaOptions(this, prefSet, mPhone);
+            }
+            CdmaSystemSelectListPreference systemSelect =
+                    (CdmaSystemSelectListPreference)prefSet.findPreference
+                            (BUTTON_CDMA_SYSTEM_SELECT_KEY);
+            if (systemSelect != null) {
+                systemSelect.setEnabled(enable);
+            }
+        }
+
+        private boolean isSupportTdscdma() {
+            if (getResources().getBoolean(R.bool.config_support_tdscdma)) {
+                return true;
+            }
+
+            String operatorNumeric = mPhone.getServiceState().getOperatorNumeric();
+            String[] numericArray = getResources().getStringArray(
+                    R.array.config_support_tdscdma_roaming_on_networks);
+            if (numericArray.length == 0 || operatorNumeric == null) {
+                return false;
+            }
+            for (String numeric : numericArray) {
+                if (operatorNumeric.equals(numeric)) {
+                    return true;
+                }
+            }
+            return false;
+        }
     }
 }
+
diff --git a/src/com/android/phone/PhoneGlobals.java b/src/com/android/phone/PhoneGlobals.java
index 842eb06..88ff579 100644
--- a/src/com/android/phone/PhoneGlobals.java
+++ b/src/com/android/phone/PhoneGlobals.java
@@ -336,7 +336,7 @@
             registerReceiver(mReceiver, intentFilter);
 
             //set the default values for the preferences in the phone.
-            PreferenceManager.setDefaultValues(this, R.xml.network_setting, false);
+            PreferenceManager.setDefaultValues(this, R.xml.network_setting_fragment, false);
 
             PreferenceManager.setDefaultValues(this, R.xml.call_feature_setting, false);
 
@@ -695,7 +695,7 @@
                 handleServiceStateChanged(intent);
             } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
                 int phoneId = intent.getIntExtra(PhoneConstants.PHONE_KEY, 0);
-                phoneInEcm = getPhone(phoneId);
+                phoneInEcm = PhoneFactory.getPhone(phoneId);
                 Log.d(LOG_TAG, "Emergency Callback Mode. phoneId:" + phoneId);
                 if (phoneInEcm != null) {
                     if (TelephonyCapabilities.supportsEcm(phoneInEcm)) {
diff --git a/src/com/android/phone/PhoneInterfaceManager.java b/src/com/android/phone/PhoneInterfaceManager.java
index c8b609a..7e211b6 100644
--- a/src/com/android/phone/PhoneInterfaceManager.java
+++ b/src/com/android/phone/PhoneInterfaceManager.java
@@ -83,7 +83,9 @@
 import com.android.internal.telephony.SubscriptionController;
 import com.android.internal.telephony.uicc.IccIoResult;
 import com.android.internal.telephony.uicc.IccUtils;
+import com.android.internal.telephony.uicc.SIMRecords;
 import com.android.internal.telephony.uicc.UiccCard;
+import com.android.internal.telephony.uicc.UiccCardApplication;
 import com.android.internal.telephony.uicc.UiccController;
 import com.android.internal.util.HexDump;
 import com.android.phone.settings.VisualVoicemailSettingsUtil;
@@ -151,6 +153,8 @@
     private static final int EVENT_SET_ALLOWED_CARRIERS_DONE = 44;
     private static final int CMD_GET_ALLOWED_CARRIERS = 45;
     private static final int EVENT_GET_ALLOWED_CARRIERS_DONE = 46;
+    private static final int CMD_GET_FORBIDDEN_PLMNS = 48;
+    private static final int EVENT_GET_FORBIDDEN_PLMNS_DONE = 49;
 
     /** The singleton instance. */
     private static PhoneInterfaceManager sInstance;
@@ -835,6 +839,56 @@
                     }
                     break;
 
+                case EVENT_GET_FORBIDDEN_PLMNS_DONE:
+                    ar = (AsyncResult) msg.obj;
+                    request = (MainThreadRequest) ar.userObj;
+                    if (ar.exception == null && ar.result != null) {
+                        request.result = ar.result;
+                    } else {
+                        request.result = new IllegalArgumentException(
+                                "Failed to retrieve Forbidden Plmns");
+                        if (ar.result == null) {
+                            loge("getForbiddenPlmns: Empty response");
+                        } else {
+                            loge("getForbiddenPlmns: Unknown exception");
+                        }
+                    }
+                    synchronized (request) {
+                        request.notifyAll();
+                    }
+                    break;
+
+                case CMD_GET_FORBIDDEN_PLMNS:
+                    request = (MainThreadRequest) msg.obj;
+                    uiccCard = getUiccCardFromRequest(request);
+                    if (uiccCard == null) {
+                        loge("getForbiddenPlmns() UiccCard is null");
+                        request.result = new IllegalArgumentException(
+                                "getForbiddenPlmns() UiccCard is null");
+                        synchronized (request) {
+                            request.notifyAll();
+                        }
+                        break;
+                    }
+                    Integer appType = (Integer) request.argument;
+                    UiccCardApplication uiccApp = uiccCard.getApplicationByType(appType);
+                    if (uiccApp == null) {
+                        loge("getForbiddenPlmns() no app with specified type -- "
+                                + appType);
+                        request.result = new IllegalArgumentException("Failed to get UICC App");
+                        synchronized (request) {
+                            request.notifyAll();
+                        }
+                        break;
+                    } else {
+                        if (DBG) logv("getForbiddenPlmns() found app " + uiccApp.getAid()
+                                + " specified type -- " + appType);
+                    }
+                    onCompleted = obtainMessage(EVENT_GET_FORBIDDEN_PLMNS_DONE, request);
+                    ((SIMRecords) uiccApp.getIccRecords()).getForbiddenPlmns(
+                              onCompleted);
+                    break;
+
                 default:
                     Log.w(LOG_TAG, "MainThreadHandler: unexpected message code: " + msg.what);
                     break;
@@ -1483,8 +1537,8 @@
         return getCallStateForSlot(getSlotForDefaultSubscription());
     }
 
-    public int getCallStateForSlot(int slotId) {
-        Phone phone = PhoneFactory.getPhone(slotId);
+    public int getCallStateForSlot(int slotIndex) {
+        Phone phone = PhoneFactory.getPhone(slotIndex);
         return phone == null ? TelephonyManager.CALL_STATE_IDLE :
             DefaultPhoneNotifier.convertCallState(phone.getState());
     }
@@ -1653,20 +1707,29 @@
     }
 
     @Override
-    public String getImeiForSlot(int slotId, String callingPackage) {
+    public String getImeiForSlot(int slotIndex, String callingPackage) {
       if (!canReadPhoneState(callingPackage, "getImeiForSlot")) {
           return null;
       }
-      Phone phone = PhoneFactory.getPhone(slotId);
+      Phone phone = PhoneFactory.getPhone(slotIndex);
       return phone == null ? null : phone.getImei();
     }
 
     @Override
-    public String getDeviceSoftwareVersionForSlot(int slotId, String callingPackage) {
+    public String getMeidForSlot(int slotIndex, String callingPackage) {
+        if (!canReadPhoneState(callingPackage, "getMeidForSlot")) {
+            return null;
+        }
+        Phone phone = PhoneFactory.getPhone(slotIndex);
+        return phone == null ? null : phone.getMeid();
+    }
+
+    @Override
+    public String getDeviceSoftwareVersionForSlot(int slotIndex, String callingPackage) {
       if (!canReadPhoneState(callingPackage, "getDeviceSoftwareVersionForSlot")) {
           return null;
       }
-      Phone phone = PhoneFactory.getPhone(slotId);
+      Phone phone = PhoneFactory.getPhone(slotIndex);
       return phone == null ? null : phone.getDeviceSvn();
     }
 
@@ -1794,8 +1857,8 @@
     }
 
     @Override
-    public int getActivePhoneTypeForSlot(int slotId) {
-        final Phone phone = PhoneFactory.getPhone(slotId);
+    public int getActivePhoneTypeForSlot(int slotIndex) {
+        final Phone phone = PhoneFactory.getPhone(slotIndex);
         if (phone == null) {
             return PhoneConstants.PHONE_TYPE_NONE;
         } else {
@@ -2126,15 +2189,16 @@
      */
     public boolean hasIccCard() {
         // FIXME Make changes to pass defaultSimId of type int
-        return hasIccCardUsingSlotId(mSubscriptionController.getSlotId(getDefaultSubscription()));
+        return hasIccCardUsingSlotIndex(mSubscriptionController.getSlotIndex(
+                getDefaultSubscription()));
     }
 
     /**
-     * @return true if a ICC card is present for a slotId
+     * @return true if a ICC card is present for a slotIndex
      */
     @Override
-    public boolean hasIccCardUsingSlotId(int slotId) {
-        int subId[] = mSubscriptionController.getSubIdUsingSlotId(slotId);
+    public boolean hasIccCardUsingSlotIndex(int slotIndex) {
+        int subId[] = mSubscriptionController.getSubIdUsingSlotIndex(slotIndex);
         final Phone phone = getPhone(subId[0]);
         if (subId != null && phone != null) {
             return phone.getIccCard().hasIccCard();
@@ -2322,6 +2386,26 @@
         return result;
     }
 
+    /**
+     * Get the forbidden PLMN List from the given app type (ex APPTYPE_USIM)
+     * on a particular subscription
+     */
+    public String[] getForbiddenPlmns(int subId, int appType) {
+        mApp.enforceCallingOrSelfPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
+                "Requires READ_PRIVILEGED_PHONE_STATE");
+        if (appType != TelephonyManager.APPTYPE_USIM && appType != TelephonyManager.APPTYPE_SIM) {
+            loge("getForbiddenPlmnList(): App Type must be USIM or SIM");
+            return null;
+        }
+        Object response = sendRequest(
+            CMD_GET_FORBIDDEN_PLMNS, new Integer(appType), subId);
+        if (response instanceof String[]) {
+            return (String[]) response;
+        }
+        // Response is an Exception of some kind, which is signalled to the user as a NULL retval
+        return null;
+    }
+
     @Override
     public String sendEnvelopeWithStatus(int subId, String content) {
         enforceModifyPermissionOrCarrierPrivilege(subId);
@@ -2428,10 +2512,10 @@
      * available, the {@link IImsServiceFeatureListener} callback is registered as a listener for
      * feature updates.
      */
-    public IImsServiceController getImsServiceControllerAndListen(int slotId, int feature,
+    public IImsServiceController getImsServiceControllerAndListen(int slotIndex, int feature,
             IImsServiceFeatureListener callback) {
         enforceModifyPermission();
-        return PhoneFactory.getImsResolver().getImsServiceControllerAndListen(slotId, feature,
+        return PhoneFactory.getImsResolver().getImsServiceControllerAndListen(slotIndex, feature,
                 callback);
     }
 
@@ -2883,6 +2967,7 @@
     }
 
     @Override
+    @Deprecated
     public int invokeOemRilRequestRaw(byte[] oemReq, byte[] oemResp) {
         enforceModifyPermission();
 
@@ -3349,31 +3434,31 @@
 
     /**
      * {@hide}
-     * Set the allowed carrier list for slotId
+     * Set the allowed carrier list for slotIndex
      * Require system privileges. In the future we may add this to carrier APIs.
      *
      * @return The number of carriers set successfully, should match length of carriers
      */
     @Override
-    public int setAllowedCarriers(int slotId, List<CarrierIdentifier> carriers) {
+    public int setAllowedCarriers(int slotIndex, List<CarrierIdentifier> carriers) {
         enforceModifyPermission();
-        int subId = SubscriptionManager.getSubId(slotId)[0];
+        int subId = SubscriptionManager.getSubId(slotIndex)[0];
         int[] retVal = (int[]) sendRequest(CMD_SET_ALLOWED_CARRIERS, carriers, subId);
         return retVal[0];
     }
 
     /**
      * {@hide}
-     * Get the allowed carrier list for slotId.
+     * Get the allowed carrier list for slotIndex.
      * Require system privileges. In the future we may add this to carrier APIs.
      *
      * @return List of {@link android.service.telephony.CarrierIdentifier}; empty list
      * means all carriers are allowed.
      */
     @Override
-    public List<CarrierIdentifier> getAllowedCarriers(int slotId) {
+    public List<CarrierIdentifier> getAllowedCarriers(int slotIndex) {
         enforceReadPrivilegedPermission();
-        int subId = SubscriptionManager.getSubId(slotId)[0];
+        int subId = SubscriptionManager.getSubId(slotIndex)[0];
         return (List<CarrierIdentifier>) sendRequest(CMD_GET_ALLOWED_CARRIERS, null, subId);
     }
 
@@ -3508,14 +3593,14 @@
     /**
      * Set SIM card power state. Request is equivalent to inserting or removing the card.
      *
-     * @param slotId SIM slot id.
+     * @param slotIndex SIM slot id.
      * @param powerUp True if powering up the SIM, otherwise powering down
      *
      **/
     @Override
-    public void setSimPowerStateForSlot(int slotId, boolean powerUp) {
+    public void setSimPowerStateForSlot(int slotIndex, boolean powerUp) {
         enforceModifyPermission();
-        int subId[] = mSubscriptionController.getSubIdUsingSlotId(slotId);
+        int subId[] = mSubscriptionController.getSubIdUsingSlotIndex(slotIndex);
         if (subId == null || subId.length == 0) {
             return;
         }
diff --git a/src/com/android/phone/PhoneSearchIndexablesProvider.java b/src/com/android/phone/PhoneSearchIndexablesProvider.java
index f1dacd9..85ea653 100644
--- a/src/com/android/phone/PhoneSearchIndexablesProvider.java
+++ b/src/com/android/phone/PhoneSearchIndexablesProvider.java
@@ -37,7 +37,7 @@
     private static final String TAG = "PhoneSearchIndexablesProvider";
 
     private static SearchIndexableResource[] INDEXABLE_RES = new SearchIndexableResource[] {
-            new SearchIndexableResource(1, R.xml.network_setting,
+            new SearchIndexableResource(1, R.xml.network_setting_fragment,
                     MobileNetworkSettings.class.getName(),
                     R.mipmap.ic_launcher_phone),
     };
diff --git a/src/com/android/phone/RoamingDialogFragment.java b/src/com/android/phone/RoamingDialogFragment.java
new file mode 100644
index 0000000..21c6946
--- /dev/null
+++ b/src/com/android/phone/RoamingDialogFragment.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2016 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.phone;
+
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.app.DialogFragment;
+import android.app.Fragment;
+import android.app.FragmentManager;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.DialogInterface.OnClickListener;
+import android.os.Bundle;
+
+/**
+ * A dialog fragment that asks the user if they are sure they want to turn on data roaming
+ * to avoid accidental charges.
+ */
+public class RoamingDialogFragment extends DialogFragment implements OnClickListener {
+
+    /**
+     * The interface we expect a host activity to implement.
+     */
+    public interface RoamingDialogListener {
+        void onPositiveButtonClick(DialogFragment dialog);
+    }
+
+    // the host activity which implements the listening interface
+    private RoamingDialogListener mListener;
+
+
+    @Override
+    public void onAttach(Context context) {
+        super.onAttach(context);
+        // Verify host activity implemented callback interface
+        FragmentManager fragmentManager = getFragmentManager();
+        Fragment fragment = fragmentManager.findFragmentById(R.id.network_setting_content);
+        try {
+            mListener = (RoamingDialogListener) fragment;
+        } catch (ClassCastException e) {
+            throw new ClassCastException(fragment.toString() +
+                    "must implement RoamingDialogListener");
+        }
+    }
+
+    @Override
+    public Dialog onCreateDialog(Bundle savedInstanceState) {
+        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
+        builder.setMessage(getResources().getString(R.string.roaming_warning))
+                .setTitle(R.string.roaming_alert_title)
+                .setIconAttribute(android.R.attr.alertDialogIcon)
+                .setPositiveButton(android.R.string.yes, this)
+                .setNegativeButton(android.R.string.no, this);
+        return builder.create();
+    }
+
+    @Override
+    public void onClick(DialogInterface dialog, int which) {
+        // let the host know that the positive button has been clicked
+        if (which == dialog.BUTTON_POSITIVE) {
+            mListener.onPositiveButtonClick(this);
+        }
+    }
+}
diff --git a/src/com/android/phone/settings/PhoneAccountSettingsFragment.java b/src/com/android/phone/settings/PhoneAccountSettingsFragment.java
index 77de3f5..07402db 100644
--- a/src/com/android/phone/settings/PhoneAccountSettingsFragment.java
+++ b/src/com/android/phone/settings/PhoneAccountSettingsFragment.java
@@ -310,8 +310,8 @@
                 int subId2 = mTelephonyManager.getSubIdForPhoneAccount(account2);
                 if (subId1 != SubscriptionManager.INVALID_SUBSCRIPTION_ID &&
                         subId2 != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
-                    retval = (mSubscriptionManager.getSlotId(subId1) <
-                        mSubscriptionManager.getSlotId(subId2)) ? -1 : 1;
+                    retval = (mSubscriptionManager.getSlotIndex(subId1) <
+                        mSubscriptionManager.getSlotIndex(subId2)) ? -1 : 1;
                 }
 
                 // Then order by package
diff --git a/src/com/android/phone/settings/VoicemailSettingsActivity.java b/src/com/android/phone/settings/VoicemailSettingsActivity.java
index d9d410e..9db20e8 100644
--- a/src/com/android/phone/settings/VoicemailSettingsActivity.java
+++ b/src/com/android/phone/settings/VoicemailSettingsActivity.java
@@ -24,6 +24,7 @@
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
+import android.os.UserManager;
 import android.preference.CheckBoxPreference;
 import android.preference.Preference;
 import android.preference.PreferenceActivity;
@@ -37,6 +38,8 @@
 import android.util.Log;
 import android.view.MenuItem;
 import android.widget.ListAdapter;
+import android.widget.Toast;
+
 import com.android.internal.telephony.CallForwardInfo;
 import com.android.internal.telephony.Phone;
 import com.android.internal.telephony.PhoneConstants;
@@ -214,7 +217,14 @@
     @Override
     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);
-
+        // Make sure we are running as the primary user only
+        UserManager userManager = getApplicationContext().getSystemService(UserManager.class);
+        if (!userManager.isPrimaryUser()) {
+           Toast.makeText(this, R.string.voice_number_setting_primary_user_only,
+                   Toast.LENGTH_SHORT).show();
+           finish();
+           return;
+        }
         // Show the voicemail preference in onResume if the calling intent specifies the
         // ACTION_ADD_VOICEMAIL action.
         mShowVoicemailPreference = (icicle == null) &&
@@ -227,6 +237,7 @@
         mPhoneAccountHandle = PhoneUtils.makePstnPhoneAccountHandle(mPhone);
         mOmtpVvmCarrierConfigHelper = new OmtpVvmCarrierConfigHelper(
                 mPhone.getContext(), mPhone.getSubId());
+        addPreferencesFromResource(R.xml.voicemail_settings);
     }
 
     @Override
@@ -234,19 +245,17 @@
         super.onResume();
         mForeground = true;
 
-        PreferenceScreen preferenceScreen = getPreferenceScreen();
-        if (preferenceScreen != null) {
-            preferenceScreen.removeAll();
-        }
-
-        addPreferencesFromResource(R.xml.voicemail_settings);
-
         PreferenceScreen prefSet = getPreferenceScreen();
 
         if (mSubMenuVoicemailSettings == null) {
             mSubMenuVoicemailSettings =
                     (EditPhoneNumberPreference) findPreference(BUTTON_VOICEMAIL_KEY);
         }
+        if (mSubMenuVoicemailSettings != null) {
+            mSubMenuVoicemailSettings.setParentActivity(this, VOICEMAIL_PREF_ID, this);
+            mSubMenuVoicemailSettings.setDialogOnClosedListener(this);
+            mSubMenuVoicemailSettings.setDialogTitle(R.string.voicemail_settings_number_label);
+        }
 
         mVoicemailProviders = (VoicemailProviderListPreference) findPreference(
                 BUTTON_VOICEMAIL_PROVIDER_KEY);
@@ -265,34 +274,36 @@
                 getResources().getString(R.string.voicemail_notification_vibrate_key));
         mVoicemailNotificationVibrate.setOnPreferenceChangeListener(this);
 
-        mVoicemailVisualVoicemail = (SwitchPreference) findPreference(
+        mVoicemailVisualVoicemail = (SwitchPreference) prefSet.findPreference(
                 getResources().getString(R.string.voicemail_visual_voicemail_key));
 
-        mVoicemailChangePinPreference = findPreference(
+        mVoicemailChangePinPreference = prefSet.findPreference(
                 getResources().getString(R.string.voicemail_change_pin_key));
-        Intent changePinIntent = new Intent(new Intent(this, VoicemailChangePinActivity.class));
-        changePinIntent.putExtra(VoicemailChangePinActivity.EXTRA_PHONE_ACCOUNT_HANDLE,
-                mPhoneAccountHandle);
+        if (mVoicemailChangePinPreference != null) {
+            Intent changePinIntent = new Intent(new Intent(this, VoicemailChangePinActivity.class));
+            changePinIntent.putExtra(VoicemailChangePinActivity.EXTRA_PHONE_ACCOUNT_HANDLE,
+                    mPhoneAccountHandle);
 
-        mVoicemailChangePinPreference.setIntent(changePinIntent);
-        if (VoicemailChangePinActivity.isDefaultOldPinSet(this, mPhoneAccountHandle)) {
-            mVoicemailChangePinPreference.setTitle(R.string.voicemail_set_pin_dialog_title);
-        } else {
-            mVoicemailChangePinPreference.setTitle(R.string.voicemail_change_pin_dialog_title);
+            mVoicemailChangePinPreference.setIntent(changePinIntent);
+            if (VoicemailChangePinActivity.isDefaultOldPinSet(this, mPhoneAccountHandle)) {
+                mVoicemailChangePinPreference.setTitle(R.string.voicemail_set_pin_dialog_title);
+            } else {
+                mVoicemailChangePinPreference.setTitle(R.string.voicemail_change_pin_dialog_title);
+            }
         }
-
-        if (mOmtpVvmCarrierConfigHelper.isValid()) {
-            mVoicemailVisualVoicemail.setOnPreferenceChangeListener(this);
-            mVoicemailVisualVoicemail.setChecked(
-                    VisualVoicemailSettingsUtil.isEnabled(this, mPhoneAccountHandle));
-            if (!isVisualVoicemailActivated()) {
+        if (mVoicemailVisualVoicemail != null) {
+            if (mOmtpVvmCarrierConfigHelper.isValid()) {
+                mVoicemailVisualVoicemail.setOnPreferenceChangeListener(this);
+                mVoicemailVisualVoicemail.setChecked(
+                        VisualVoicemailSettingsUtil.isEnabled(this, mPhoneAccountHandle));
+                if (!isVisualVoicemailActivated()) {
+                    prefSet.removePreference(mVoicemailChangePinPreference);
+                }
+            } else {
+                prefSet.removePreference(mVoicemailVisualVoicemail);
                 prefSet.removePreference(mVoicemailChangePinPreference);
             }
-        } else {
-            prefSet.removePreference(mVoicemailVisualVoicemail);
-            prefSet.removePreference(mVoicemailChangePinPreference);
         }
-
         updateVMPreferenceWidgets(mVoicemailProviders.getValue());
 
         // check the intent that started this activity and pop up the voicemail
diff --git a/src/com/android/phone/settings/fdn/EditFdnContactScreen.java b/src/com/android/phone/settings/fdn/EditFdnContactScreen.java
index 1387215..23ef0bb 100644
--- a/src/com/android/phone/settings/fdn/EditFdnContactScreen.java
+++ b/src/com/android/phone/settings/fdn/EditFdnContactScreen.java
@@ -281,7 +281,7 @@
       * TODO: Fix this logic.
       */
      private boolean isValidNumber(String number) {
-         return (number.length() <= 20);
+         return (number.length() <= 20) && (number.length() > 0);
      }
 
 
@@ -419,6 +419,12 @@
             } else if (v == mNumberField) {
                 mButton.requestFocus();
             } else if (v == mButton) {
+                final String number = PhoneNumberUtils.convertAndStrip(getNumberFromTextField());
+
+                if (!isValidNumber(number)) {
+                    handleResult(false, true);
+                    return;
+                }
                 // Authenticate the pin AFTER the contact information
                 // is entered, and if we're not busy.
                 if (!mDataBusy) {
diff --git a/src/com/android/services/telephony/ConferenceParticipantConnection.java b/src/com/android/services/telephony/ConferenceParticipantConnection.java
index ed7ad44..19dda54 100644
--- a/src/com/android/services/telephony/ConferenceParticipantConnection.java
+++ b/src/com/android/services/telephony/ConferenceParticipantConnection.java
@@ -16,6 +16,7 @@
 
 package com.android.services.telephony;
 
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.telephony.Phone;
 import com.android.internal.telephony.PhoneConstants;
 
@@ -70,7 +71,7 @@
             address = null;
         } else {
             String countryIso = getCountryIso(parentConnection.getCall().getPhone());
-            address = getParticipantAddress(participant, countryIso);
+            address = getParticipantAddress(participant.getHandle(), countryIso);
         }
         setAddress(address, presentation);
         setCallerDisplayName(participant.getDisplayName(), presentation);
@@ -212,21 +213,19 @@
      * Conference event package data contains SIP URIs, so we try to extract the phone number and
      * format into a typical tel: style URI.
      *
-     * @param participant The conference participant.
+     * @param address The conference participant's address.
      * @param countryIso The country ISO of the current subscription; used when formatting the
      *                   participant phone number to E.164 format.
      * @return The participant's address URI.
      */
-    private Uri getParticipantAddress(ConferenceParticipant participant, String countryIso) {
-        Uri address = participant.getHandle();
+    @VisibleForTesting
+    public static Uri getParticipantAddress(Uri address, String countryIso) {
         if (address == null) {
             return address;
         }
-
-        // If the participant's address is already a TEL scheme, just return it as is.
-        if (PhoneAccount.SCHEME_TEL.equals(address.getScheme())) {
-            return address;
-        }
+        // Even if address is already in tel: format, still parse it and rebuild.
+        // This is to recognize tel URIs such as:
+        // tel:6505551212;phone-context=ims.mnc012.mcc034.3gppnetwork.org
 
         // Conference event package participants are identified using SIP URIs (see RFC3261).
         // A valid SIP uri has the format: sip:user:password@host:port;uri-parameters?headers
diff --git a/src/com/android/services/telephony/TelecomAccountRegistry.java b/src/com/android/services/telephony/TelecomAccountRegistry.java
index b2e9984..fbb6433 100644
--- a/src/com/android/services/telephony/TelecomAccountRegistry.java
+++ b/src/com/android/services/telephony/TelecomAccountRegistry.java
@@ -152,7 +152,7 @@
                 }
 
                 String slotIdString;
-                if (SubscriptionManager.isValidSlotId(slotId)) {
+                if (SubscriptionManager.isValidSlotIndex(slotId)) {
                     slotIdString = Integer.toString(slotId);
                 } else {
                     slotIdString = mContext.getResources().getString(R.string.unknown);
diff --git a/src/com/android/services/telephony/TelephonyConnectionService.java b/src/com/android/services/telephony/TelephonyConnectionService.java
index 71076f3..2b6824c 100644
--- a/src/com/android/services/telephony/TelephonyConnectionService.java
+++ b/src/com/android/services/telephony/TelephonyConnectionService.java
@@ -42,12 +42,12 @@
 
 import com.android.internal.telephony.Call;
 import com.android.internal.telephony.CallStateException;
+import com.android.internal.telephony.GsmCdmaPhone;
 import com.android.internal.telephony.IccCard;
 import com.android.internal.telephony.IccCardConstants;
 import com.android.internal.telephony.Phone;
 import com.android.internal.telephony.PhoneConstants;
 import com.android.internal.telephony.PhoneFactory;
-import com.android.internal.telephony.SubscriptionController;
 import com.android.internal.telephony.imsphone.ImsExternalCallTracker;
 import com.android.internal.telephony.imsphone.ImsPhone;
 import com.android.phone.MMIDialogActivity;
@@ -727,6 +727,18 @@
         try {
             if (phone != null) {
                 originalConnection = phone.dial(number, null, videoState, extras);
+
+                if (phone instanceof GsmCdmaPhone) {
+                    GsmCdmaPhone gsmCdmaPhone = (GsmCdmaPhone) phone;
+                    if (gsmCdmaPhone.isNotificationOfWfcCallRequired(number)) {
+                        // Send connection event to InCall UI to inform the user of the fact they
+                        // are potentially placing an international call on WFC.
+                        Log.i(this, "placeOutgoingConnection - sending international call on WFC " +
+                                "confirmation event");
+                        connection.sendConnectionEvent(
+                                TelephonyManager.EVENT_NOTIFY_INTERNATIONAL_CALL_ON_WFC, null);
+                    }
+                }
             }
         } catch (CallStateException e) {
             Log.e(this, e, "placeOutgoingConnection, phone.dial exception: " + e);
@@ -807,7 +819,7 @@
         Phone chosenPhone = null;
         int subId = PhoneUtils.getSubIdForPhoneAccountHandle(accountHandle);
         if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
-            int phoneId = SubscriptionController.getInstance().getPhoneId(subId);
+            int phoneId = SubscriptionManager.getPhoneId(subId);
             chosenPhone = PhoneFactory.getPhone(phoneId);
         }
         // If this is an emergency call and the phone we originally planned to make this call
diff --git a/tests/Android.mk b/tests/Android.mk
index 66df1a8..2feb55a 100644
--- a/tests/Android.mk
+++ b/tests/Android.mk
@@ -32,6 +32,8 @@
 LOCAL_STATIC_JAVA_LIBRARIES := \
         android-support-test \
         mockito-target \
-        legacy-android-test
-
+        legacy-android-test \
+        mockito-target-minus-junit4 \
+        espresso-core \
+        truth-prebuilt
 include $(BUILD_PACKAGE)
diff --git a/tests/src/com/android/phone/RoamingDialogFragmentTest.java b/tests/src/com/android/phone/RoamingDialogFragmentTest.java
new file mode 100644
index 0000000..96a3fda
--- /dev/null
+++ b/tests/src/com/android/phone/RoamingDialogFragmentTest.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright (C) 2016 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.phone;
+
+import android.app.Activity;
+import android.content.pm.ActivityInfo;
+import android.provider.Settings.Global;
+import android.provider.Settings.SettingNotFoundException;
+import android.support.test.espresso.matcher.PreferenceMatchers;
+import android.support.test.rule.ActivityTestRule;
+import com.google.common.truth.Truth;
+import junit.framework.AssertionFailedError;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static android.support.test.espresso.Espresso.onData;
+import static android.support.test.espresso.Espresso.onView;
+import static android.support.test.espresso.action.ViewActions.click;
+import static android.support.test.espresso.assertion.ViewAssertions.doesNotExist;
+import static android.support.test.espresso.assertion.ViewAssertions.matches;
+import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant;
+import static android.support.test.espresso.matcher.ViewMatchers.isChecked;
+import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
+import static android.support.test.espresso.matcher.ViewMatchers.withId;
+import static android.support.test.espresso.matcher.ViewMatchers.withText;
+import static com.google.common.truth.Truth.assertThat;
+
+/**
+ * Espresso tests to check some properties of the dialog that appears when a user
+ * tries to turn on data roaming.
+ */
+public class RoamingDialogFragmentTest {
+
+    @Rule
+    public ActivityTestRule<MobileNetworkSettings> mRule =
+            new ActivityTestRule<>(MobileNetworkSettings.class);
+    private Activity mActivity;
+
+    /**
+     * Make sure roaming is off before we start a test since this checks the dialog that only
+     * shows up when we try to turn it on.
+     */
+    @Before
+    public void disableRoaming() {
+        mActivity = mRule.getActivity();
+
+        // turn off data roaming if it is on
+        try {
+            onData(PreferenceMatchers.withTitle(R.string.roaming))
+                    .check(matches(hasDescendant(isChecked())))
+                    .perform(click());
+        } catch (AssertionFailedError e) {
+            // don't click the switch if it is already off.
+        }
+    }
+
+    @Test
+    public void dataRoamingDialogPersistsOnRotation() {
+        // click on the data roaming preference to trigger warning dialog
+        onData(PreferenceMatchers.withTitle(R.string.roaming)).perform(click());
+
+        // request both orientations to ensure at least one rotation occurs
+        mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
+        mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
+
+        // verify the title of the dialog is visible
+        onView(withText(R.string.roaming_alert_title)).check(matches(isDisplayed()));
+
+    }
+
+    @Test
+    public void dataRoamingEnabledWhenPositiveButtonClicked() throws SettingNotFoundException {
+        // click on the data roaming preference to trigger warning dialog
+        onData(PreferenceMatchers.withTitle(R.string.roaming)).perform(click());
+
+        // click to confirm we want to turn on data roaming
+        onView(withId(android.R.id.button1)).perform(click());
+
+        // verify that the the setting has actually been changed
+        assertThat(Global.getInt(mActivity.getApplicationContext().getContentResolver(),
+                Global.DATA_ROAMING)).isEqualTo(1);
+    }
+
+    @Test
+    public void dialogDismissedOnNegativeButtonClicked() {
+        // click on the data roaming preference to trigger warning dialog
+        onData(PreferenceMatchers.withTitle(R.string.roaming)).perform(click());
+
+        // click to cancel turning on data roaming
+        onView(withId(android.R.id.button2)).perform(click());
+
+        // verify the title of the dialog is gone
+        onView(withText(R.string.roaming_alert_title)).check(doesNotExist());
+    }
+
+    @Test
+    public void dataRoamingStaysDisabledWhenDialogCanceled() throws SettingNotFoundException {
+        // click on the data roaming preference to trigger warning dialog
+        onData(PreferenceMatchers.withTitle(R.string.roaming)).perform(click());
+
+        // click to cancel turning on data roaming
+        onView(withId(android.R.id.button2)).perform(click());
+
+        // verify that the the setting has not been changed
+        assertThat(Global.getInt(mActivity.getApplicationContext().getContentResolver(),
+                Global.DATA_ROAMING)).isEqualTo(0);
+
+    }
+}
diff --git a/tests/src/com/android/services/telephony/ConferenceParticipantConnectionTest.java b/tests/src/com/android/services/telephony/ConferenceParticipantConnectionTest.java
new file mode 100644
index 0000000..73fe0af
--- /dev/null
+++ b/tests/src/com/android/services/telephony/ConferenceParticipantConnectionTest.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.services.telephony;
+
+import android.net.Uri;
+import android.support.test.runner.AndroidJUnit4;
+import android.telecom.Conference;
+import android.telecom.ConferenceParticipant;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import static com.android.services.telephony.ConferenceParticipantConnection.getParticipantAddress;
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Tests proper parsing of conference event package participant addresses.
+ */
+@RunWith(AndroidJUnit4.class)
+public class ConferenceParticipantConnectionTest {
+
+    @Test
+    public void testParticipantParseSimpleTel() {
+        assertUrisEqual(Uri.parse("tel:+16505551212"),
+                getParticipantAddress(Uri.parse("tel:6505551212"), "US"));
+    }
+
+    @Test
+    public void testParticipantParseTelExtended() {
+        assertUrisEqual(Uri.parse("tel:+16505551212"),
+                getParticipantAddress(Uri.parse("tel:6505551212;phone-context=blah"), "US"));
+    }
+
+    @Test
+    public void testParticipantParseSip() {
+        assertUrisEqual(Uri.parse("tel:+16505551212"),
+                getParticipantAddress(Uri.parse("sip:16505551212;phone-context=blah.com@host.com"),
+                        "US"));
+    }
+
+    @Test
+    public void testParticipantParseSip2() {
+        assertUrisEqual(Uri.parse("tel:+12125551212"),
+                getParticipantAddress(Uri.parse("sip:+1-212-555-1212@something.com;user=phone"),
+                        "US"));
+    }
+
+    @Test
+    public void testParticipantParseTelJp() {
+        assertUrisEqual(Uri.parse("tel:+819066570660"),
+                getParticipantAddress(Uri.parse(
+                        "tel:09066570660;phone-context=ims.mnc020.mcc440.3gppnetwork.org"),
+                        "JP"));
+    }
+
+    @Test
+    public void testParticipantParseSipJp() {
+        assertUrisEqual(Uri.parse("tel:+819066571180"),
+                getParticipantAddress(Uri.parse(
+                        "sip:+819066571180@ims.mnc020.mcc440.3gppnetwork.org;user=phone"),
+                        "JP"));
+    }
+
+    private void assertUrisEqual(Uri expected, Uri actual) {
+        assertEquals(expected.getScheme(), actual.getScheme());
+        assertEquals(expected.getSchemeSpecificPart(), actual.getSchemeSpecificPart());
+    }
+}