Merge "Remove RadioBand Activity" into main
diff --git a/res/values-bs/strings.xml b/res/values-bs/strings.xml
index 6675ae7..992f1b2 100644
--- a/res/values-bs/strings.xml
+++ b/res/values-bs/strings.xml
@@ -596,7 +596,7 @@
     <string name="failedToImportSingleContactMsg" msgid="228095510489830266">"Uvoz kontakta nije uspio"</string>
     <string name="hac_mode_title" msgid="4127986689621125468">"Slušni aparat"</string>
     <string name="hac_mode_summary" msgid="7774989500136009881">"Uključite kompatibilnost za slušni aparat"</string>
-    <string name="rtt_mode_title" msgid="3075948111362818043">"Pozivanje sa slanjem SMS-ova u stvarnom vremenu (RTT)"</string>
+    <string name="rtt_mode_title" msgid="3075948111362818043">"Poziv sa SMS-ovima u stvarnom vremenu (RTT)"</string>
     <string name="rtt_mode_summary" msgid="8631541375609989562">"Dozvolite razmjenu poruka tokom glasovnog poziva"</string>
     <string name="rtt_mode_more_information" msgid="587500128658756318">"RTT pomaže pozivaocima koji su gluhi, imaju probleme sa sluhom ili govorom te onima kojima treba više od samog glasa.&lt;br&gt; &lt;a href=<xliff:g id="URL">http://support.google.com/mobile?p=telephony_rtt</xliff:g>&gt;Saznajte više&lt;/a&gt;\n       &lt;br&gt;&lt;br&gt; - RTT pozivi se pohranjuju kao transkripti poruka\n       &lt;br&gt; - RTT nije dostupan za video pozive"</string>
     <string name="no_rtt_when_roaming" msgid="5268008247378355389">"Napomena: RTT nije dostupan u romingu"</string>
diff --git a/res/values-da/strings.xml b/res/values-da/strings.xml
index a9dd327..58f2670 100644
--- a/res/values-da/strings.xml
+++ b/res/values-da/strings.xml
@@ -596,9 +596,9 @@
     <string name="failedToImportSingleContactMsg" msgid="228095510489830266">"Kontaktpersonen kunne ikke importeres"</string>
     <string name="hac_mode_title" msgid="4127986689621125468">"Høreapparater"</string>
     <string name="hac_mode_summary" msgid="7774989500136009881">"Slå høreapparatskompatibilitet til"</string>
-    <string name="rtt_mode_title" msgid="3075948111362818043">"Opkald via sms i realtid"</string>
+    <string name="rtt_mode_title" msgid="3075948111362818043">"Opkald via beskeder i realtid"</string>
     <string name="rtt_mode_summary" msgid="8631541375609989562">"Tillad afsendelse af sms-beskeder i et taleopkald"</string>
-    <string name="rtt_mode_more_information" msgid="587500128658756318">"Sms i realtid hjælper personer, som er døve, hørehæmmede, talehandicappede, eller som har brug for mere end bare tale, med at foretage opkald.&lt;br&gt; &lt;a href=<xliff:g id="URL">http://support.google.com/mobile?p=telephony_rtt</xliff:g>&gt;Få flere oplysninger&lt;/a&gt;\n       &lt;br&gt;&lt;br&gt; – Opkald via sms i realtid gemmes som en beskedtransskription\n       &lt;br&gt; – Sms i realtid er ikke tilgængeligt til videoopkald"</string>
+    <string name="rtt_mode_more_information" msgid="587500128658756318">"Beskeder i realtid hjælper personer, som er døve, hørehæmmede, talehandicappede, eller som har brug for mere end bare tale, med at foretage opkald.&lt;br&gt; &lt;a href=<xliff:g id="URL">http://support.google.com/mobile?p=telephony_rtt</xliff:g>&gt;Få flere oplysninger&lt;/a&gt;\n       &lt;br&gt;&lt;br&gt; – Opkald via beskeder i realtid gemmes som en beskedtransskription\n       &lt;br&gt; – Beskeder i realtid er ikke tilgængeligt til videoopkald"</string>
     <string name="no_rtt_when_roaming" msgid="5268008247378355389">"Bemærk! RTT er ikke tilgængeligt under roaming"</string>
   <string-array name="tty_mode_entries">
     <item msgid="3238070884803849303">"TTY fra"</item>
