Merge "Launch TetherSettings via Settings.ACTION_TETHER_SETTINGS"
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 4afb097..4c9e91a 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -102,6 +102,7 @@
     <uses-permission android:name="android.permission.MANAGE_SCOPED_ACCESS_DIRECTORY_PERMISSIONS" />
     <uses-permission android:name="android.permission.CAMERA" />
     <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
+    <uses-permission android:name="android.permission.BIND_CELL_BROADCAST_SERVICE" />
 
     <application android:label="@string/settings_label"
             android:icon="@drawable/ic_launcher_settings"
diff --git a/TEST_MAPPING b/TEST_MAPPING
new file mode 100644
index 0000000..4865e19
--- /dev/null
+++ b/TEST_MAPPING
@@ -0,0 +1,15 @@
+{
+  "postsubmit": [
+    {
+      "name": "SettingsUnitTests",
+      "options": [
+        {
+          "exclude-annotation": "androidx.test.filters.FlakyTest"
+        }
+      ]
+    },
+    {
+      "name": "SettingsPerfTests"
+    }
+  ]
+}
diff --git a/src/com/android/settings/IccLockSettings.java b/src/com/android/settings/IccLockSettings.java
index 8880001..eed3b49 100644
--- a/src/com/android/settings/IccLockSettings.java
+++ b/src/com/android/settings/IccLockSettings.java
@@ -24,11 +24,12 @@
 import android.content.res.Configuration;
 import android.content.res.Resources;
 import android.graphics.PixelFormat;
-import android.os.AsyncResult;
+import android.os.AsyncTask;
 import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
 import android.telephony.SubscriptionInfo;
+import android.telephony.TelephonyManager;
 import android.text.TextUtils;
 import android.util.Log;
 import android.view.Gravity;
@@ -49,9 +50,6 @@
 import androidx.preference.Preference;
 import androidx.preference.SwitchPreference;
 
-import com.android.internal.telephony.CommandException;
-import com.android.internal.telephony.Phone;
-import com.android.internal.telephony.PhoneFactory;
 import com.android.internal.telephony.TelephonyIntents;
 import com.android.settings.network.ProxySubscriptionManager;
 
@@ -112,7 +110,6 @@
     private TabWidget mTabWidget;
     private ListView mListView;
 
-    private Phone mPhone;
     private ProxySubscriptionManager mProxySubscriptionMgr;
 
     private EditPinPreference mPinDialog;
@@ -121,24 +118,18 @@
     private Resources mRes;
 
     // For async handler to identify request type
-    private static final int MSG_ENABLE_ICC_PIN_COMPLETE = 100;
-    private static final int MSG_CHANGE_ICC_PIN_COMPLETE = 101;
     private static final int MSG_SIM_STATE_CHANGED = 102;
 
     // @see android.widget.Toast$TN
     private static final long LONG_DURATION_TIMEOUT = 7000;
 
+    private int mSubId;
+    private TelephonyManager mTelephonyManager;
+
     // For replies from IccCard interface
     private Handler mHandler = new Handler() {
         public void handleMessage(Message msg) {
-            final AsyncResult ar = (AsyncResult) msg.obj;
             switch (msg.what) {
-                case MSG_ENABLE_ICC_PIN_COMPLETE:
-                    iccLockChanged(ar.exception == null, msg.arg1, ar.exception);
-                    break;
-                case MSG_CHANGE_ICC_PIN_COMPLETE:
-                    iccPinChanged(ar.exception == null, msg.arg1);
-                    break;
                 case MSG_SIM_STATE_CHANGED:
                     updatePreferences();
                     break;
@@ -158,11 +149,12 @@
     };
 
     // For top-level settings screen to query
-    static boolean isIccLockEnabled() {
-        return PhoneFactory.getDefaultPhone().getIccCard().getIccLockEnabled();
+    private boolean isIccLockEnabled() {
+        mTelephonyManager =  mTelephonyManager.createForSubscriptionId(mSubId);
+        return mTelephonyManager.isIccLockEnabled();
     }
 
-    static String getSummary(Context context) {
+    private String getSummary(Context context) {
         final Resources res = context.getResources();
         final String summary = isIccLockEnabled()
                 ? res.getString(R.string.sim_lock_on)
@@ -184,6 +176,8 @@
         mProxySubscriptionMgr = ProxySubscriptionManager.getInstance(getContext());
         mProxySubscriptionMgr.setLifecycle(getLifecycle());
 
+        mTelephonyManager = getContext().getSystemService(TelephonyManager.class);
+
         addPreferencesFromResource(R.xml.sim_lock_settings);
 
         mPinDialog = (EditPinPreference) findPreference(PIN_DIALOG);
@@ -251,15 +245,13 @@
                             : subInfo.getDisplayName())));
             }
             final SubscriptionInfo sir = getActiveSubscriptionInfoForSimSlotIndex(subInfoList, 0);
-
-            mPhone = (sir == null) ? null : PhoneFactory.getPhone(sir.getSimSlotIndex());
+            mSubId = sir.getSubscriptionId();
 
             if (savedInstanceState != null && savedInstanceState.containsKey(CURRENT_TAB)) {
                 mTabHost.setCurrentTabByTag(savedInstanceState.getString(CURRENT_TAB));
             }
             return view;
         } else {
-            mPhone = PhoneFactory.getDefaultPhone();
             return super.onCreateView(inflater, container, savedInstanceState);
         }
     }