diff --git a/res/values-hi/strings.xml b/res/values-hi/strings.xml
index 5d03fe8..4f8e559 100644
--- a/res/values-hi/strings.xml
+++ b/res/values-hi/strings.xml
@@ -314,7 +314,7 @@
     <string name="video_calling_settings_title" msgid="342829454913266078">"वाहक वीडियो कॉलिंग"</string>
     <string name="gsm_umts_options" msgid="4968446771519376808">"GSM/UMTS विकल्प"</string>
     <string name="cdma_options" msgid="3669592472226145665">"CDMA विकल्प"</string>
-    <string name="throttle_data_usage" msgid="1944145350660420711">"डेटा उपयोग"</string>
+    <string name="throttle_data_usage" msgid="1944145350660420711">"डेटा खर्च"</string>
     <string name="throttle_current_usage" msgid="7483859109708658613">"वर्तमान अवधि में उपयोग किया गया डेटा"</string>
     <string name="throttle_time_frame" msgid="1813452485948918791">"डेटा उपयोग अवधि"</string>
     <string name="throttle_rate" msgid="7641913901133634905">"डेटा दर नीति"</string>
diff --git a/res/values-lv/strings.xml b/res/values-lv/strings.xml
index f8bef4a..90165b8 100644
--- a/res/values-lv/strings.xml
+++ b/res/values-lv/strings.xml
@@ -908,7 +908,7 @@
     <string name="radio_info_smsc_update_label" msgid="5141996256097115753">"Atjaunināt"</string>
     <string name="radio_info_smsc_refresh_label" msgid="8409923721451604560">"Atsvaidzināt"</string>
     <string name="radio_info_toggle_dns_check_label" msgid="1394078554927787350">"Pārslēgt DNS pārbaudi"</string>
-    <string name="oem_radio_info_label" msgid="2914167475119997456">"OEM raksturīga informācija/iestatījumi"</string>
+    <string name="oem_radio_info_label" msgid="2914167475119997456">"OAR raksturīga informācija/iestatījumi"</string>
     <string name="radio_info_endc_available" msgid="2983767110681230019">"EN-DC pieejamība (NSA):"</string>
     <string name="radio_info_dcnr_restricted" msgid="7147511536420148173">"DCNR ierobežojums (NSA):"</string>
     <string name="radio_info_nr_available" msgid="3383388088451237182">"NR pieejamība (NSA):"</string>
diff --git a/res/values/config.xml b/res/values/config.xml
index 939faa7..dcfa364 100644
--- a/res/values/config.xml
+++ b/res/values/config.xml
@@ -318,6 +318,13 @@
     <string-array name="thermal_mitigation_allowlisted_packages" translatable="false">
     </string-array>
 
+    <!-- Array of carriers that don't care about NGRAN's preference in the preferred emergency
+         network scan list after SIM is removed. -->
+    <integer-array name="config_carriers_ignore_ngran_preference_when_sim_removed">
+        <!-- 001-01 Test SIM -->
+        <item>1911</item>
+    </integer-array>
+
     <!-- Array of countries that active SIM is needed for emergency calls. Values should be
          ISO3166 country codes in lowercase. -->
     <string-array name="config_countries_require_sim_for_emergency" translatable="false">
diff --git a/src/com/android/phone/PhoneGlobals.java b/src/com/android/phone/PhoneGlobals.java
index 483a706..0cb95c5 100644
--- a/src/com/android/phone/PhoneGlobals.java
+++ b/src/com/android/phone/PhoneGlobals.java
@@ -50,6 +50,7 @@
 import android.telephony.TelephonyCallback;
 import android.telephony.TelephonyLocalConnection;
 import android.telephony.TelephonyManager;