@@ -271,14 +263,20 @@
     }
 
     private void updatePreferences() {
+
+        final List<SubscriptionInfo> subInfoList =
+                mProxySubscriptionMgr.getActiveSubscriptionsInfo();
+        final SubscriptionInfo sir = getActiveSubscriptionInfoForSimSlotIndex(subInfoList, 0);
+        mSubId = sir.getSubscriptionId();
+
         if (mPinDialog != null) {
-            mPinDialog.setEnabled(mPhone != null);
+            mPinDialog.setEnabled(sir != null);
         }
         if (mPinToggle != null) {
-            mPinToggle.setEnabled(mPhone != null);
+            mPinToggle.setEnabled(sir != null);
 
-            if (mPhone != null) {
-                mPinToggle.setChecked(mPhone.getIccCard().getIccLockEnabled());
+            if (sir != null) {
+                mPinToggle.setChecked(isIccLockEnabled());
             }
         }
     }
@@ -462,29 +460,52 @@
     private void tryChangeIccLockState() {
         // Try to change icc lock. If it succeeds, toggle the lock state and
         // reset dialog state. Else inject error message and show dialog again.
-        final Message callback = Message.obtain(mHandler, MSG_ENABLE_ICC_PIN_COMPLETE);
-        mPhone.getIccCard().setIccLockEnabled(mToState, mPin, callback);
+        new SetIccLockEnabled(mToState, mPin).execute();
         // Disable the setting till the response is received.
         mPinToggle.setEnabled(false);
     }
 
-    private void iccLockChanged(boolean success, int attemptsRemaining, Throwable exception) {
+    private class SetIccLockEnabled extends AsyncTask<Void, Void, Void> {
+        private final boolean mState;
+        private final String mPassword;
+        private int mAttemptsRemaining;
+
+        private SetIccLockEnabled(boolean state, String pin) {
+            mState = state;
+            mPassword = pin;
+        }
+
+        @Override
+        protected Void doInBackground(Void... params) {
+            mTelephonyManager =  mTelephonyManager.createForSubscriptionId(mSubId);
+            mAttemptsRemaining = mTelephonyManager.setIccLockEnabled(mState, mPassword);
+            return null;
+        }
+
+        @Override
+        protected void onPostExecute(Void aVoid) {
+            if (mAttemptsRemaining == TelephonyManager.CHANGE_ICC_LOCK_SUCCESS) {
+                iccLockChanged(true, mAttemptsRemaining);
+            } else {
+                iccLockChanged(false, mAttemptsRemaining);
+            }
+        }
+    }
+
+    private void iccLockChanged(boolean success, int attemptsRemaining) {
+        Log.d(TAG, "iccLockChanged: success = " + success);
         if (success) {
             mPinToggle.setChecked(mToState);
         } else {
-            if (exception instanceof CommandException) {
-                final CommandException.Error err =
-                        ((CommandException) exception).getCommandError();
-                if (err == CommandException.Error.PASSWORD_INCORRECT) {
-                    createCustomTextToast(getPinPasswordErrorMessage(attemptsRemaining));
+            if (attemptsRemaining >= 0) {
+                createCustomTextToast(getPinPasswordErrorMessage(attemptsRemaining));
+            } else {
+                if (mToState) {
+                    Toast.makeText(getContext(), mRes.getString(
+                            R.string.sim_pin_enable_failed), Toast.LENGTH_LONG).show();
                 } else {
-                    if (mToState) {
-                        Toast.makeText(getContext(), mRes.getString
-                               (R.string.sim_pin_enable_failed), Toast.LENGTH_LONG).show();
-                    } else {
-                        Toast.makeText(getContext(), mRes.getString
-                               (R.string.sim_pin_disable_failed), Toast.LENGTH_LONG).show();
-                    }
+                    Toast.makeText(getContext(), mRes.getString(
+                            R.string.sim_pin_disable_failed), Toast.LENGTH_LONG).show();
                 }
             }
         }
@@ -540,21 +561,46 @@
     }
 
     private void iccPinChanged(boolean success, int attemptsRemaining) {
+        Log.d(TAG, "iccPinChanged: success = " + success);
         if (!success) {
             createCustomTextToast(getPinPasswordErrorMessage(attemptsRemaining));
         } else {
             Toast.makeText(getContext(), mRes.getString(R.string.sim_change_succeeded),
                     Toast.LENGTH_SHORT)
                     .show();
-
         }
         resetDialogState();
     }
 
     private void tryChangePin() {
-        final Message callback = Message.obtain(mHandler, MSG_CHANGE_ICC_PIN_COMPLETE);
-        mPhone.getIccCard().changeIccLockPassword(mOldPin,
-                mNewPin, callback);
+        new ChangeIccLockPassword(mOldPin, mNewPin).execute();
+    }
+
+    private class ChangeIccLockPassword extends AsyncTask<Void, Void, Void> {
+        private final String mOldPwd;
+        private final String mNewPwd;
+        private int mAttemptsRemaining;
+
+        private ChangeIccLockPassword(String oldPin, String newPin) {
+            mOldPwd = oldPin;
+            mNewPwd = newPin;
+        }
+
+        @Override
+        protected Void doInBackground(Void... params) {
+            mTelephonyManager = mTelephonyManager.createForSubscriptionId(mSubId);
+            mAttemptsRemaining = mTelephonyManager.changeIccLockPassword(mOldPwd, mNewPwd);
+            return null;
+        }
+
+        @Override
+        protected void onPostExecute(Void aVoid) {
+            if (mAttemptsRemaining == TelephonyManager.CHANGE_ICC_LOCK_SUCCESS) {
+                iccPinChanged(true, mAttemptsRemaining);
+            } else {
+                iccPinChanged(false, mAttemptsRemaining);
+            }
+        }
     }
 
     private String getPinPasswordErrorMessage(int attemptsRemaining) {
@@ -610,8 +656,6 @@
             final SubscriptionInfo sir = getActiveSubscriptionInfoForSimSlotIndex(
                     mProxySubscriptionMgr.getActiveSubscriptionsInfo(), slotId);
 
-            mPhone = (sir == null) ? null : PhoneFactory.getPhone(sir.getSimSlotIndex());
-
             // The User has changed tab; update the body.
             updatePreferences();
         }
diff --git a/src/com/android/settings/applications/appinfo/AppDataUsagePreferenceController.java b/src/com/android/settings/applications/appinfo/AppDataUsagePreferenceController.java
index 4d19151..a3ea478 100644
--- a/src/com/android/settings/applications/appinfo/AppDataUsagePreferenceController.java
+++ b/src/com/android/settings/applications/appinfo/AppDataUsagePreferenceController.java
@@ -127,7 +127,7 @@
                 return mContext.getString(R.string.no_data_usage);
             }
             return mContext.getString(R.string.data_summary_format,
-                    Formatter.formatFileSize(mContext, totalBytes),
+                    Formatter.formatFileSize(mContext, totalBytes, Formatter.FLAG_IEC_UNITS),
                     DateUtils.formatDateTime(mContext, startTime,
                             DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH));
         }
diff --git a/src/com/android/settings/bluetooth/BluetoothDetailsProfilesController.java b/src/com/android/settings/bluetooth/BluetoothDetailsProfilesController.java
index 749a38f..aa12409 100644
--- a/src/com/android/settings/bluetooth/BluetoothDetailsProfilesController.java
+++ b/src/com/android/settings/bluetooth/BluetoothDetailsProfilesController.java
@@ -109,7 +109,7 @@
             profilePref.setChecked(profile.getConnectionStatus(device) ==
                     BluetoothProfile.STATE_CONNECTED);
         } else {
-            profilePref.setChecked(profile.isPreferred(device));
+            profilePref.setChecked(profile.isEnabled(device));
         }
 
         if (profile instanceof A2dpProfile) {
@@ -117,7 +117,7 @@
             SwitchPreference highQualityPref = (SwitchPreference) mProfilesContainer.findPreference(
                     HIGH_QUALITY_AUDIO_PREF_TAG);
             if (highQualityPref != null) {
-                if (a2dp.isPreferred(device) && a2dp.supportsHighQualityAudio(device)) {
+                if (a2dp.isEnabled(device) && a2dp.supportsHighQualityAudio(device)) {
                     highQualityPref.setVisible(true);
                     highQualityPref.setTitle(a2dp.getHighQualityAudioOptionLabel(device));
                     highQualityPref.setChecked(a2dp.isHighQualityAudioEnabled(device));
@@ -142,8 +142,7 @@
         if (profile instanceof MapProfile) {
             bluetoothDevice.setMessageAccessPermission(BluetoothDevice.ACCESS_ALLOWED);
         }
-        profile.setPreferred(bluetoothDevice, true);
-        mCachedDevice.connectProfile(profile);
+        profile.setEnabled(bluetoothDevice, true);
     }
 
     /**
@@ -151,8 +150,7 @@
      */
     private void disableProfile(LocalBluetoothProfile profile) {
         final BluetoothDevice bluetoothDevice = mCachedDevice.getDevice();
-        mCachedDevice.disconnect(profile);
-        profile.setPreferred(bluetoothDevice, false);
+        profile.setEnabled(bluetoothDevice, false);
         if (profile instanceof MapProfile) {
             bluetoothDevice.setMessageAccessPermission(BluetoothDevice.ACCESS_REJECTED);
         } else if (profile instanceof PbapServerProfile) {
diff --git a/src/com/android/settings/core/SettingsBaseActivity.java b/src/com/android/settings/core/SettingsBaseActivity.java
index 5ff81d5..6e37b16 100644
--- a/src/com/android/settings/core/SettingsBaseActivity.java
+++ b/src/com/android/settings/core/SettingsBaseActivity.java
@@ -17,6 +17,7 @@
 
 import android.annotation.LayoutRes;
 import android.annotation.Nullable;
+import android.app.ActivityManager;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
@@ -26,6 +27,7 @@
 import android.content.res.TypedArray;
 import android.os.AsyncTask;
 import android.os.Bundle;
+import android.text.TextUtils;
 import android.util.ArraySet;
 import android.util.Log;
 import android.view.LayoutInflater;
@@ -61,6 +63,10 @@
     @Override
     protected void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
+        if (isLockTaskModePinned() && !isSettingsRunOnTop()) {
+            Log.w(TAG, "Devices lock task mode pinned.");
+            finish();
+        }
         final long startTime = System.currentTimeMillis();
         getLifecycle().addObserver(new HideNonSystemOverlayMixin(this));
 
@@ -148,6 +154,20 @@
         }
     }
 
+    private boolean isLockTaskModePinned() {
+        final ActivityManager activityManager =
+            getApplicationContext().getSystemService(ActivityManager.class);
+        return activityManager.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_PINNED;
+    }
+
+    private boolean isSettingsRunOnTop() {
+        final ActivityManager activityManager =
+            getApplicationContext().getSystemService(ActivityManager.class);
+        final String taskPkgName = activityManager.getRunningTasks(1 /* maxNum */)
+            .get(0 /* index */).baseActivity.getPackageName();
+        return TextUtils.equals(getPackageName(), taskPkgName);
+    }
+
     /**
      * @return whether or not the enabled state actually changed.
      */
diff --git a/src/com/android/settings/deviceinfo/simstatus/SimStatusDialogController.java b/src/com/android/settings/deviceinfo/simstatus/SimStatusDialogController.java
index 26d8e2b..04112c4 100644
--- a/src/com/android/settings/deviceinfo/simstatus/SimStatusDialogController.java
+++ b/src/com/android/settings/deviceinfo/simstatus/SimStatusDialogController.java
@@ -16,22 +16,26 @@
 
 package com.android.settings.deviceinfo.simstatus;
 
-import android.Manifest;
+import android.annotation.Nullable;
 import android.content.BroadcastReceiver;
+import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
 import android.content.IntentFilter;
+import android.content.ServiceConnection;
 import android.content.res.Resources;
-import android.os.Bundle;
+import android.os.IBinder;
 import android.os.PersistableBundle;
-import android.os.UserHandle;
+import android.os.RemoteException;
 import android.telephony.Annotation;
 import android.telephony.CarrierConfigManager;
+import android.telephony.CellBroadcastIntents;
+import android.telephony.CellBroadcastService;
 import android.telephony.CellSignalStrength;
+import android.telephony.ICellBroadcastService;
 import android.telephony.PhoneStateListener;
 import android.telephony.ServiceState;
 import android.telephony.SignalStrength;
-import android.telephony.SmsCbMessage;
 import android.telephony.SubscriptionInfo;
 import android.telephony.SubscriptionManager;
 import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener;
@@ -39,6 +43,7 @@
 import android.telephony.UiccCardInfo;
 import android.telephony.euicc.EuiccManager;
 import android.text.TextUtils;
+import android.util.Log;
 
 import androidx.annotation.NonNull;
 import androidx.annotation.VisibleForTesting;
@@ -59,6 +64,8 @@
 
     private final static String TAG = "SimStatusDialogCtrl";
 
+    private static final String CELL_BROADCAST_SERVICE_PACKAGE = "com.android.cellbroadcastservice";
+
     @VisibleForTesting
     final static int NETWORK_PROVIDER_VALUE_ID = R.id.operator_name_value;
     @VisibleForTesting
@@ -94,12 +101,6 @@
     @VisibleForTesting
     final static int IMS_REGISTRATION_STATE_VALUE_ID = R.id.ims_reg_state_value;
 
-    private final static String CB_AREA_INFO_RECEIVED_ACTION =
-            "com.android.cellbroadcastreceiver.CB_AREA_INFO_RECEIVED";
-    private final static String GET_LATEST_CB_AREA_INFO_ACTION =
-            "com.android.cellbroadcastreceiver.GET_LATEST_CB_AREA_INFO";
-    private final static String CELL_BROADCAST_RECEIVER_APP = "com.android.cellbroadcastreceiver";
-
     private final OnSubscriptionsChangedListener mOnSubscriptionsChangedListener =
             new OnSubscriptionsChangedListener() {
                 @Override
@@ -129,23 +130,48 @@
     private final BroadcastReceiver mAreaInfoReceiver = new BroadcastReceiver() {
         @Override
         public void onReceive(Context context, Intent intent) {
-            final String action = intent.getAction();
-            if (TextUtils.equals(action, CB_AREA_INFO_RECEIVED_ACTION)) {
-                final Bundle extras = intent.getExtras();
-                if (extras == null) {
-                    return;
-                }
-                final SmsCbMessage cbMessage = (SmsCbMessage) extras.get("message");
-                if (cbMessage != null && mSlotIndex == cbMessage.getSlotIndex()) {
-                    final String latestAreaInfo = cbMessage.getMessageBody();
-                    mDialog.setText(OPERATOR_INFO_VALUE_ID, latestAreaInfo);
-                }
-            }
+            updateAreaInfoText();
         }
     };
 
     private PhoneStateListener mPhoneStateListener;
 
+    private CellBroadcastServiceConnection mCellBroadcastServiceConnection;
+
+    private class CellBroadcastServiceConnection implements ServiceConnection {
+        private IBinder mService;
+
+        @Nullable
+        public IBinder getService() {
+            return mService;
+        }
+
+        @Override
+        public void onServiceConnected(ComponentName className, IBinder service) {
+            Log.d(TAG, "connected to CellBroadcastService");
+            this.mService = service;
+            updateAreaInfoText();
+        }
+
+        @Override
+        public void onServiceDisconnected(ComponentName className) {
+            this.mService = null;
+            Log.d(TAG, "mICellBroadcastService has disconnected unexpectedly");
+        }
+
+        @Override
+        public void onBindingDied(ComponentName name) {
+            this.mService = null;
+            Log.d(TAG, "Binding died");
+        }
+
+        @Override
+        public void onNullBinding(ComponentName name) {
+            this.mService = null;
+            Log.d(TAG, "Null binding");
+        }
+    }
+
     public SimStatusDialogController(@NonNull SimStatusDialogFragment dialog, Lifecycle lifecycle,
             int slotId) {
         mDialog = dialog;
@@ -188,6 +214,19 @@
         updateImsRegistrationState();
     }
 
+    /**
+     * Deinitialization works
+     */
+    public void deinitialize() {
+        if (mShowLatestAreaInfo) {
+            if (mCellBroadcastServiceConnection != null
+                    && mCellBroadcastServiceConnection.getService() != null) {
+                mContext.unbindService(mCellBroadcastServiceConnection);
+            }
+            mCellBroadcastServiceConnection = null;
+        }
+    }
+
     @Override
     public void onResume() {
         if (mSubscriptionInfo == null) {
@@ -202,14 +241,9 @@
         mSubscriptionManager.addOnSubscriptionsChangedListener(mOnSubscriptionsChangedListener);
 
         if (mShowLatestAreaInfo) {
+            updateAreaInfoText();
             mContext.registerReceiver(mAreaInfoReceiver,
-                    new IntentFilter(CB_AREA_INFO_RECEIVED_ACTION),
-                    Manifest.permission.RECEIVE_EMERGENCY_BROADCAST, null /* scheduler */);
-            // Ask CellBroadcastReceiver to broadcast the latest area info received
-            final Intent getLatestIntent = new Intent(GET_LATEST_CB_AREA_INFO_ACTION);
-            getLatestIntent.setPackage(CELL_BROADCAST_RECEIVER_APP);
-            mContext.sendBroadcastAsUser(getLatestIntent, UserHandle.ALL,
-                    Manifest.permission.RECEIVE_EMERGENCY_BROADCAST);
+                    new IntentFilter(CellBroadcastIntents.ACTION_AREA_INFO_UPDATED));
         }
     }
 
@@ -263,13 +297,54 @@
         mDialog.setText(CELLULAR_NETWORK_STATE, networkStateValue);
     }
 
+    /**
+     * Update area info text retrieved from
+     * {@link CellBroadcastService#getCellBroadcastAreaInfo(int)}
+     */
+    private void updateAreaInfoText() {
+        if (!mShowLatestAreaInfo || mCellBroadcastServiceConnection == null) return;
+        ICellBroadcastService cellBroadcastService =
+                ICellBroadcastService.Stub.asInterface(
+                        mCellBroadcastServiceConnection.getService());
+        if (cellBroadcastService == null) return;
+        try {
+            mDialog.setText(OPERATOR_INFO_VALUE_ID,
+                    cellBroadcastService.getCellBroadcastAreaInfo(
+                            SimStatusDialogController.this.mSlotIndex));
+
+        } catch (RemoteException e) {
+            Log.d(TAG, "Can't get area info. e=" + e);
+        }
+    }
+
+    /**
+     * Bind cell broadcast service.
+     */
+    private void bindCellBroadcastService() {
+        mCellBroadcastServiceConnection = new CellBroadcastServiceConnection();
+        Intent intent = new Intent(CellBroadcastService.CELL_BROADCAST_SERVICE_INTERFACE);
+        intent.setPackage(CELL_BROADCAST_SERVICE_PACKAGE);
+        if (mCellBroadcastServiceConnection != null
+                && mCellBroadcastServiceConnection.getService() == null) {
+            if (!mContext.bindService(intent, mCellBroadcastServiceConnection,
+                    Context.BIND_AUTO_CREATE)) {
+                Log.e(TAG, "Unable to bind to service");
+            }
+        } else {
+            Log.d(TAG, "skipping bindService because connection already exists");
+        }
+    }
 
     private void updateLatestAreaInfo() {
         mShowLatestAreaInfo = Resources.getSystem().getBoolean(
                 com.android.internal.R.bool.config_showAreaUpdateInfoSettings)
                 && mTelephonyManager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA;
 
-        if (!mShowLatestAreaInfo) {
+        if (mShowLatestAreaInfo) {
+            // Bind cell broadcast service to get the area info. The info will be updated once
+            // the service is connected.
+            bindCellBroadcastService();
+        } else {
             mDialog.removeSettingFromScreen(OPERATOR_INFO_LABEL_ID);
             mDialog.removeSettingFromScreen(OPERATOR_INFO_VALUE_ID);
         }
diff --git a/src/com/android/settings/deviceinfo/simstatus/SimStatusDialogFragment.java b/src/com/android/settings/deviceinfo/simstatus/SimStatusDialogFragment.java
index d2d563f..93323b3 100644
--- a/src/com/android/settings/deviceinfo/simstatus/SimStatusDialogFragment.java
+++ b/src/com/android/settings/deviceinfo/simstatus/SimStatusDialogFragment.java
@@ -74,6 +74,12 @@
         return builder.setView(mRootView).create();
     }
 
+    @Override
+    public void onDestroy() {
+        mController.deinitialize();
+        super.onDestroy();
+    }
+
     public void removeSettingFromScreen(int viewId) {
         final View view = mRootView.findViewById(viewId);
         if (view != null) {
diff --git a/src/com/android/settings/network/telephony/MmsMessagePreferenceController.java b/src/com/android/settings/network/telephony/MmsMessagePreferenceController.java
index c1f2949..3503099 100644
--- a/src/com/android/settings/network/telephony/MmsMessagePreferenceController.java
+++ b/src/com/android/settings/network/telephony/MmsMessagePreferenceController.java
@@ -97,7 +97,7 @@
 
     @Override
     public boolean setChecked(boolean isChecked) {
-        return mSubscriptionManager.setAlwaysAllowMmsData(mSubId, isChecked);
+        return mTelephonyManager.setAlwaysAllowMmsData(isChecked);
     }
 
     @Override
diff --git a/src/com/android/settings/network/telephony/RenameMobileNetworkDialogFragment.java b/src/com/android/settings/network/telephony/RenameMobileNetworkDialogFragment.java
index 38db43e..fa5deab 100644
--- a/src/com/android/settings/network/telephony/RenameMobileNetworkDialogFragment.java
+++ b/src/com/android/settings/network/telephony/RenameMobileNetworkDialogFragment.java
@@ -39,15 +39,17 @@
 import android.widget.Spinner;
 import android.widget.TextView;
 
-import com.android.settings.R;
-import com.android.settings.core.instrumentation.InstrumentedDialogFragment;
-import com.android.settingslib.DeviceInfoUtils;
-
 import androidx.annotation.NonNull;
 import androidx.annotation.Nullable;
 import androidx.annotation.VisibleForTesting;
 import androidx.appcompat.app.AlertDialog;
 
+import com.android.settings.R;
+import com.android.settings.core.instrumentation.InstrumentedDialogFragment;
+import com.android.settingslib.DeviceInfoUtils;
+
+import java.util.List;
+
 /**
  * A dialog allowing the display name of a mobile network subscription to be changed
  */
@@ -115,9 +117,9 @@
                 .setPositiveButton(R.string.mobile_network_sim_name_rename, (dialog, which) -> {
                     mSubscriptionManager.setDisplayName(mNameView.getText().toString(), mSubId,
                             SubscriptionManager.NAME_SOURCE_USER_INPUT);
-                    mSubscriptionManager.setIconTint(
-                            mColors[mColorSpinner.getSelectedItemPosition()].getColor(),
-                            mSubId);
+                    final Color color = (mColorSpinner == null) ? mColors[0]
+                            : mColors[mColorSpinner.getSelectedItemPosition()];
+                    mSubscriptionManager.setIconTint(color.getColor(), mSubId);
                 })
                 .setNegativeButton(android.R.string.cancel, null);
         return builder.create();
@@ -126,7 +128,17 @@
     @VisibleForTesting
     protected void populateView(View view) {
         mNameView = view.findViewById(R.id.name_edittext);
-        final SubscriptionInfo info = mSubscriptionManager.getActiveSubscriptionInfo(mSubId);
+        SubscriptionInfo info = null;
+        final List<SubscriptionInfo> infoList = mSubscriptionManager
+                .getAvailableSubscriptionInfoList();
+        if (infoList != null) {
+            for (SubscriptionInfo subInfo : infoList) {
+                if (subInfo.getSubscriptionId() == mSubId) {
+                    info = subInfo;
+                    break;
+                }
+            }
+        }
         if (info == null) {
             Log.w(TAG, "got null SubscriptionInfo for mSubId:" + mSubId);
             return;
diff --git a/src/com/android/settings/security/SimLockPreferenceController.java b/src/com/android/settings/security/SimLockPreferenceController.java
index d4def6b..3b23daa 100644
--- a/src/com/android/settings/security/SimLockPreferenceController.java
+++ b/src/com/android/settings/security/SimLockPreferenceController.java
@@ -38,7 +38,7 @@
     private final CarrierConfigManager mCarrierConfigManager;
     private final UserManager mUserManager;
     private final SubscriptionManager mSubscriptionManager;
-    private final TelephonyManager mTelephonyManager;
+    private TelephonyManager mTelephonyManager;
 
     public SimLockPreferenceController(Context context) {
         super(context, KEY_SIM_LOCK);
@@ -99,7 +99,9 @@
 
         if (subInfoList != null) {
             for (SubscriptionInfo subInfo : subInfoList) {
-                if (mTelephonyManager.hasIccCard(subInfo.getSimSlotIndex())) {
+                mTelephonyManager = mTelephonyManager
+                        .createForSubscriptionId(subInfo.getSimSlotIndex());
+                if (mTelephonyManager.hasIccCard()) {
                     return true;
                 }
             }
diff --git a/src/com/android/settings/vpn2/AppDialogFragment.java b/src/com/android/settings/vpn2/AppDialogFragment.java
index 2f9cd7a..ea9e546 100644
--- a/src/com/android/settings/vpn2/AppDialogFragment.java
+++ b/src/com/android/settings/vpn2/AppDialogFragment.java
@@ -22,6 +22,7 @@
 import android.content.DialogInterface;
 import android.content.pm.PackageInfo;
 import android.net.IConnectivityManager;
+import android.net.VpnManager;
 import android.os.Bundle;
 import android.os.RemoteException;
 import android.os.ServiceManager;
@@ -145,7 +146,8 @@
         }
         final int userId = getUserId();
         try {
-            mService.setVpnPackageAuthorization(mPackageInfo.packageName, userId, false);
+            mService.setVpnPackageAuthorization(
+                    mPackageInfo.packageName, userId, VpnManager.TYPE_VPN_NONE);
             onDisconnect(dialog);
         } catch (RemoteException e) {
             Log.e(TAG, "Failed to forget authorization of " + mPackageInfo.packageName +
diff --git a/src/com/android/settings/vpn2/AppManagementFragment.java b/src/com/android/settings/vpn2/AppManagementFragment.java
index 5f46446..8e3d9bb 100644
--- a/src/com/android/settings/vpn2/AppManagementFragment.java
+++ b/src/com/android/settings/vpn2/AppManagementFragment.java
@@ -15,6 +15,7 @@
  */
 package com.android.settings.vpn2;
 
+import static android.app.AppOpsManager.OP_ACTIVATE_PLATFORM_VPN;
 import static android.app.AppOpsManager.OP_ACTIVATE_VPN;
 
 import android.annotation.NonNull;
@@ -312,7 +313,7 @@
         final AppOpsManager service =
                 (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
         final List<AppOpsManager.PackageOps> ops = service.getOpsForPackage(application.uid,
-                application.packageName, new int[]{OP_ACTIVATE_VPN});
+                application.packageName, new int[]{OP_ACTIVATE_VPN, OP_ACTIVATE_PLATFORM_VPN});
         return !ArrayUtils.isEmpty(ops);
     }
 
diff --git a/src/com/android/settings/vpn2/VpnSettings.java b/src/com/android/settings/vpn2/VpnSettings.java
index 83cdf71..8a2b465 100644
--- a/src/com/android/settings/vpn2/VpnSettings.java
+++ b/src/com/android/settings/vpn2/VpnSettings.java
@@ -16,6 +16,7 @@
 
 package com.android.settings.vpn2;
 
+import static android.app.AppOpsManager.OP_ACTIVATE_PLATFORM_VPN;
 import static android.app.AppOpsManager.OP_ACTIVATE_VPN;
 
 import android.annotation.UiThread;
@@ -522,7 +523,8 @@
 
         // Fetch VPN-enabled apps from AppOps.
         AppOpsManager aom = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
-        List<AppOpsManager.PackageOps> apps = aom.getPackagesForOps(new int[] {OP_ACTIVATE_VPN});
+        List<AppOpsManager.PackageOps> apps =
+                aom.getPackagesForOps(new int[] {OP_ACTIVATE_VPN, OP_ACTIVATE_PLATFORM_VPN});
         if (apps != null) {
             for (AppOpsManager.PackageOps pkg : apps) {
                 int userId = UserHandle.getUserId(pkg.getUid());
@@ -533,8 +535,8 @@
                 // Look for a MODE_ALLOWED permission to activate VPN.
                 boolean allowed = false;
                 for (AppOpsManager.OpEntry op : pkg.getOps()) {
-                    if (op.getOp() == OP_ACTIVATE_VPN &&
-                            op.getMode() == AppOpsManager.MODE_ALLOWED) {
+                    if ((op.getOp() == OP_ACTIVATE_VPN || op.getOp() == OP_ACTIVATE_PLATFORM_VPN)
+                            && op.getMode() == AppOpsManager.MODE_ALLOWED) {
                         allowed = true;
                     }
                 }
diff --git a/tests/perftests/Android.bp b/tests/perftests/Android.bp
new file mode 100644
index 0000000..1ba5d9c
--- /dev/null
+++ b/tests/perftests/Android.bp
@@ -0,0 +1,22 @@
+android_test {
+    name: "SettingsPerfTests",
+
+    certificate: "platform",
+
+    libs: [
+        "android.test.runner",
+    ],
+
+    static_libs: [
+        "androidx.test.rules",
+        "ub-uiautomator",
+    ],
+
+    // Include all test java files.
+    srcs: ["src/**/*.java"],
+
+    platform_apis: true,
+    test_suites: ["device-tests"],
+
+    instrumentation_for: "Settings",
+}
diff --git a/tests/perftests/AndroidManifest.xml b/tests/perftests/AndroidManifest.xml
new file mode 100644
index 0000000..4ce6a54
--- /dev/null
+++ b/tests/perftests/AndroidManifest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2020 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.settings.tests.perf">
+
+    <application>
+        <uses-library android:name="android.test.runner" />
+    </application>
+
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
+        android:targetPackage="com.android.settings"
+        android:label="Settings Performance Test Cases">
+    </instrumentation>
+
+</manifest>
diff --git a/tests/perftests/src/com/android/settings/tests/perf/LaunchSettingsTest.java b/tests/perftests/src/com/android/settings/tests/perf/LaunchSettingsTest.java
new file mode 100644
index 0000000..5140be2
--- /dev/null
+++ b/tests/perftests/src/com/android/settings/tests/perf/LaunchSettingsTest.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.settings.tests.perf;
+
+import android.app.Instrumentation;
+import android.os.Bundle;
+
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class LaunchSettingsTest {
+
+    @Before
+    public void setUp() throws Exception {
+    }
+
+    @After
+    public void tearDown() throws Exception {
+    }
+
+    @Test
+    public void testReportMetrics() throws Exception {
+        Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
+        final Bundle result = new Bundle();
+        result.putString("LaunchSettingsTest_metric_key1", "1000");
+        result.putString("LaunchSettingsTest_metric_key2", "5000");
+        instrumentation.sendStatus(0, result);
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/bluetooth/BluetoothDetailsProfilesControllerTest.java b/tests/robotests/src/com/android/settings/bluetooth/BluetoothDetailsProfilesControllerTest.java
index 9637884..5fc45a6 100644
--- a/tests/robotests/src/com/android/settings/bluetooth/BluetoothDetailsProfilesControllerTest.java
+++ b/tests/robotests/src/com/android/settings/bluetooth/BluetoothDetailsProfilesControllerTest.java
@@ -115,18 +115,6 @@
         }
 
         @Override
-        public boolean connect(BluetoothDevice device) {
-            mConnectedDevices.add(device);
-            return true;
-        }
-
-        @Override
-        public boolean disconnect(BluetoothDevice device) {
-            mConnectedDevices.remove(device);
-            return false;
-        }
-
-        @Override
         public int getConnectionStatus(BluetoothDevice device) {
             if (mConnectedDevices.contains(device)) {
                 return BluetoothProfile.STATE_CONNECTED;
@@ -136,20 +124,21 @@
         }
 
         @Override
-        public boolean isPreferred(BluetoothDevice device) {
+        public boolean isEnabled(BluetoothDevice device) {
             return mPreferred.getOrDefault(device, false);
         }
 
         @Override
-        public int getPreferred(BluetoothDevice device) {
-            return isPreferred(device) ?
-                    BluetoothProfile.CONNECTION_POLICY_ALLOWED
+        public int getConnectionPolicy(BluetoothDevice device) {
+            return isEnabled(device)
+                    ? BluetoothProfile.CONNECTION_POLICY_ALLOWED
                     : BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
         }
 
         @Override
-        public void setPreferred(BluetoothDevice device, boolean preferred) {
-            mPreferred.put(device, preferred);
+        public boolean setEnabled(BluetoothDevice device, boolean enabled) {
+            mPreferred.put(device, enabled);
+            return true;
         }
 
         @Override
@@ -192,7 +181,7 @@
     private LocalBluetoothProfile addFakeProfile(int profileNameResId,
             boolean deviceIsPreferred) {
         LocalBluetoothProfile profile = new FakeBluetoothProfile(mContext, profileNameResId);
-        profile.setPreferred(mDevice, deviceIsPreferred);
+        profile.setEnabled(mDevice, deviceIsPreferred);
         mConnectableProfiles.add(profile);
         when(mProfileManager.getProfileByName(eq(profile.toString()))).thenReturn(profile);
         return profile;
@@ -266,7 +255,7 @@
         assertThat(pref.isChecked()).isTrue();
         pref.performClick();
         assertThat(pref.isChecked()).isFalse();
-        assertThat(mConnectableProfiles.get(0).isPreferred(mDevice)).isFalse();
+        assertThat(mConnectableProfiles.get(0).isEnabled(mDevice)).isFalse();
 
         // Make sure no new preferences were added.
         assertThat(mProfiles.getPreferenceCount()).isEqualTo(2);
@@ -274,7 +263,7 @@
         // Clicking the pref again should make the profile once again preferred.
         pref.performClick();
         assertThat(pref.isChecked()).isTrue();
-        assertThat(mConnectableProfiles.get(0).isPreferred(mDevice)).isTrue();
+        assertThat(mConnectableProfiles.get(0).isEnabled(mDevice)).isTrue();
 
         // Make sure we still haven't gotten any new preferences added.
         assertThat(mProfiles.getPreferenceCount()).isEqualTo(2);
@@ -364,7 +353,7 @@
             mContext.getString(R.string.bluetooth_profile_a2dp_high_quality_unknown_codec));
         when(profile.supportsHighQualityAudio(mDevice)).thenReturn(supportsHighQualityAudio);
         when(profile.isHighQualityAudioEnabled(mDevice)).thenReturn(highQualityAudioEnabled);
-        when(profile.isPreferred(mDevice)).thenReturn(preferred);
+        when(profile.isEnabled(mDevice)).thenReturn(preferred);
         when(profile.isProfileReady()).thenReturn(true);
         mConnectableProfiles.add(profile);
         return profile;
@@ -426,8 +415,8 @@
         SwitchPreference audioPref =
             (SwitchPreference) mScreen.findPreference(audioProfile.toString());
         audioPref.performClick();
-        verify(audioProfile).setPreferred(mDevice, false);
-        when(audioProfile.isPreferred(mDevice)).thenReturn(false);
+        verify(audioProfile).setEnabled(mDevice, false);
+        when(audioProfile.isEnabled(mDevice)).thenReturn(false);
         mController.onDeviceAttributesChanged();
         assertThat(audioPref.isVisible()).isTrue();
         SwitchPreference highQualityAudioPref = getHighQualityAudioPref();
@@ -435,8 +424,8 @@
 
         // And re-enabling media audio should make high quality switch to reappear.
         audioPref.performClick();
-        verify(audioProfile).setPreferred(mDevice, true);
-        when(audioProfile.isPreferred(mDevice)).thenReturn(true);
+        verify(audioProfile).setEnabled(mDevice, true);
+        when(audioProfile.isEnabled(mDevice)).thenReturn(true);
         mController.onDeviceAttributesChanged();
         highQualityAudioPref = getHighQualityAudioPref();
         assertThat(highQualityAudioPref.isVisible()).isTrue();
diff --git a/tests/robotests/src/com/android/settings/homepage/contextualcards/conditional/ConditionContextualCardControllerTest.java b/tests/robotests/src/com/android/settings/homepage/contextualcards/conditional/ConditionContextualCardControllerTest.java
index 06f9b98..ad2930d 100644
--- a/tests/robotests/src/com/android/settings/homepage/contextualcards/conditional/ConditionContextualCardControllerTest.java
+++ b/tests/robotests/src/com/android/settings/homepage/contextualcards/conditional/ConditionContextualCardControllerTest.java
@@ -23,8 +23,11 @@
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
+import static org.robolectric.Shadows.shadowOf;
 
 import android.content.Context;
+import android.telephony.SubscriptionManager;
+import android.telephony.TelephonyManager;
 
 import com.android.settings.homepage.contextualcards.ContextualCard;
 import com.android.settings.homepage.contextualcards.ContextualCard.CardType;
@@ -37,6 +40,8 @@
 import org.mockito.MockitoAnnotations;
 import org.robolectric.RobolectricTestRunner;
 import org.robolectric.RuntimeEnvironment;
+import org.robolectric.shadows.ShadowSubscriptionManager;
+import org.robolectric.shadows.ShadowTelephonyManager;
 import org.robolectric.util.ReflectionHelpers;
 
 import java.util.ArrayList;
@@ -45,6 +50,7 @@
 
 @RunWith(RobolectricTestRunner.class)
 public class ConditionContextualCardControllerTest {
+    private static final int SUB_ID = 2;
 
     @Mock
     private ConditionManager mConditionManager;
@@ -57,6 +63,17 @@
     public void setUp() {
         MockitoAnnotations.initMocks(this);
         mContext = spy(RuntimeEnvironment.application);
+
+        // parameters required by CellularDataConditionController
+        final ShadowSubscriptionManager shadowSubscriptionMgr = shadowOf(
+                mContext.getSystemService(SubscriptionManager.class));
+        shadowSubscriptionMgr.setDefaultDataSubscriptionId(SUB_ID);
+
+        final TelephonyManager telephonyManager =
+                spy(mContext.getSystemService(TelephonyManager.class));
+        final ShadowTelephonyManager shadowTelephonyMgr = shadowOf(telephonyManager);
+        shadowTelephonyMgr.setTelephonyManagerForSubscriptionId(SUB_ID, telephonyManager);
+
         mController = spy(new ConditionContextualCardController(mContext));
         ReflectionHelpers.setField(mController, "mConditionManager", mConditionManager);
     }
diff --git a/tests/robotests/src/com/android/settings/network/telephony/MmsMessagePreferenceControllerTest.java b/tests/robotests/src/com/android/settings/network/telephony/MmsMessagePreferenceControllerTest.java
index 0263fe9..a612657 100644
--- a/tests/robotests/src/com/android/settings/network/telephony/MmsMessagePreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/network/telephony/MmsMessagePreferenceControllerTest.java
@@ -115,9 +115,9 @@
     @Test
     public void setChecked_setDataIntoSubscriptionManager() {
         mController.setChecked(true);
-        verify(mSubscriptionManager).setAlwaysAllowMmsData(SUB_ID, true);
+        verify(mTelephonyManager).setAlwaysAllowMmsData(true);
 
         mController.setChecked(false);
-        verify(mSubscriptionManager).setAlwaysAllowMmsData(SUB_ID, false);
+        verify(mTelephonyManager).setAlwaysAllowMmsData(false);
     }
 }
diff --git a/tests/robotests/src/com/android/settings/network/telephony/RenameMobileNetworkDialogFragmentTest.java b/tests/robotests/src/com/android/settings/network/telephony/RenameMobileNetworkDialogFragmentTest.java
index 0d94928..b406986 100644
--- a/tests/robotests/src/com/android/settings/network/telephony/RenameMobileNetworkDialogFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/network/telephony/RenameMobileNetworkDialogFragmentTest.java
@@ -23,12 +23,12 @@
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import android.content.Context;
 import android.content.DialogInterface;
 import android.graphics.Color;
 import android.telephony.ServiceState;
@@ -55,7 +55,13 @@
 import org.mockito.MockitoAnnotations;
 import org.robolectric.Robolectric;
 import org.robolectric.RobolectricTestRunner;
+import org.robolectric.RuntimeEnvironment;
 import org.robolectric.annotation.Config;
+import org.robolectric.shadow.api.Shadow;
+import org.robolectric.shadows.ShadowTelephonyManager;
+
+import java.util.ArrayList;
+import java.util.List;
 
 @RunWith(RobolectricTestRunner.class)
 @Config(shadows = ShadowAlertDialogCompat.class)
@@ -64,6 +70,8 @@
     @Mock
     private TelephonyManager mTelephonyMgr;
     @Mock
+    private ServiceState mServiceState;
+    @Mock
     private SubscriptionManager mSubscriptionMgr;
     @Mock
     private SubscriptionInfo mSubscriptionInfo;
@@ -71,23 +79,35 @@
     private FragmentActivity mActivity;
     private RenameMobileNetworkDialogFragment mFragment;
     private int mSubscriptionId = 1234;
+    private List<SubscriptionInfo> mSubscriptionInfoList;
 
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
-        mActivity = spy(Robolectric.buildActivity(FragmentActivity.class).setup().get());
+
+        Context context = spy(RuntimeEnvironment.application);
+
+        final ShadowTelephonyManager stm = Shadow.extract(context.getSystemService(
+                TelephonyManager.class));
+        stm.setTelephonyManagerForSubscriptionId(mSubscriptionId, mTelephonyMgr);
+        when(mTelephonyMgr.createForSubscriptionId(anyInt())).thenReturn(mTelephonyMgr);
+
+        when(mTelephonyMgr.getServiceState()).thenReturn(mServiceState);
+        when(mServiceState.getOperatorAlphaLong()).thenReturn("fake carrier name");
 
         when(mSubscriptionInfo.getSubscriptionId()).thenReturn(mSubscriptionId);
         when(mSubscriptionInfo.getDisplayName()).thenReturn("test");
+        when(mSubscriptionMgr.setDisplayName(any(), anyInt(), anyInt())).thenReturn(0);
+
+        mActivity = spy(Robolectric.buildActivity(FragmentActivity.class).setup().get());
 
         mFragment = spy(RenameMobileNetworkDialogFragment.newInstance(mSubscriptionId));
-        doReturn(mTelephonyMgr).when(mFragment).getTelephonyManager(any());
         doReturn(mSubscriptionMgr).when(mFragment).getSubscriptionManager(any());
 
-        final ServiceState serviceState = mock(ServiceState.class);
-        when(serviceState.getOperatorAlphaLong()).thenReturn("fake carrier name");
-        when(mTelephonyMgr.createForSubscriptionId(anyInt())).thenReturn(mTelephonyMgr);
-        when(mTelephonyMgr.getServiceState()).thenReturn(serviceState);
+        mSubscriptionInfoList = new ArrayList<SubscriptionInfo>();
+        mSubscriptionInfoList.add(mSubscriptionInfo);
+        when(mSubscriptionMgr.getAvailableSubscriptionInfoList()).thenReturn(
+                mSubscriptionInfoList);
     }
 
     @Test
@@ -100,8 +120,6 @@
 
     @Test
     public void dialog_cancelButtonClicked_setDisplayNameAndIconTintNotCalled() {
-        when(mSubscriptionMgr.getActiveSubscriptionInfo(mSubscriptionId)).thenReturn(
-                mSubscriptionInfo);
         final AlertDialog dialog = startDialog();
         final EditText nameView = mFragment.getNameView();
         nameView.setText("test2");
@@ -115,9 +133,6 @@
 
     @Test
     public void dialog_saveButtonClicked_setDisplayNameAndIconTint() {
-        when(mSubscriptionMgr.getActiveSubscriptionInfo(mSubscriptionId)).thenReturn(
-                mSubscriptionInfo);
-
         final AlertDialog dialog = startDialog();
         final EditText nameView = mFragment.getNameView();
         nameView.setText("test2");
@@ -140,8 +155,6 @@
     public void populateView_infoIsOpportunistic_hideNumberLabel() {
         final View view = LayoutInflater.from(mActivity).inflate(
                 R.layout.dialog_mobile_network_rename, null);
-        when(mSubscriptionMgr.getActiveSubscriptionInfo(mSubscriptionId)).thenReturn(
-                mSubscriptionInfo);
         when(mSubscriptionInfo.isOpportunistic()).thenReturn(true);
 
         startDialog();
diff --git a/tests/robotests/src/com/android/settings/security/SimLockPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/security/SimLockPreferenceControllerTest.java
index 0ae33a0..ebafceb 100644
--- a/tests/robotests/src/com/android/settings/security/SimLockPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/security/SimLockPreferenceControllerTest.java
@@ -141,7 +141,8 @@
         final List<SubscriptionInfo> subscriptionInfoList = new ArrayList<>();
         SubscriptionInfo info = mock(SubscriptionInfo.class);
         subscriptionInfoList.add(info);
-        when(mTelephonyManager.hasIccCard(anyInt())).thenReturn(true);
+        when(mTelephonyManager.createForSubscriptionId(anyInt())).thenReturn(mTelephonyManager);
+        when(mTelephonyManager.hasIccCard()).thenReturn(true);
         when(mSubscriptionManager.getActiveSubscriptionInfoList(eq(true)))
                 .thenReturn(subscriptionInfoList);
     }