+import android.text.TextUtils;
 import android.util.ArraySet;
 import android.util.LocalLog;
 import android.util.Log;
@@ -1061,16 +1062,14 @@
                     && reason == ROAMING_NOTIFICATION_REASON_CARRIER_CONFIG_CHANGED) {
                 mShownNotificationReasons.add(callingReason);
             }
-            boolean isShowRoamingNotificationEnabled = getCarrierConfigForSubId(mDefaultDataSubId)
-                    .getBoolean(CarrierConfigManager
-                            .KEY_SHOW_DATA_CONNECTED_ROAMING_NOTIFICATION_BOOL);
+            boolean shouldShowRoamingNotification = shouldShowRoamingNotification(roamingNumeric);
             // No need to show it again if we never cancelled it explicitly.
             if (getCurrentRoamingNotification() == ROAMING_NOTIFICATION_CONNECTED) {
                 return;
             }
 
             // Inform users that roaming charges may apply.
-            if (!shownInThisNumeric && !shownForThisReason && isShowRoamingNotificationEnabled) {
+            if (!shownInThisNumeric && !shownForThisReason && shouldShowRoamingNotification) {
                 updateDataRoamingNotification(ROAMING_NOTIFICATION_CONNECTED);
             } else {
                 // Don't show roaming notification if we've already shown for this MccMnc or
@@ -1078,7 +1077,7 @@
                 Log.d(LOG_TAG, "Skip roaming connected notification since already"
                         + " shownInThisNumeric:" + shownInThisNumeric
                         + " shownForThisReason:" + shownForThisReason
-                        + " isShowRoamingNotificationEnabled:" + isShowRoamingNotificationEnabled);
+                        + " shouldShowRoamingNotification:" + shouldShowRoamingNotification);
                 // Dismiss notification if the other notification is shown.
                 if (getCurrentRoamingNotification() != ROAMING_NOTIFICATION_NO_NOTIFICATION) {
                     updateDataRoamingNotification(ROAMING_NOTIFICATION_NO_NOTIFICATION);
@@ -1173,10 +1172,10 @@
             msg.arg1 = mDefaultDataSubId;
             msg.sendToTarget();
         } else if (dataAllowed && dataIsNowRoaming(mDefaultDataSubId)) {
-            boolean isShowRoamingNotificationEnabled = getCarrierConfigForSubId(mDefaultDataSubId)
-                    .getBoolean(CarrierConfigManager
-                            .KEY_SHOW_DATA_CONNECTED_ROAMING_NOTIFICATION_BOOL);
-            if (!isShowRoamingNotificationEnabled) return;
+            if (!shouldShowRoamingNotification(roamingOperatorNumeric)) {
+                Log.d(LOG_TAG, "Skip showing roaming connected notification.");
+                return;
+            }
             // Don't show roaming notification if we've already shown for this MccMnc
             if (roamingOperatorNumeric != null
                     && !mPrevRoamingOperatorNumerics.add(roamingOperatorNumeric)) {
@@ -1213,6 +1212,46 @@
         return getPhone(subId).getServiceState().getDataRoaming();
     }
 
+    private boolean shouldShowRoamingNotification(String roamingNumeric) {
+        PersistableBundle config = getCarrierConfigForSubId(mDefaultDataSubId);
+        boolean showRoamingNotification = config.getBoolean(
+                CarrierConfigManager.KEY_SHOW_DATA_CONNECTED_ROAMING_NOTIFICATION_BOOL);
+
+        if (TextUtils.isEmpty(roamingNumeric) || !mFeatureFlags.hideRoamingIcon()) {
+            Log.d(LOG_TAG, "shouldShowRoamingNotification: roamingNumeric=" + roamingNumeric
+                    + ", hideRoaming=" + mFeatureFlags.hideRoamingIcon());
+            return showRoamingNotification;
+        }
+
+        String[] includedMccMncs = config.getStringArray(CarrierConfigManager
+                .KEY_DATA_CONNECTED_ROAMING_NOTIFICATION_INCLUDED_MCC_MNCS_STRING_ARRAY);
+        if (includedMccMncs != null) {
+            for (String mccMnc : includedMccMncs) {
+                if (roamingNumeric.equals(mccMnc)) {
+                    Log.d(LOG_TAG, "shouldShowRoamingNotification: show for MCC/MNC " + mccMnc);
+                    return showRoamingNotification;
+                }
+            }
+        }
+
+        String[] excludedMccs = config.getStringArray(CarrierConfigManager
+                .KEY_DATA_CONNECTED_ROAMING_NOTIFICATION_EXCLUDED_MCCS_STRING_ARRAY);
+        String roamingMcc = roamingNumeric.length() < 3 ? "" : roamingNumeric.substring(0, 3);
+        if (excludedMccs != null && !TextUtils.isEmpty(roamingMcc)) {
+            for (String mcc : excludedMccs) {
+                if (roamingMcc.equals(mcc)) {
+                    Log.d(LOG_TAG, "shouldShowRoamingNotification: ignore for MCC " + mcc);
+                    return false;
+                }
+            }
+        }
+
+        if (showRoamingNotification) {
+            Log.d(LOG_TAG, "shouldShowRoamingNotification: show for numeric " + roamingNumeric);
+        }
+        return showRoamingNotification;
+    }
+
     private void updateLimitedSimFunctionForDualSim() {
         if (DBG) Log.d(LOG_TAG, "updateLimitedSimFunctionForDualSim");
         // check conditions to display limited SIM function notification under dual SIM
diff --git a/src/com/android/services/telephony/domainselection/CarrierConfigHelper.java b/src/com/android/services/telephony/domainselection/CarrierConfigHelper.java
index 6ca2eeb..d39a6b7 100644
--- a/src/com/android/services/telephony/domainselection/CarrierConfigHelper.java
+++ b/src/com/android/services/telephony/domainselection/CarrierConfigHelper.java
@@ -23,6 +23,7 @@
 import android.annotation.Nullable;
 import android.content.Context;
 import android.content.SharedPreferences;
+import android.content.res.Resources;
 import android.os.Handler;
 import android.os.Looper;
 import android.os.Message;
@@ -36,6 +37,12 @@
 import android.util.Log;
 
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.phone.R;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
 
 /** Helper class to cache carrier configurations. */
 public class CarrierConfigHelper extends Handler {
@@ -57,6 +64,8 @@
     // For test purpose only
     private final SharedPreferences mSharedPreferences;
 
+    private List<Integer> mIgnoreNrWhenSimRemoved = null;
+
     /**
      * Creates an instance.
      *
@@ -87,6 +96,7 @@
         mSharedPreferences = sharedPreferences;
 
         readFromSharedPreference();
+        readResourceConfiguration();
     }
 
     /**
@@ -154,8 +164,7 @@
                 break;
             }
         }
-        // Ignore configuration for TEST SIM.
-        if (carrierId == 1911) carrierConfig = false;
+        if (mIgnoreNrWhenSimRemoved.contains(carrierId)) carrierConfig = false;
 
         Boolean savedConfig = mVoNrSupported.get(Integer.valueOf(slotIndex));
         if (carrierConfig == savedConfig) {
@@ -174,6 +183,22 @@
                 + ", supported=" + carrierConfig);
     }
 
+    private void readResourceConfiguration() {
+        try {
+            mIgnoreNrWhenSimRemoved = Arrays.stream(mContext.getResources().getIntArray(
+                    R.array.config_carriers_ignore_ngran_preference_when_sim_removed))
+                    .boxed().collect(Collectors.toList());
+        } catch (Resources.NotFoundException nfe) {
+            Log.e(TAG, "readResourceConfiguration exception=" + nfe);
+        } catch (NullPointerException npe) {
+            Log.e(TAG, "readResourceConfiguration exception=" + npe);
+        }
+        if (mIgnoreNrWhenSimRemoved == null) {
+            mIgnoreNrWhenSimRemoved = new ArrayList<Integer>();
+        }
+        Log.i(TAG, "readResourceConfiguration ignoreNrWhenSimRemoved=" + mIgnoreNrWhenSimRemoved);
+    }
+
     /** Destroys the instance. */
     public void destroy() {
         if (DBG) Log.d(TAG, "destroy");
diff --git a/src/com/android/services/telephony/domainselection/EmergencyCallDomainSelector.java b/src/com/android/services/telephony/domainselection/EmergencyCallDomainSelector.java
index 8b39434..3d6a4d1 100644
--- a/src/com/android/services/telephony/domainselection/EmergencyCallDomainSelector.java
+++ b/src/com/android/services/telephony/domainselection/EmergencyCallDomainSelector.java
@@ -288,7 +288,6 @@
                             sendMessage(obtainMessage(MSG_NETWORK_SCAN_RESULT, regResult));
                         });
             } else {
-                maybeModifyImsRats();
                 // Continuous scan, do not start a new timer.
                 requestScan(false);
             }
@@ -500,9 +499,7 @@
                 b.getIntArray(KEY_EMERGENCY_OVER_IMS_SUPPORTED_3GPP_NETWORK_TYPES_INT_ARRAY);
         mImsRoamRatsConfig = b.getIntArray(
                 KEY_EMERGENCY_OVER_IMS_ROAMING_SUPPORTED_3GPP_NETWORK_TYPES_INT_ARRAY);
-        if (mCarrierConfigHelper.isVoNrEmergencySupported(getSlotId())) {
-            maybeModifyImsRats();
-        }
+        maybeModifyImsRats();
 
         mCsRatsConfig =
                 b.getIntArray(KEY_EMERGENCY_OVER_CS_SUPPORTED_ACCESS_NETWORK_TYPES_INT_ARRAY);
@@ -572,11 +569,10 @@
         }
     }
 
-    /**
-     * Adds NGRAN if no other network has been found in case of no SIM or SIM locked state.
-     */
+    /** Adds NGRAN if SIM is absent or locked and the last valid subscription supported NGRAN. */
     private void maybeModifyImsRats() {
-        if (!isSimReady() && mImsRatsConfig.length < 2) {
+        if (mCarrierConfigHelper.isVoNrEmergencySupported(getSlotId())
+                && !isSimReady() && mImsRatsConfig.length < 2) {
             // Default configuration includes only EUTRAN.
             mImsRatsConfig = new int[] { EUTRAN, NGRAN };
             mImsRoamRatsConfig = new int[] { EUTRAN, NGRAN };
@@ -861,6 +857,11 @@
             }
         }
 
+        // Adds NGRAN at the end of the list if SIM is absent or locked and NGRAN is not included.
+        if (!isSimReady() && !preferredNetworks.contains(NGRAN)) {
+            preferredNetworks.add(NGRAN);
+        }
+
         return preferredNetworks;
     }
 
diff --git a/tests/src/com/android/services/telephony/domainselection/CarrierConfigHelperTest.java b/tests/src/com/android/services/telephony/domainselection/CarrierConfigHelperTest.java
index 1828067..5d4fe17 100644
--- a/tests/src/com/android/services/telephony/domainselection/CarrierConfigHelperTest.java
+++ b/tests/src/com/android/services/telephony/domainselection/CarrierConfigHelperTest.java
@@ -32,9 +32,11 @@
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 import android.content.Context;
 import android.content.SharedPreferences;
+import android.content.res.Resources;
 import android.os.HandlerThread;
 import android.os.Looper;
 import android.os.PersistableBundle;
@@ -64,10 +66,12 @@
     private static final int SLOT_0 = 0;
     private static final int SLOT_1 = 1;
     private static final int SUB_1 = 1;
+    private static final int TEST_SIM_CARRIER_ID = 1911;
 
     @Mock private Context mContext;
     @Mock private SharedPreferences mSharedPreferences;
     @Mock private SharedPreferences.Editor mEditor;
+    @Mock private Resources mResources;
 
     private HandlerThread mHandlerThread;
     private TestableLooper mLooper;
@@ -93,6 +97,11 @@
             public String getOpPackageName() {
                 return "";
             }
+
+            @Override
+            public Resources getResources() {
+                return mResources;
+            }
         };
 
         if (Looper.myLooper() == null) {
@@ -116,6 +125,8 @@
         doReturn(TelephonyManager.SIM_STATE_READY)
                 .when(mTelephonyManager).getSimState(anyInt());
 
+        doReturn(new int[] { TEST_SIM_CARRIER_ID }).when(mResources).getIntArray(anyInt());
+
         mCarrierConfigHelper = new CarrierConfigHelper(mContext, mHandlerThread.getLooper(),
                 mSharedPreferences);
     }
@@ -231,6 +242,28 @@
         assertTrue(mCarrierConfigHelper.isVoNrEmergencySupported(SLOT_0));
     }
 
+    @Test
+    public void testCarrierIgnoreNrWhenSimRemoved() throws Exception {
+        ArgumentCaptor<CarrierConfigManager.CarrierConfigChangeListener> callbackCaptor =
+                ArgumentCaptor.forClass(CarrierConfigManager.CarrierConfigChangeListener.class);
+
+        verify(mCarrierConfigManager).registerCarrierConfigChangeListener(any(),
+                callbackCaptor.capture());
+
+        CarrierConfigManager.CarrierConfigChangeListener callback = callbackCaptor.getValue();
+
+        assertNotNull(callback);
+
+        // NR is included and carrier config for TEST SIM is applied.
+        PersistableBundle b = getPersistableBundle(new int[] { EUTRAN, NGRAN }, true);
+        doReturn(b).when(mCarrierConfigManager).getConfigForSubId(anyInt(), anyString());
+        callback.onCarrierConfigChanged(SLOT_0, SUB_1, TEST_SIM_CARRIER_ID, 0);
+
+        // NR is ignored.
+        assertFalse(mCarrierConfigHelper.isVoNrEmergencySupported(SLOT_0));
+        assertFalse(mCarrierConfigHelper.isVoNrEmergencySupported(SLOT_1));
+    }
+
     private static PersistableBundle getPersistableBundle(int[] imsRats, boolean applied) {
         PersistableBundle bundle  = new PersistableBundle();
         bundle.putIntArray(KEY_EMERGENCY_OVER_IMS_SUPPORTED_3GPP_NETWORK_TYPES_INT_ARRAY, imsRats);
diff --git a/tests/src/com/android/services/telephony/domainselection/EmergencyCallDomainSelectorTest.java b/tests/src/com/android/services/telephony/domainselection/EmergencyCallDomainSelectorTest.java
index 818fe8e..eab40f9 100644
--- a/tests/src/com/android/services/telephony/domainselection/EmergencyCallDomainSelectorTest.java
+++ b/tests/src/com/android/services/telephony/domainselection/EmergencyCallDomainSelectorTest.java
@@ -2004,7 +2004,35 @@
     }
 
     @Test
-    public void testSimLockScanPsPreferredIncludingNr() throws Exception {
+    public void testSimLockScanPsPreferredWithNr() throws Exception {
+        createSelector(SLOT_0_SUB_ID);
+        unsolBarringInfoChanged(false);
+
+        // The last valid subscription supported NR.
+        doReturn(true).when(mCarrierConfigHelper).isVoNrEmergencySupported(eq(SLOT_0));
+        when(mTelephonyManager.getSimState(anyInt())).thenReturn(
+                TelephonyManager.SIM_STATE_PIN_REQUIRED);
+
+        EmergencyRegResult regResult = getEmergencyRegResult(
+                UNKNOWN, REGISTRATION_STATE_UNKNOWN, 0, false, false, 0, 0, "", "");
+        SelectionAttributes attr = getSelectionAttributes(SLOT_0, SLOT_0_SUB_ID, regResult);
+        mDomainSelector.selectDomain(attr, mTransportSelectorCallback);
+        processAllMessages();
+
+        bindImsServiceUnregistered();
+        processAllMessages();
+
+        verify(mWwanSelectorCallback, times(1)).onRequestEmergencyNetworkScan(
+                any(), anyInt(), any(), any());
+        assertEquals(4, mAccessNetwork.size());
+        assertEquals(EUTRAN, (int) mAccessNetwork.get(0));
+        assertEquals(NGRAN, (int) mAccessNetwork.get(1));
+        assertEquals(UTRAN, (int) mAccessNetwork.get(2));
+        assertEquals(GERAN, (int) mAccessNetwork.get(3));
+    }
+
+    @Test
+    public void testSimLockScanPsPreferredWithNrAtTheEnd() throws Exception {
         createSelector(SLOT_0_SUB_ID);
         unsolBarringInfoChanged(false);
 
@@ -2022,32 +2050,18 @@
 
         verify(mWwanSelectorCallback, times(1)).onRequestEmergencyNetworkScan(
                 any(), anyInt(), any(), any());
-        assertEquals(3, mAccessNetwork.size());
+        assertEquals(4, mAccessNetwork.size());
         assertEquals(EUTRAN, (int) mAccessNetwork.get(0));
         assertEquals(UTRAN, (int) mAccessNetwork.get(1));
         assertEquals(GERAN, (int) mAccessNetwork.get(2));
-        assertNotNull(mResultConsumer);
-
-        mResultConsumer.accept(regResult);
-        processAllMessages();
-
-        verify(mWwanSelectorCallback, times(2)).onRequestEmergencyNetworkScan(
-                any(), anyInt(), any(), any());
-        assertEquals(4, mAccessNetwork.size());
-        assertEquals(EUTRAN, (int) mAccessNetwork.get(0));
-        assertEquals(NGRAN, (int) mAccessNetwork.get(1));
-        assertEquals(UTRAN, (int) mAccessNetwork.get(2));
-        assertEquals(GERAN, (int) mAccessNetwork.get(3));
+        assertEquals(NGRAN, (int) mAccessNetwork.get(3));
     }
 
     @Test
-    public void testInvalidSubscriptionScanPsPreferredWithoutNr() throws Exception {
-        createSelector(SLOT_0_SUB_ID);
+    public void testInvalidSubscriptionScanPsPreferredWithNrAtTheEnd() throws Exception {
+        createSelector(SubscriptionManager.INVALID_SUBSCRIPTION_ID);
         unsolBarringInfoChanged(false);
 
-        when(mTelephonyManager.getSimState(anyInt())).thenReturn(
-                TelephonyManager.SIM_STATE_PIN_REQUIRED);
-
         EmergencyRegResult regResult = getEmergencyRegResult(
                 UNKNOWN, REGISTRATION_STATE_UNKNOWN, 0, false, false, 0, 0, "", "");
         SelectionAttributes attr = getSelectionAttributes(SLOT_0,
@@ -2060,20 +2074,20 @@
 
         verify(mWwanSelectorCallback, times(1)).onRequestEmergencyNetworkScan(
                 any(), anyInt(), any(), any());
-        assertEquals(3, mAccessNetwork.size());
+        assertEquals(4, mAccessNetwork.size());
         assertEquals(EUTRAN, (int) mAccessNetwork.get(0));
         assertEquals(UTRAN, (int) mAccessNetwork.get(1));
         assertEquals(GERAN, (int) mAccessNetwork.get(2));
+        assertEquals(NGRAN, (int) mAccessNetwork.get(3));
     }
 
     @Test
     public void testInvalidSubscriptionScanPsPreferredWithNr() throws Exception {
-        createSelector(SLOT_0_SUB_ID);
+        createSelector(SubscriptionManager.INVALID_SUBSCRIPTION_ID);
         unsolBarringInfoChanged(false);
 
+        // The last valid subscription supported NR.
         doReturn(true).when(mCarrierConfigHelper).isVoNrEmergencySupported(eq(SLOT_0));
-        when(mTelephonyManager.getSimState(anyInt())).thenReturn(
-                TelephonyManager.SIM_STATE_PIN_REQUIRED);
 
         EmergencyRegResult regResult = getEmergencyRegResult(
                 UNKNOWN, REGISTRATION_STATE_UNKNOWN, 0, false, false, 0, 0, "", "");