Merge "Drop FEATURE_TELEPHONY_GSM from interface requirements" into main
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 3dc9e08..feb5a78 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -599,7 +599,7 @@
 
         <receiver
             android:name=".security.SafetySourceReceiver"
-            android:exported="false"
+            android:exported="true"
             androidprv:systemUserOnly="true">
             <intent-filter>
                 <action android:name="android.safetycenter.action.REFRESH_SAFETY_SOURCES"/>
diff --git a/res/values-bn/strings.xml b/res/values-bn/strings.xml
index 1004106..e4a02b3 100644
--- a/res/values-bn/strings.xml
+++ b/res/values-bn/strings.xml
@@ -534,7 +534,7 @@
     <string name="notification_voicemail_title_count" msgid="2806950319222327082">"নতুন ভয়েসমেল (<xliff:g id="COUNT">%d</xliff:g>)"</string>
     <string name="notification_voicemail_text_format" msgid="5720947141702312537">"<xliff:g id="VOICEMAIL_NUMBER">%s</xliff:g> এ ডায়াল করুন"</string>
     <string name="notification_voicemail_no_vm_number" msgid="3423686009815186750">"ভয়েসমেল নম্বর অজানা"</string>
-    <string name="notification_network_selection_title" msgid="255595526707809121">"কোনো পরিষেবা নেই"</string>
+    <string name="notification_network_selection_title" msgid="255595526707809121">"কোনও পরিষেবা নেই"</string>
     <string name="notification_network_selection_text" msgid="553288408722427659">"বেছে নেওয়া নেটওয়ার্ক (<xliff:g id="OPERATOR_NAME">%s</xliff:g>) নেই"</string>
     <string name="incall_error_power_off" product="watch" msgid="7191184639454113633">"কল করতে মোবাইল নেটওয়ার্ক চালু করুন, বিমান মোড বা ব্যাটারি সেভার বন্ধ করুন৷"</string>
     <string name="incall_error_power_off" product="default" msgid="8131672264311208673">"কল করতে বিমান মোড বন্ধ করুন৷"</string>
diff --git a/res/values-fr-rCA/strings.xml b/res/values-fr-rCA/strings.xml
index b62728f..ff32473 100644
--- a/res/values-fr-rCA/strings.xml
+++ b/res/values-fr-rCA/strings.xml
@@ -582,7 +582,7 @@
     <string name="description_concat_format" msgid="2014471565101724088">"%1$s, %2$s"</string>
     <string name="dialerKeyboardHintText" msgid="1115266533703764049">"Utilisez le clavier pour composer un numéro."</string>
     <string name="onscreenHoldText" msgid="4025348842151665191">"Attente"</string>
-    <string name="onscreenEndCallText" msgid="6138725377654842757">"Terminé"</string>
+    <string name="onscreenEndCallText" msgid="6138725377654842757">"Terminer"</string>
     <string name="onscreenShowDialpadText" msgid="658465753816164079">"Clavier numérique"</string>
     <string name="onscreenMuteText" msgid="5470306116733843621">"Couper le son"</string>
     <string name="onscreenAddCallText" msgid="9075675082903611677">"Autre appel"</string>
diff --git a/res/values-fr/strings.xml b/res/values-fr/strings.xml
index f20960c..22a69bb 100644
--- a/res/values-fr/strings.xml
+++ b/res/values-fr/strings.xml
@@ -582,7 +582,7 @@
     <string name="description_concat_format" msgid="2014471565101724088">"%1$s, %2$s"</string>
     <string name="dialerKeyboardHintText" msgid="1115266533703764049">"Utilisez le clavier pour composer un numéro."</string>
     <string name="onscreenHoldText" msgid="4025348842151665191">"En attente"</string>
-    <string name="onscreenEndCallText" msgid="6138725377654842757">"Raccrocher"</string>
+    <string name="onscreenEndCallText" msgid="6138725377654842757">"Terminer"</string>
     <string name="onscreenShowDialpadText" msgid="658465753816164079">"Clavier"</string>
     <string name="onscreenMuteText" msgid="5470306116733843621">"Silencieux"</string>
     <string name="onscreenAddCallText" msgid="9075675082903611677">"Autre appel"</string>
diff --git a/res/values-ky/strings.xml b/res/values-ky/strings.xml
index 4e74022..a7054f9 100644
--- a/res/values-ky/strings.xml
+++ b/res/values-ky/strings.xml
@@ -539,7 +539,7 @@
     <string name="incall_error_power_off" product="watch" msgid="7191184639454113633">"Мобилдик тармакты күйгүзүңүз, чалуу үчүн \"Учакта\" режимин же \"Батареяны үнөмдөө\" режимин өчүрүңүз."</string>
     <string name="incall_error_power_off" product="default" msgid="8131672264311208673">"Чалуу үчүн учак режимин өчүрүңүз."</string>
     <string name="incall_error_power_off_wfc" msgid="9125661184694727052">"Чалуу үчүн учак режимин өчүрүңүз же зымсыз тармакка туташыңыз."</string>
-    <string name="incall_error_power_off_thermal" product="default" msgid="8695809601655300168"><b>"Телефон ысып кетти"</b>\n\n"Бул чалуу аяктабай жатат. Телефон муздагандан кийин кайра аракет кылыңыз.\n\nШашылыш чалууларды аткара берсеңиз болот."</string>
+    <string name="incall_error_power_off_thermal" product="default" msgid="8695809601655300168"><b>"Телефон ысып кетти"</b>\n\n"Бул чалуу аяктабай жатат. Телефон муздагандан кийин кайталап көрүңүз.\n\nШашылыш чалууларды аткара берсеңиз болот."</string>
     <string name="incall_error_ecm_emergency_only" msgid="5622379058883722080">"Кадимки шартта чалуу үчүн шашылыш кайра чалуу режиминен чыгыңыз."</string>
     <string name="incall_error_emergency_only" msgid="8786127461027964653">"Тармакта катталган эмес."</string>
     <string name="incall_error_out_of_service" msgid="1927265196942672791">"Мобилдик тармак жок."</string>
diff --git a/res/values/config.xml b/res/values/config.xml
index 61e01b0..847c4c5 100644
--- a/res/values/config.xml
+++ b/res/values/config.xml
@@ -157,6 +157,8 @@
     <string name="mobile_network_settings_package" translatable="false">com.android.settings</string>
     <!-- Class name for the mobile network settings activity [DO NOT TRANSLATE] -->
     <string name="mobile_network_settings_class" translatable="false">com.android.settings.Settings$MobileNetworkActivity</string>
+    <!-- Class name for the SIMs settings activity [DO NOT TRANSLATE] -->
+    <string name="sims_settings_class" translatable="false">com.android.settings.Settings$MobileNetworkListActivity</string>
 
     <!-- CDMA activation goes through HFA -->
     <!-- DEPRECATED: Use CarrierConfigManager#KEY_USE_HFA_FOR_PROVISIONING_BOOL -->
diff --git a/src/com/android/phone/CallFeaturesSetting.java b/src/com/android/phone/CallFeaturesSetting.java
index 1dfcde7..1c55256 100644
--- a/src/com/android/phone/CallFeaturesSetting.java
+++ b/src/com/android/phone/CallFeaturesSetting.java
@@ -35,6 +35,7 @@
 import android.os.HandlerExecutor;
 import android.os.Looper;
 import android.os.PersistableBundle;
+import android.os.UserHandle;
 import android.os.UserManager;
 import android.preference.Preference;
 import android.preference.PreferenceActivity;
@@ -233,7 +234,7 @@
                                         getString(R.string.mobile_network_settings_package),
                                         getString(R.string.mobile_network_settings_class));
                                 intent.setComponent(mobileNetworkSettingsComponent);
-                                startActivity(intent);
+                                startActivityAsUser(intent, UserHandle.CURRENT);
                             }
                         };
                 builder.setMessage(getResourcesForSubId().getString(
@@ -622,7 +623,7 @@
         Intent intent = subscriptionInfoHelper.getIntent(CallFeaturesSetting.class);
         intent.setAction(Intent.ACTION_MAIN);
         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
-        activity.startActivity(intent);
+        activity.startActivityAsUser(intent, UserHandle.CURRENT);
         activity.finish();
     }
 
diff --git a/src/com/android/phone/CarrierConfigLoader.java b/src/com/android/phone/CarrierConfigLoader.java
index 46f20f5..c6c26b0 100644
--- a/src/com/android/phone/CarrierConfigLoader.java
+++ b/src/com/android/phone/CarrierConfigLoader.java
@@ -1872,9 +1872,16 @@
      */
     @Nullable
     private String getCurrentPackageName() {
+        if (mFeatureFlags.hsumPackageManager()) {
+            PackageManager pm = mContext.createContextAsUser(Binder.getCallingUserHandle(), 0)
+                    .getPackageManager();
+            if (pm == null) return null;
+            String[] callingPackageNames = pm.getPackagesForUid(Binder.getCallingUid());
+            return (callingPackageNames == null) ? null : callingPackageNames[0];
+        }
         if (mPackageManager == null) return null;
-        String[] callingUids = mPackageManager.getPackagesForUid(Binder.getCallingUid());
-        return (callingUids == null) ? null : callingUids[0];
+        String[] callingPackageNames = mPackageManager.getPackagesForUid(Binder.getCallingUid());
+        return (callingPackageNames == null) ? null : callingPackageNames[0];
     }
 
     /**
diff --git a/src/com/android/phone/EmergencyCallbackModeService.java b/src/com/android/phone/EmergencyCallbackModeService.java
index 464db6f..70eb017 100644
--- a/src/com/android/phone/EmergencyCallbackModeService.java
+++ b/src/com/android/phone/EmergencyCallbackModeService.java
@@ -129,9 +129,9 @@
             // Show dialog box
             else if (intent.getAction().equals(
                     TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS)) {
-                    context.startActivity(
+                    context.startActivityAsUser(
                             new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS)
-                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
+                                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), UserHandle.CURRENT);
             }
         }
     };
diff --git a/src/com/android/phone/EmergencyDialer.java b/src/com/android/phone/EmergencyDialer.java
index a608b1b..d4fdca6 100644
--- a/src/com/android/phone/EmergencyDialer.java
+++ b/src/com/android/phone/EmergencyDialer.java
@@ -40,6 +40,7 @@
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.os.PersistableBundle;
+import android.os.UserHandle;
 import android.provider.Settings;
 import android.telecom.PhoneAccount;
 import android.telecom.TelecomManager;
@@ -511,7 +512,7 @@
 
         Intent intent = (Intent) button.getTag(R.id.tag_intent);
         if (intent != null) {
-            startActivity(intent);
+            startActivityAsUser(intent, UserHandle.CURRENT);
         }
     }
 
diff --git a/src/com/android/phone/ImsRcsController.java b/src/com/android/phone/ImsRcsController.java
index 766d719..e2ae343 100644
--- a/src/com/android/phone/ImsRcsController.java
+++ b/src/com/android/phone/ImsRcsController.java
@@ -986,9 +986,16 @@
      */
     @Nullable
     private String getCurrentPackageName() {
+        if (mFeatureFlags.hsumPackageManager()) {
+            PackageManager pm = mApp.getBaseContext().createContextAsUser(
+                    Binder.getCallingUserHandle(), 0).getPackageManager();
+            if (pm == null) return null;
+            String[] callingPackageNames = pm.getPackagesForUid(Binder.getCallingUid());
+            return (callingPackageNames == null) ? null : callingPackageNames[0];
+        }
         if (mPackageManager == null) return null;
-        String[] callingUids = mPackageManager.getPackagesForUid(Binder.getCallingUid());
-        return (callingUids == null) ? null : callingUids[0];
+        String[] callingPackageNames = mPackageManager.getPackagesForUid(Binder.getCallingUid());
+        return (callingPackageNames == null) ? null : callingPackageNames[0];
     }
 
     /**
diff --git a/src/com/android/phone/NotificationMgr.java b/src/com/android/phone/NotificationMgr.java
index 3cd9a8b..3c7b321 100644
--- a/src/com/android/phone/NotificationMgr.java
+++ b/src/com/android/phone/NotificationMgr.java
@@ -519,8 +519,14 @@
             return false;
         }
 
-        List<ResolveInfo> receivers = mContext.getPackageManager()
-                .queryBroadcastReceivers(intent, 0);
+        List<ResolveInfo> receivers;
+        if (mFeatureFlags.hsumPackageManager()) {
+            receivers = mContext.createContextAsUser(userHandle, 0)
+                    .getPackageManager().queryBroadcastReceivers(intent, 0);
+        } else {
+            receivers = mContext.getPackageManager()
+                    .queryBroadcastReceivers(intent, 0);
+        }
         return receivers.size() > 0;
     }
 
diff --git a/src/com/android/phone/PhoneInterfaceManager.java b/src/com/android/phone/PhoneInterfaceManager.java
index 46d8b83..f4b41a2 100644
--- a/src/com/android/phone/PhoneInterfaceManager.java
+++ b/src/com/android/phone/PhoneInterfaceManager.java
@@ -442,6 +442,9 @@
     private PackageManager mPackageManager;
     private final int mVendorApiLevel;
 
+    @Nullable
+    private ComponentName mTestEuiccUiComponent;
+
     /** User Activity */
     private final AtomicBoolean mNotifyUserActivity;
     private static final int USER_ACTIVITY_NOTIFICATION_DELAY = 200;
@@ -475,7 +478,7 @@
     public static final String RESET_NETWORK_ERASE_MODEM_CONFIG_ENABLED =
             "reset_network_erase_modem_config_enabled";
 
-    private static final int SET_NETWORK_SELECTION_MODE_AUTOMATIC_TIMEOUT_MS = 2000; // 2 seconds
+    private static final int BLOCKING_REQUEST_DEFAULT_TIMEOUT_MS = 2000; // 2 seconds
 
     private static final int MODEM_ACTIVITY_TIME_OFFSET_CORRECTION_MS = 50;
 
@@ -2613,7 +2616,7 @@
             if (state != PhoneConstants.State.OFFHOOK && state != PhoneConstants.State.RINGING) {
                 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-                mApp.startActivity(intent);
+                mApp.startActivityAsUser(intent, UserHandle.CURRENT);
             }
         } finally {
             Binder.restoreCallingIdentity(identity);
@@ -2628,7 +2631,7 @@
         if (DBG) log("call: " + number);
 
         // This is just a wrapper around the ACTION_CALL intent, but we still
-        // need to do a permission check since we're calling startActivity()
+        // need to do a permission check since we're calling startActivityAsUser()
         // from the context of the phone app.
         enforceCallPermission();
 
@@ -2664,7 +2667,7 @@
             Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
             intent.putExtra(SUBSCRIPTION_KEY, subId);
             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-            mApp.startActivity(intent);
+            mApp.startActivityAsUser(intent, UserHandle.CURRENT);
         } finally {
             Binder.restoreCallingIdentity(identity);
         }
@@ -2994,8 +2997,11 @@
     public boolean needMobileRadioShutdown() {
         enforceReadPrivilegedPermission("needMobileRadioShutdown");
 
-        enforceTelephonyFeatureWithException(getCurrentPackageName(),
-                PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS, "needMobileRadioShutdown");
+        if (!mApp.getResources().getBoolean(
+                com.android.internal.R.bool.config_force_phone_globals_creation)) {
+            enforceTelephonyFeatureWithException(getCurrentPackageName(),
+                    PackageManager.FEATURE_TELEPHONY_RADIO_ACCESS, "needMobileRadioShutdown");
+        }
 
         /*
          * If any of the Radios are available, it will need to be
@@ -4221,8 +4227,12 @@
 
         final long identity = Binder.clearCallingIdentity();
         try {
-            Boolean success = (Boolean) sendRequest(CMD_SET_VOICEMAIL_NUMBER,
-                    new Pair<String, String>(alphaTag, number), new Integer(subId));
+            Boolean success = (Boolean) sendRequest(
+                    CMD_SET_VOICEMAIL_NUMBER,
+                    new Pair<String, String>(alphaTag, number),
+                    new Integer(subId),
+                    BLOCKING_REQUEST_DEFAULT_TIMEOUT_MS);
+            if (success == null) return false; // most likely due to a timeout
             return success;
         } finally {
             Binder.restoreCallingIdentity(identity);
@@ -6792,7 +6802,7 @@
             }
             if (DBG) log("setNetworkSelectionModeAutomatic: subId " + subId);
             sendRequest(CMD_SET_NETWORK_SELECTION_MODE_AUTOMATIC, null, subId,
-                    SET_NETWORK_SELECTION_MODE_AUTOMATIC_TIMEOUT_MS);
+                    BLOCKING_REQUEST_DEFAULT_TIMEOUT_MS);
         } finally {
             Binder.restoreCallingIdentity(identity);
         }
@@ -7418,8 +7428,11 @@
     public boolean isTetheringApnRequiredForSubscriber(int subId) {
         enforceModifyPermission();
 
-        enforceTelephonyFeatureWithException(getCurrentPackageName(),
-                PackageManager.FEATURE_TELEPHONY_DATA, "isTetheringApnRequiredForSubscriber");
+        if (!mApp.getResources().getBoolean(
+                    com.android.internal.R.bool.config_force_phone_globals_creation)) {
+            enforceTelephonyFeatureWithException(getCurrentPackageName(),
+                    PackageManager.FEATURE_TELEPHONY_DATA, "isTetheringApnRequiredForSubscriber");
+        }
 
         final long identity = Binder.clearCallingIdentity();
         final Phone phone = getPhone(subId);
@@ -7619,8 +7632,12 @@
     public int getCarrierPrivilegeStatusForUid(int subId, int uid) {
         enforceReadPrivilegedPermission("getCarrierPrivilegeStatusForUid");
 
-        enforceTelephonyFeatureWithException(getCurrentPackageName(),
-                PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION, "getCarrierPrivilegeStatusForUid");
+        if (!mApp.getResources().getBoolean(
+                    com.android.internal.R.bool.config_force_phone_globals_creation)) {
+            enforceTelephonyFeatureWithException(getCurrentPackageName(),
+                    PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION,
+                    "getCarrierPrivilegeStatusForUid");
+        }
 
         return getCarrierPrivilegeStatusForUidWithPermission(subId, uid);
     }
@@ -7720,6 +7737,12 @@
     @Override
     public List<String> getPackagesWithCarrierPrivileges(int phoneId) {
         enforceReadPrivilegedPermission("getPackagesWithCarrierPrivileges");
+
+        enforceTelephonyFeatureWithException(
+                getCurrentPackageName(),
+                PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION,
+                "getPackagesWithCarrierPrivileges");
+
         Phone phone = PhoneFactory.getPhone(phoneId);
         if (phone == null) {
             return Collections.emptyList();
@@ -7905,8 +7928,11 @@
             return null;
         }
 
-        enforceTelephonyFeatureWithException(callingPackage,
-                PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION, "getLine1NumberForDisplay");
+        if (!mApp.getResources().getBoolean(
+                    com.android.internal.R.bool.config_force_phone_globals_creation)) {
+            enforceTelephonyFeatureWithException(callingPackage,
+                    PackageManager.FEATURE_TELEPHONY_SUBSCRIPTION, "getLine1NumberForDisplay");
+        }
 
         final long identity = Binder.clearCallingIdentity();
         try {
@@ -8712,8 +8738,11 @@
     public void requestModemActivityInfo(ResultReceiver result) {
         enforceModifyPermission();
 
-        enforceTelephonyFeatureWithException(getCurrentPackageName(),
-                PackageManager.FEATURE_TELEPHONY, "requestModemActivityInfo");
+        if (!mApp.getResources().getBoolean(
+                    com.android.internal.R.bool.config_force_phone_globals_creation)) {
+            enforceTelephonyFeatureWithException(getCurrentPackageName(),
+                    PackageManager.FEATURE_TELEPHONY, "requestModemActivityInfo");
+        }
 
         WorkSource workSource = getWorkSource(Binder.getCallingUid());
 
@@ -9581,8 +9610,16 @@
     }
 
     private WorkSource getWorkSource(int uid) {
-        String packageName = mApp.getPackageManager().getNameForUid(uid);
-        if (uid == Process.ROOT_UID && packageName == null) {
+        PackageManager pm;
+        if (mFeatureFlags.hsumPackageManager()) {
+            pm = mApp.getBaseContext().createContextAsUser(UserHandle.getUserHandleForUid(uid), 0)
+                    .getPackageManager();
+        } else {
+            pm = mApp.getPackageManager();
+        }
+
+        String packageName = pm.getNameForUid(uid);
+        if (UserHandle.isSameApp(uid, Process.ROOT_UID) && packageName == null) {
             // Downstream WorkSource attribution inside the RIL requires both a UID and package name
             // to be set for wakelock tracking, otherwise RIL requests fail with a runtime
             // exception. ROOT_UID seems not to have a valid package name returned by
@@ -10385,8 +10422,11 @@
                             mApp, defaultPhone.getSubId(), "isEmergencyNumber(Potential)");
         }
 
-        enforceTelephonyFeatureWithException(getCurrentPackageName(),
-                PackageManager.FEATURE_TELEPHONY_CALLING, "isEmergencyNumber");
+        if (!mApp.getResources().getBoolean(
+                com.android.internal.R.bool.config_force_phone_globals_creation)) {
+            enforceTelephonyFeatureWithException(getCurrentPackageName(),
+                    PackageManager.FEATURE_TELEPHONY_CALLING, "isEmergencyNumber");
+        }
 
         final long identity = Binder.clearCallingIdentity();
         try {
@@ -10848,9 +10888,16 @@
      */
     @Override
     public @Nullable String getCurrentPackageName() {
-        PackageManager pm = mApp.getPackageManager();
-        String[] packageNames = pm == null ? null : pm.getPackagesForUid(Binder.getCallingUid());
-        return packageNames == null ? null : packageNames[0];
+        if (mFeatureFlags.hsumPackageManager()) {
+            PackageManager pm = mApp.getBaseContext().createContextAsUser(
+                    Binder.getCallingUserHandle(), 0).getPackageManager();
+            if (pm == null) return null;
+            String[] callingUids = pm.getPackagesForUid(Binder.getCallingUid());
+            return (callingUids == null) ? null : callingUids[0];
+        }
+        if (mPackageManager == null) return null;
+        String[] callingUids = mPackageManager.getPackagesForUid(Binder.getCallingUid());
+        return (callingUids == null) ? null : callingUids[0];
     }
 
     /**
@@ -10860,7 +10907,13 @@
      * Note: This is for logging purposes only and should not be used for security checks.
      */
     private String getCurrentPackageNameOrPhone() {
-        PackageManager pm = mApp.getPackageManager();
+        PackageManager pm;
+        if (mFeatureFlags.hsumPackageManager()) {
+            pm = mApp.getBaseContext().createContextAsUser(
+                    Binder.getCallingUserHandle(), 0).getPackageManager();
+        } else {
+            pm = mApp.getPackageManager();
+        }
         String uidName = pm == null ? null : pm.getNameForUid(Binder.getCallingUid());
         if (uidName != null && !uidName.isEmpty()) return uidName;
         return getCurrentPackageName();
@@ -11017,7 +11070,7 @@
         // Bring up choose default SMS subscription dialog right now
         intent.putExtra(PickSmsSubscriptionActivity.DIALOG_TYPE_KEY,
                 PickSmsSubscriptionActivity.SMS_PICK_FOR_MESSAGE);
-        mApp.startActivity(intent);
+        mApp.startActivityAsUser(intent, UserHandle.CURRENT);
     }
 
     @Override
@@ -11030,13 +11083,13 @@
             Intent intent = new Intent(Intent.ACTION_SENDTO);
             intent.setData(Uri.parse("smsto:"));
             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-            mApp.startActivity(intent);
+            mApp.startActivityAsUser(intent, UserHandle.CURRENT);
         } catch (ActivityNotFoundException e) {
             Log.w(LOG_TAG, "Unable to show intent forwarder, try showing error dialog instead");
             Intent intent = new Intent();
             intent.setClass(mApp, ErrorDialogActivity.class);
             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-            mApp.startActivity(intent);
+            mApp.startActivityAsUser(intent, UserHandle.CURRENT);
         }
     }
 
@@ -11304,7 +11357,7 @@
         // In fact, the current code acquires way too many,
         // and probably has lurking deadlocks.
 
-        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
+        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
             throw new SecurityException("Only the OS may call notifyUserActivity()");
         }
 
@@ -12536,8 +12589,13 @@
 
         String callingProcess;
         try {
-            callingProcess = mApp.getPackageManager().getApplicationInfo(
-                    getCurrentPackageName(), 0).processName;
+            if (mFeatureFlags.hsumPackageManager()) {
+                callingProcess = mApp.getPackageManager().getApplicationInfoAsUser(
+                        getCurrentPackageName(), 0, Binder.getCallingUserHandle()).processName;
+            } else {
+                callingProcess = mApp.getPackageManager().getApplicationInfo(
+                        getCurrentPackageName(), 0).processName;
+            }
         } catch (PackageManager.NameNotFoundException e) {
             callingProcess = getCurrentPackageName();
         }
@@ -12825,15 +12883,31 @@
 
         Context context = getPhoneFromSubIdOrDefault(subId).getContext();
 
-        UserHandle userHandle = null;
-        final long identity = Binder.clearCallingIdentity();
-        try {
-            userHandle = TelephonyUtils.getSubscriptionUserHandle(context, subId);
-        } finally {
-            Binder.restoreCallingIdentity(identity);
+        if (mTelecomFeatureFlags.telecomMainUserInGetRespondMessageApp()){
+            UserHandle mainUser = null;
+            Context userContext = null;
+            final long identity = Binder.clearCallingIdentity();
+            try {
+                mainUser = mUserManager.getMainUser();
+                userContext = context.createContextAsUser(mainUser, 0);
+                Log.d(LOG_TAG, "getDefaultRespondViaMessageApplication: mainUser = " + mainUser);
+            } finally {
+                Binder.restoreCallingIdentity(identity);
+            }
+            return SmsApplication.getDefaultRespondViaMessageApplicationAsUser(userContext,
+                    updateIfNeeded, mainUser);
+        } else {
+            UserHandle userHandle = null;
+            final long identity = Binder.clearCallingIdentity();
+            try {
+                userHandle = TelephonyUtils.getSubscriptionUserHandle(context, subId);
+            } finally {
+                Binder.restoreCallingIdentity(identity);
+            }
+            return SmsApplication.getDefaultRespondViaMessageApplicationAsUser(context,
+                    updateIfNeeded, userHandle);
         }
-        return SmsApplication.getDefaultRespondViaMessageApplicationAsUser(context,
-                updateIfNeeded, userHandle);
+
     }
 
     /**
@@ -13155,7 +13229,7 @@
                 }
             };
             mSatelliteAccessController.requestIsCommunicationAllowedForCurrentLocation(
-                    resultReceiver);
+                    resultReceiver, true);
         } else {
             // No need to check if satellite is allowed at current location when disabling satellite
             mSatelliteController.requestSatelliteEnabled(
@@ -13473,7 +13547,7 @@
     public void requestIsCommunicationAllowedForCurrentLocation(int subId,
             @NonNull ResultReceiver result) {
         enforceSatelliteCommunicationPermission("requestIsCommunicationAllowedForCurrentLocation");
-        mSatelliteAccessController.requestIsCommunicationAllowedForCurrentLocation(result);
+        mSatelliteAccessController.requestIsCommunicationAllowedForCurrentLocation(result, false);
     }
 
     /**
@@ -13793,6 +13867,22 @@
     }
 
     /**
+     * This API can be used by only CTS to control ingoring cellular service state event.
+     *
+     * @param enabled Whether to enable boolean config.
+     * @return {@code true} if the value is set successfully, {@code false} otherwise.
+     */
+    public boolean setSatelliteIgnoreCellularServiceState(boolean enabled) {
+        Log.d(LOG_TAG, "setSatelliteIgnoreServiceState - " + enabled);
+        TelephonyPermissions.enforceShellOnly(
+                Binder.getCallingUid(), "setSatelliteIgnoreServiceState");
+        TelephonyPermissions.enforceCallingOrSelfModifyPermissionOrCarrierPrivilege(mApp,
+                SubscriptionManager.INVALID_SUBSCRIPTION_ID,
+                "setSatelliteIgnoreServiceState");
+        return mSatelliteController.setSatelliteIgnoreCellularServiceState(enabled);
+    }
+
+    /**
      * This API can be used by only CTS to override the timeout durations used by the
      * DatagramController module.
      *
@@ -14385,4 +14475,44 @@
             Binder.restoreCallingIdentity(identity);
         }
     }
+
+    /**
+     * This API can be used by only CTS to override the Euicc UI component.
+     *
+     * @param componentName ui component to be launched for testing. {@code null} to reset.
+     *
+     * @hide
+     */
+    @Override
+    public void setTestEuiccUiComponent(@Nullable ComponentName componentName) {
+        enforceModifyPermission();
+        log("setTestEuiccUiComponent: " + componentName);
+        mTestEuiccUiComponent = componentName;
+    }
+
+    /**
+     * This API can be used by only CTS to retrieve the Euicc UI component.
+     *
+     * @return Euicc UI component. {@code null} if not available.
+     * @hide
+     */
+    @Override
+    @Nullable
+    public ComponentName getTestEuiccUiComponent() {
+        enforceReadPrivilegedPermission("getTestEuiccUiComponent");
+        return mTestEuiccUiComponent;
+    }
+
+    /**
+     * This API can be used only for test purpose to override the carrier roaming Ntn eligibility
+     *
+     * @param state        to update Ntn Eligibility.
+     * @param resetRequired to reset the overridden flag in satellite controller.
+     * @return {@code true} if the shell command is successful, {@code false} otherwise.
+     */
+    public boolean overrideCarrierRoamingNtnEligibilityChanged(boolean state,
+            boolean resetRequired) {
+        return mSatelliteAccessController.overrideCarrierRoamingNtnEligibilityChanged(state,
+                resetRequired);
+    }
 }
diff --git a/src/com/android/phone/SimContacts.java b/src/com/android/phone/SimContacts.java
index 4229482..d5f7840 100644
--- a/src/com/android/phone/SimContacts.java
+++ b/src/com/android/phone/SimContacts.java
@@ -33,6 +33,7 @@
 import android.net.Uri;
 import android.os.Bundle;
 import android.os.RemoteException;
+import android.os.UserHandle;
 import android.provider.ContactsContract;
 import android.provider.ContactsContract.CommonDataKinds.Email;
 import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
@@ -372,7 +373,7 @@
                             Uri.fromParts(PhoneAccount.SCHEME_TEL, phoneNumber, null));
                     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                           | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
-                    startActivity(intent);
+                    startActivityAsUser(intent, UserHandle.CURRENT);
                     finish();
                     return true;
                 }
diff --git a/src/com/android/phone/SimPhonebookProvider.java b/src/com/android/phone/SimPhonebookProvider.java
index 3917d83..d912389 100644
--- a/src/com/android/phone/SimPhonebookProvider.java
+++ b/src/com/android/phone/SimPhonebookProvider.java
@@ -30,6 +30,7 @@
 import android.database.Cursor;
 import android.database.MatrixCursor;
 import android.net.Uri;
+import android.os.Binder;
 import android.os.Bundle;
 import android.os.CancellationSignal;
 import android.os.RemoteException;
@@ -677,8 +678,14 @@
         String callingPackage = getCallingPackage();
         int granted = PackageManager.PERMISSION_DENIED;
         if (callingPackage != null) {
-            granted = getContext().getPackageManager().checkPermission(
-                    Manifest.permission.MODIFY_PHONE_STATE, callingPackage);
+            if (Flags.hsumPackageManager()) {
+                granted = getContext().createContextAsUser(Binder.getCallingUserHandle(), 0)
+                        .getPackageManager().checkPermission(
+                                Manifest.permission.MODIFY_PHONE_STATE, callingPackage);
+            } else {
+                granted = getContext().getPackageManager().checkPermission(
+                        Manifest.permission.MODIFY_PHONE_STATE, callingPackage);
+            }
         }
         return granted == PackageManager.PERMISSION_GRANTED
                 || telephonyManager.hasCarrierPrivileges(args.subscriptionId);
diff --git a/src/com/android/phone/SpecialCharSequenceMgr.java b/src/com/android/phone/SpecialCharSequenceMgr.java
index 8fe084b..d0fe2c1 100644
--- a/src/com/android/phone/SpecialCharSequenceMgr.java
+++ b/src/com/android/phone/SpecialCharSequenceMgr.java
@@ -21,6 +21,7 @@
 import android.content.ActivityNotFoundException;
 import android.content.Context;
 import android.content.Intent;
+import android.os.UserHandle;
 import android.os.UserManager;
 import android.provider.Settings;
 import android.telephony.PhoneNumberUtils;
@@ -186,7 +187,7 @@
                                     "com.android.phone.SimContacts");
                 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                 intent.putExtra("index", index);
-                PhoneGlobals.getInstance().startActivity(intent);
+                PhoneGlobals.getInstance().startActivityAsUser(intent, UserHandle.CURRENT);
 
                 return true;
             } catch (NumberFormatException ex) {}
@@ -313,9 +314,9 @@
             log("handleRegulatoryInfoDisplay() sending intent to settings app");
             Intent showRegInfoIntent = new Intent(Settings.ACTION_SHOW_REGULATORY_INFO);
             try {
-                context.startActivity(showRegInfoIntent);
+                context.startActivityAsUser(showRegInfoIntent, UserHandle.CURRENT);
             } catch (ActivityNotFoundException e) {
-                Log.e(TAG, "startActivity() failed: " + e);
+                Log.e(TAG, "startActivityAsUser() failed: " + e);
             }
             return true;
         }
diff --git a/src/com/android/phone/TelephonyShellCommand.java b/src/com/android/phone/TelephonyShellCommand.java
index 08b041b..840f961 100644
--- a/src/com/android/phone/TelephonyShellCommand.java
+++ b/src/com/android/phone/TelephonyShellCommand.java
@@ -34,6 +34,7 @@
 import android.os.Process;
 import android.os.RemoteException;
 import android.os.ServiceSpecificException;
+import android.os.UserHandle;
 import android.provider.BlockedNumberContract;
 import android.telephony.BarringInfo;
 import android.telephony.CarrierConfigManager;
@@ -55,12 +56,12 @@
 import com.android.internal.telephony.ITelephony;
 import com.android.internal.telephony.Phone;
 import com.android.internal.telephony.PhoneFactory;
+import com.android.internal.telephony.TelephonyPermissions;
 import com.android.internal.telephony.d2d.Communicator;
 import com.android.internal.telephony.emergency.EmergencyNumberTracker;
 import com.android.internal.telephony.util.TelephonyUtils;
 import com.android.modules.utils.BasicShellCommandHandler;
 import com.android.phone.callcomposer.CallComposerPictureManager;
-import com.android.phone.euicc.EuiccUiDispatcherActivity;
 import com.android.phone.utils.CarrierAllowListInfo;
 
 import java.io.IOException;
@@ -130,9 +131,6 @@
     private static final String CC_SET_VALUES_FROM_XML = "set-values-from-xml";
     private static final String CC_CLEAR_VALUES = "clear-values";
 
-    private static final String EUICC_SUBCOMMAND = "euicc";
-    private static final String EUICC_SET_UI_COMPONENT = "set-euicc-uicomponent";
-
     private static final String GBA_SUBCOMMAND = "gba";
     private static final String GBA_SET_SERVICE = "set-service";
     private static final String GBA_GET_SERVICE = "get-service";
@@ -189,6 +187,8 @@
             "set-satellite-gateway-service-package-name";
     private static final String SET_SATELLITE_LISTENING_TIMEOUT_DURATION =
             "set-satellite-listening-timeout-duration";
+    private static final String SET_SATELLITE_IGNORE_CELLULAR_SERVICE_STATE =
+            "set-satellite-ignore-cellular-service-state";
     private static final String SET_SATELLITE_POINTING_UI_CLASS_NAME =
             "set-satellite-pointing-ui-class-name";
     private static final String SET_DATAGRAM_CONTROLLER_TIMEOUT_DURATION =
@@ -212,6 +212,9 @@
     private static final String SET_SATELLITE_SUBSCRIBERID_LIST_CHANGED_INTENT_COMPONENT =
             "set-satellite-subscriberid-list-changed-intent-component";
 
+    private static final String SET_SATELLITE_ACCESS_RESTRICTION_CHECKING_RESULT =
+            "set-satellite-access-restriction-checking-result";
+
     private static final String DOMAIN_SELECTION_SUBCOMMAND = "domainselection";
     private static final String DOMAIN_SELECTION_SET_SERVICE_OVERRIDE = "set-dss-override";
     private static final String DOMAIN_SELECTION_CLEAR_SERVICE_OVERRIDE = "clear-dss-override";
@@ -357,8 +360,6 @@
                 return handleDataTestModeCommand();
             case END_BLOCK_SUPPRESSION:
                 return handleEndBlockSuppressionCommand();
-            case EUICC_SUBCOMMAND:
-                return handleEuiccCommand();
             case GBA_SUBCOMMAND:
                 return handleGbaCommand();
             case D2D_SUBCOMMAND:
@@ -404,6 +405,8 @@
                 return handleSetSatelliteGatewayServicePackageNameCommand();
             case SET_SATELLITE_LISTENING_TIMEOUT_DURATION:
                 return handleSetSatelliteListeningTimeoutDuration();
+            case SET_SATELLITE_IGNORE_CELLULAR_SERVICE_STATE:
+                return handleSetSatelliteIgnoreCellularServiceState();
             case SET_SATELLITE_POINTING_UI_CLASS_NAME:
                 return handleSetSatellitePointingUiClassNameCommand();
             case SET_DATAGRAM_CONTROLLER_TIMEOUT_DURATION:
@@ -426,6 +429,8 @@
                 return handleSetIsSatelliteCommunicationAllowedForCurrentLocationCache();
             case SET_SATELLITE_SUBSCRIBERID_LIST_CHANGED_INTENT_COMPONENT:
                 return handleSetSatelliteSubscriberIdListChangedIntentComponent();
+            case SET_SATELLITE_ACCESS_RESTRICTION_CHECKING_RESULT:
+                return handleOverrideCarrierRoamingNtnEligibilityChanged();
             default: {
                 return handleDefaultCommands(cmd);
             }
@@ -690,15 +695,6 @@
         pw.println("          is specified, it will choose the default voice SIM slot.");
     }
 
-    private void onHelpEuicc() {
-        PrintWriter pw = getOutPrintWriter();
-        pw.println("Euicc Commands:");
-        pw.println("  euicc set-euicc-uicomponent COMPONENT_NAME PACKAGE_NAME");
-        pw.println("  Sets the Euicc Ui-Component which handles EuiccService Actions.");
-        pw.println("  COMPONENT_NAME: The component name which handles UI Actions.");
-        pw.println("  PACKAGE_NAME: THe package name in which ui component belongs.");
-    }
-
     private void onHelpGba() {
         PrintWriter pw = getOutPrintWriter();
         pw.println("Gba Commands:");
@@ -1119,7 +1115,8 @@
         }
         // Verify that the user is allowed to run the command. Only allowed in rooted device in a
         // non user build.
-        if (Binder.getCallingUid() != Process.ROOT_UID || TelephonyUtils.IS_USER) {
+        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.ROOT_UID)
+                || TelephonyUtils.IS_USER) {
             errPw.println("cc: Permission denied.");
             return -1;
         }
@@ -1684,15 +1681,14 @@
     }
 
     private boolean checkShellUid() {
-        // adb can run as root or as shell, depending on whether the device is rooted.
-        return Binder.getCallingUid() == Process.SHELL_UID
-                || Binder.getCallingUid() == Process.ROOT_UID;
+        return TelephonyPermissions.isRootOrShell(Binder.getCallingUid());
     }
 
     private int handleCcCommand() {
         // Verify that the user is allowed to run the command. Only allowed in rooted device in a
         // non user build.
-        if (Binder.getCallingUid() != Process.ROOT_UID || TelephonyUtils.IS_USER) {
+        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.ROOT_UID)
+                || TelephonyUtils.IS_USER) {
             getErrPrintWriter().println("cc: Permission denied.");
             return -1;
         }
@@ -2216,39 +2212,11 @@
         return 0;
     }
 
-    private int handleEuiccCommand() {
-        String arg = getNextArg();
-        if (arg == null) {
-            onHelpEuicc();
-            return 0;
-        }
-
-        switch (arg) {
-            case EUICC_SET_UI_COMPONENT: {
-                return handleEuiccServiceCommand();
-            }
-        }
-        return -1;
-    }
-
-    private int handleEuiccServiceCommand() {
-        String uiComponent = getNextArg();
-        String packageName = getNextArg();
-        if (packageName == null || uiComponent == null) {
-            return -1;
-        }
-        EuiccUiDispatcherActivity.setTestEuiccUiComponent(packageName, uiComponent);
-        if (VDBG) {
-            Log.v(LOG_TAG, "euicc set-euicc-uicomponent " + uiComponent +" "
-                    + packageName);
-        }
-        return 0;
-    }
-
     private int handleRestartModemCommand() {
         // Verify that the user is allowed to run the command. Only allowed in rooted device in a
         // non user build.
-        if (Binder.getCallingUid() != Process.ROOT_UID || TelephonyUtils.IS_USER) {
+        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.ROOT_UID)
+                || TelephonyUtils.IS_USER) {
             getErrPrintWriter().println("RestartModem: Permission denied.");
             return -1;
         }
@@ -2262,7 +2230,8 @@
     private int handleGetImei() {
         // Verify that the user is allowed to run the command. Only allowed in rooted device in a
         // non user build.
-        if (Binder.getCallingUid() != Process.ROOT_UID || TelephonyUtils.IS_USER) {
+        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.ROOT_UID)
+                || TelephonyUtils.IS_USER) {
             getErrPrintWriter().println("Device IMEI: Permission denied.");
             return -1;
         }
@@ -2293,7 +2262,8 @@
     private int handleUnattendedReboot() {
         // Verify that the user is allowed to run the command. Only allowed in rooted device in a
         // non user build.
-        if (Binder.getCallingUid() != Process.ROOT_UID || TelephonyUtils.IS_USER) {
+        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.ROOT_UID)
+                || TelephonyUtils.IS_USER) {
             getErrPrintWriter().println("UnattendedReboot: Permission denied.");
             return -1;
         }
@@ -2307,7 +2277,8 @@
     private int handleGetSimSlotsMapping() {
         // Verify that the user is allowed to run the command. Only allowed in rooted device in a
         // non user build.
-        if (Binder.getCallingUid() != Process.ROOT_UID || TelephonyUtils.IS_USER) {
+        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.ROOT_UID)
+                || TelephonyUtils.IS_USER) {
             getErrPrintWriter().println("GetSimSlotsMapping: Permission denied.");
             return -1;
         }
@@ -3393,6 +3364,37 @@
         return 0;
     }
 
+    private int handleSetSatelliteIgnoreCellularServiceState() {
+        PrintWriter errPw = getErrPrintWriter();
+        boolean enabled = false;
+
+        String opt;
+        while ((opt = getNextOption()) != null) {
+            switch (opt) {
+                case "-d": {
+                    enabled = Boolean.parseBoolean(getNextArgRequired());
+                    break;
+                }
+            }
+        }
+        Log.d(LOG_TAG, "handleSetSatelliteIgnoreCellularServiceState: enabled =" + enabled);
+
+        try {
+            boolean result = mInterface.setSatelliteIgnoreCellularServiceState(enabled);
+            if (VDBG) {
+                Log.v(LOG_TAG, "handleSetSatelliteIgnoreCellularServiceState " + enabled
+                        + ", result = " + result);
+            }
+            getOutPrintWriter().println(result);
+        } catch (RemoteException e) {
+            Log.w(LOG_TAG, "handleSetSatelliteIgnoreCellularServiceState: " + enabled
+                    + ", error = " + e.getMessage());
+            errPw.println("Exception: " + e.getMessage());
+            return -1;
+        }
+        return 0;
+    }
+
     private int handleSetDatagramControllerTimeoutDuration() {
         PrintWriter errPw = getErrPrintWriter();
         boolean reset = false;
@@ -3719,7 +3721,6 @@
         PrintWriter errPw = getErrPrintWriter();
         String opt;
         String state;
-
         if ((opt = getNextArg()) == null) {
             errPw.println(
                     "adb shell cmd phone set-is-satellite-communication-allowed-for-current"
@@ -3732,6 +3733,10 @@
                     state = "cache_allowed";
                     break;
                 }
+                case "-na": {
+                    state = "cache_not_allowed";
+                    break;
+                }
                 case "-n": {
                     state = "cache_clear_and_not_allowed";
                     break;
@@ -4070,4 +4075,48 @@
         }
         return jSonString;
     }
+
+    /**
+     * This method override the check for carrier roaming Ntn eligibility.
+     * <ul>
+     * <li> `adb shell cmd phone set-satellite-access-restriction-checking-result true` will set
+     * override eligibility to true.</li>
+     * <li> `adb shell cmd phone set-satellite-access-restriction-checking-result false` will
+     * override eligibility to false.</li>
+     * <li> `adb shell cmd phone set-satellite-access-restriction-checking-result` will reset the
+     * override data set through adb command.</li>
+     * </ul>
+     *
+     * @return {@code true} is command executed successfully otherwise {@code false}.
+     */
+    private int handleOverrideCarrierRoamingNtnEligibilityChanged() {
+        PrintWriter errPw = getErrPrintWriter();
+        String opt;
+        boolean state = false;
+        boolean isRestRequired = false;
+        try {
+            if ((opt = getNextArg()) == null) {
+                isRestRequired = true;
+            } else {
+                if ("true".equalsIgnoreCase(opt)) {
+                    state = true;
+                }
+            }
+            boolean result = mInterface.overrideCarrierRoamingNtnEligibilityChanged(state,
+                    isRestRequired);
+            if (VDBG) {
+                Log.v(LOG_TAG, "handleSetSatelliteAccessRestrictionCheckingResult "
+                        + "returns: "
+                        + result);
+            }
+            getOutPrintWriter().println(result);
+        } catch (RemoteException e) {
+            Log.w(LOG_TAG, "handleSetSatelliteAccessRestrictionCheckingResult("
+                    + state + "), error = " + e.getMessage());
+            errPw.println("Exception: " + e.getMessage());
+            return -1;
+        }
+        Log.d(LOG_TAG, "handleSetSatelliteAccessRestrictionCheckingResult(" + state + ")");
+        return 0;
+    }
 }
diff --git a/src/com/android/phone/euicc/EuiccUiDispatcherActivity.java b/src/com/android/phone/euicc/EuiccUiDispatcherActivity.java
index 3e44062..9632329 100644
--- a/src/com/android/phone/euicc/EuiccUiDispatcherActivity.java
+++ b/src/com/android/phone/euicc/EuiccUiDispatcherActivity.java
@@ -28,8 +28,8 @@
 import android.os.UserHandle;
 import android.permission.LegacyPermissionManager;
 import android.service.euicc.EuiccService;
+import android.telephony.TelephonyManager;
 import android.telephony.euicc.EuiccManager;
-import android.text.TextUtils;
 import android.util.Log;
 
 import com.android.internal.annotations.VisibleForTesting;
@@ -59,8 +59,6 @@
     private LegacyPermissionManager mPermissionManager;
     private boolean mGrantPermissionDone = false;
     private ThreadPoolExecutor mExecutor;
-    // Used for CTS EuiccManager action verification
-    private static ComponentName mTestEuiccUiComponentName;
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
@@ -90,25 +88,13 @@
             }
 
             euiccUiIntent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
-            startActivity(euiccUiIntent);
+            startActivityAsUser(euiccUiIntent, UserHandle.CURRENT);
         } finally {
             // Since we're using Theme.NO_DISPLAY, we must always finish() at the end of onCreate().
             finish();
         }
     }
 
-    /**
-    * This API used to set the Test EuiccUiComponent for CTS
-    * @param packageName package which handles the intent
-    * @param componentName ui component to be launched for testing
-    */
-    public static void setTestEuiccUiComponent(String packageName, String componentName) {
-        mTestEuiccUiComponentName = null;
-        if (!TextUtils.isEmpty(packageName) && !TextUtils.isEmpty(componentName)) {
-            mTestEuiccUiComponentName = new ComponentName(packageName, componentName);
-        }
-    }
-
     @VisibleForTesting
     @Nullable
     Intent resolveEuiccUiIntent() {
@@ -124,10 +110,11 @@
             return null;
         }
 
-        if (mTestEuiccUiComponentName != null) {
-            Log.i(TAG, "Test mode");
-            euiccUiIntent.setComponent(mTestEuiccUiComponentName);
-            mTestEuiccUiComponentName = null;
+        ComponentName testEuiccUiComponent = ((TelephonyManager)
+                getSystemService(Context.TELEPHONY_SERVICE)).getTestEuiccUiComponent();
+        if (testEuiccUiComponent != null) {
+            Log.i(TAG, "Test mode: " + testEuiccUiComponent);
+            euiccUiIntent.setComponent(testEuiccUiComponent);
             return euiccUiIntent;
         }
 
diff --git a/src/com/android/phone/satellite/accesscontrol/SatelliteAccessController.java b/src/com/android/phone/satellite/accesscontrol/SatelliteAccessController.java
index ce77a92..57c7ff0 100644
--- a/src/com/android/phone/satellite/accesscontrol/SatelliteAccessController.java
+++ b/src/com/android/phone/satellite/accesscontrol/SatelliteAccessController.java
@@ -25,6 +25,10 @@
 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_REQUEST_NOT_SUPPORTED;
 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_SUCCESS;
 
+import static com.android.internal.telephony.satellite.SatelliteConstants.TRIGGERING_EVENT_EXTERNAL_REQUEST;
+import static com.android.internal.telephony.satellite.SatelliteConstants.TRIGGERING_EVENT_LOCATION_SETTINGS_ENABLED;
+import static com.android.internal.telephony.satellite.SatelliteConstants.TRIGGERING_EVENT_MCC_CHANGED;
+import static com.android.internal.telephony.satellite.SatelliteConstants.TRIGGERING_EVENT_UNKNOWN;
 import static com.android.internal.telephony.satellite.SatelliteController.SATELLITE_SHARED_PREF;
 
 import android.annotation.ArrayRes;
@@ -255,9 +259,9 @@
      */
     private final ConcurrentHashMap<IBinder, ISatelliteCommunicationAllowedStateCallback>
             mSatelliteCommunicationAllowedStateChangedListeners = new ConcurrentHashMap<>();
-    private final Object mSatelliteCommunicationAllowStateLock = new Object();
+    protected final Object mSatelliteCommunicationAllowStateLock = new Object();
     @GuardedBy("mSatelliteCommunicationAllowStateLock")
-    private boolean mCurrentSatelliteAllowedState = false;
+    protected boolean mCurrentSatelliteAllowedState = false;
 
     protected static final long ALLOWED_STATE_CACHE_VALID_DURATION_NANOS =
             TimeUnit.HOURS.toNanos(4);
@@ -282,6 +286,10 @@
         }
     };
 
+    private final Object mIsAllowedCheckBeforeEnablingSatelliteLock = new Object();
+    @GuardedBy("mIsAllowedCheckBeforeEnablingSatelliteLock")
+    private boolean mIsAllowedCheckBeforeEnablingSatellite;
+
     /**
      * Create a SatelliteAccessController instance.
      *
@@ -357,7 +365,7 @@
                                 protected void onReceiveResult(int resultCode, Bundle resultData) {
                                     // do nothing
                                 }
-                            });
+                            }, false);
                 }
             }
         };
@@ -375,7 +383,7 @@
                                 protected void onReceiveResult(int resultCode, Bundle resultData) {
                                     // do nothing
                                 }
-                            });
+                            }, false);
                 }
             }
 
@@ -402,6 +410,7 @@
                         + mCurrentSatelliteAllowedState);
                 mCurrentSatelliteAllowedState = isAllowed;
                 notifySatelliteCommunicationAllowedStateChanged(isAllowed);
+                mControllerMetricsStats.reportAllowedStateChanged();
             }
         }
     }
@@ -441,7 +450,7 @@
             case EVENT_LOCATION_SETTINGS_ENABLED:
                 // Fall through
             case EVENT_COUNTRY_CODE_CHANGED:
-                handleSatelliteAllowedRegionPossiblyChanged();
+                handleSatelliteAllowedRegionPossiblyChanged(msg.what);
                 break;
             default:
                 plogw("SatelliteAccessControllerHandler: unexpected message code: " + msg.what);
@@ -457,12 +466,18 @@
      *               if the request failed.
      */
     public void requestIsCommunicationAllowedForCurrentLocation(
-            @NonNull ResultReceiver result) {
+            @NonNull ResultReceiver result, boolean enablingSatellite) {
         if (!mFeatureFlags.oemEnabledSatelliteFlag()) {
             plogd("oemEnabledSatelliteFlag is disabled");
             result.send(SATELLITE_RESULT_REQUEST_NOT_SUPPORTED, null);
             return;
         }
+        plogd("requestIsCommunicationAllowedForCurrentLocation : "
+                + "enablingSatellite is " + enablingSatellite);
+        synchronized (mIsAllowedCheckBeforeEnablingSatelliteLock) {
+            mIsAllowedCheckBeforeEnablingSatellite = enablingSatellite;
+        }
+        mAccessControllerMetricsStats.setTriggeringEvent(TRIGGERING_EVENT_EXTERNAL_REQUEST);
         sendRequestAsync(CMD_IS_SATELLITE_COMMUNICATION_ALLOWED,
                 new Pair<>(mSatelliteController.getSatellitePhone().getSubId(), result));
     }
@@ -1048,6 +1063,9 @@
         if (!shouldRetryValidatingPossibleChangeInAllowedRegion(resultCode)) {
             setIsSatelliteAllowedRegionPossiblyChanged(false);
         }
+        synchronized (mIsAllowedCheckBeforeEnablingSatelliteLock) {
+            mIsAllowedCheckBeforeEnablingSatellite = false;
+        }
         reportMetrics(resultCode, allowed);
     }
 
@@ -1114,7 +1132,7 @@
         };
     }
 
-    private void handleSatelliteAllowedRegionPossiblyChanged() {
+    private void handleSatelliteAllowedRegionPossiblyChanged(int handleEvent) {
         if (!mFeatureFlags.oemEnabledSatelliteFlag()) {
             ploge("handleSatelliteAllowedRegionPossiblyChanged: "
                     + "The feature flag oemEnabledSatelliteFlag() is not enabled");
@@ -1124,7 +1142,14 @@
             logd("handleSatelliteAllowedRegionPossiblyChanged");
             setIsSatelliteAllowedRegionPossiblyChanged(true);
             requestIsCommunicationAllowedForCurrentLocation(
-                    mHandlerForSatelliteAllowedResult);
+                    mHandlerForSatelliteAllowedResult, false);
+            int triggeringEvent = TRIGGERING_EVENT_UNKNOWN;
+            if (handleEvent == EVENT_LOCATION_SETTINGS_ENABLED) {
+                triggeringEvent = TRIGGERING_EVENT_LOCATION_SETTINGS_ENABLED;
+            } else if (handleEvent == EVENT_COUNTRY_CODE_CHANGED) {
+                triggeringEvent = TRIGGERING_EVENT_MCC_CHANGED;
+            }
+            mAccessControllerMetricsStats.setTriggeringEvent(triggeringEvent);
         }
     }
 
@@ -1168,28 +1193,32 @@
     /**
      * Telephony-internal logic to verify if satellite access is restricted from the location query.
      */
-    private void checkSatelliteAccessRestrictionUsingGPS() {
+    @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
+    public void checkSatelliteAccessRestrictionUsingGPS() {
         logv("checkSatelliteAccessRestrictionUsingGPS:");
-        if (isInEmergency()) {
-            executeLocationQuery();
-        } else {
-            if (mLocationManager.isLocationEnabled()) {
-                plogd("location query is allowed");
-                if (allowLocationQueryForSatelliteAllowedCheck()) {
-                    executeLocationQuery();
-                } else {
-                    Bundle bundle = new Bundle();
-                    bundle.putBoolean(KEY_SATELLITE_COMMUNICATION_ALLOWED,
-                            mLatestSatelliteCommunicationAllowed);
-                    sendSatelliteAllowResultToReceivers(SATELLITE_RESULT_SUCCESS, bundle,
-                            mLatestSatelliteCommunicationAllowed);
-                }
+        synchronized (mIsAllowedCheckBeforeEnablingSatelliteLock) {
+            if (isInEmergency()) {
+                executeLocationQuery();
             } else {
-                plogv("location query is not allowed");
-                Bundle bundle = new Bundle();
-                bundle.putBoolean(KEY_SATELLITE_COMMUNICATION_ALLOWED, false);
-                sendSatelliteAllowResultToReceivers(
-                        SATELLITE_RESULT_LOCATION_DISABLED, bundle, false);
+                if (mLocationManager.isLocationEnabled()) {
+                    plogd("location query is allowed");
+                    if (allowLocationQueryForSatelliteAllowedCheck()
+                            || mIsAllowedCheckBeforeEnablingSatellite) {
+                        executeLocationQuery();
+                    } else {
+                        Bundle bundle = new Bundle();
+                        bundle.putBoolean(KEY_SATELLITE_COMMUNICATION_ALLOWED,
+                                mLatestSatelliteCommunicationAllowed);
+                        sendSatelliteAllowResultToReceivers(SATELLITE_RESULT_SUCCESS, bundle,
+                                mLatestSatelliteCommunicationAllowed);
+                    }
+                } else {
+                    plogv("location query is not allowed");
+                    Bundle bundle = new Bundle();
+                    bundle.putBoolean(KEY_SATELLITE_COMMUNICATION_ALLOWED, false);
+                    sendSatelliteAllowResultToReceivers(
+                            SATELLITE_RESULT_LOCATION_DISABLED, bundle, false);
+                }
             }
         }
     }
@@ -1285,8 +1314,7 @@
         }
     }
 
-    @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
-    protected void queryCurrentLocation() {
+    private void queryCurrentLocation() {
         synchronized (mLock) {
             if (mLocationRequestCancellationSignal != null) {
                 plogd("queryCurrentLocation : "
@@ -1324,6 +1352,7 @@
                 }
                 mAccessControllerMetricsStats.setAccessControlType(
                         SatelliteConstants.ACCESS_CONTROL_TYPE_CURRENT_LOCATION);
+                mControllerMetricsStats.reportLocationQuerySuccessful(true);
                 checkSatelliteAccessRestrictionForLocation(location);
             } else {
                 plogd("current location is not available");
@@ -1338,6 +1367,7 @@
                     sendSatelliteAllowResultToReceivers(
                             SATELLITE_RESULT_LOCATION_NOT_AVAILABLE, bundle, false);
                 }
+                mControllerMetricsStats.reportLocationQuerySuccessful(false);
             }
         }
     }
@@ -1890,6 +1920,10 @@
                 mLatestSatelliteCommunicationAllowedSetTime = getElapsedRealtimeNanos();
                 mLatestSatelliteCommunicationAllowed = true;
                 mCurrentSatelliteAllowedState = true;
+            } else if ("cache_not_allowed".equalsIgnoreCase(state)) {
+                mLatestSatelliteCommunicationAllowedSetTime = getElapsedRealtimeNanos();
+                mLatestSatelliteCommunicationAllowed = false;
+                mCurrentSatelliteAllowedState = false;
             } else if ("cache_clear_and_not_allowed".equalsIgnoreCase(state)) {
                 mLatestSatelliteCommunicationAllowedSetTime = 0;
                 mLatestSatelliteCommunicationAllowed = false;
@@ -1986,6 +2020,32 @@
         }
     }
 
+    /**
+     * This API can be used only for test purpose to override the carrier roaming Ntn eligibility
+     *
+     * @param state        to update Ntn Eligibility.
+     * @param resetRequired to reset the overridden flag in satellite controller.
+     * @return {@code true} if the shell command is successful, {@code false} otherwise.
+     */
+    public boolean overrideCarrierRoamingNtnEligibilityChanged(boolean state,
+            boolean resetRequired) {
+        if (!mFeatureFlags.carrierRoamingNbIotNtn()) {
+            logd("overrideCarrierRoamingNtnEligibilityChanged: "
+                    + "carrierRoamingNbIotNtn is disabled");
+            return false;
+        }
+
+        if (!isMockModemAllowed()) {
+            logd("overrideCarrierRoamingNtnEligibilityChanged: "
+                    + "mock modem not allowed.");
+            return false;
+        }
+
+        logd("calling overrideCarrierRoamingNtnEligibilityChanged");
+        return mSatelliteController.overrideCarrierRoamingNtnEligibilityChanged(state,
+                resetRequired);
+    }
+
     private void plogv(@NonNull String log) {
         Rlog.v(TAG, log);
         if (mPersistentLogger != null) {
diff --git a/src/com/android/phone/settings/RadioInfo.java b/src/com/android/phone/settings/RadioInfo.java
index dcd6971..24d680c 100644
--- a/src/com/android/phone/settings/RadioInfo.java
+++ b/src/com/android/phone/settings/RadioInfo.java
@@ -44,6 +44,7 @@
 import android.os.Message;
 import android.os.PersistableBundle;
 import android.os.SystemProperties;
+import android.os.UserHandle;
 import android.os.UserManager;
 import android.telephony.AccessNetworkConstants;
 import android.telephony.CarrierConfigManager;
@@ -361,6 +362,7 @@
     private int mPreferredNetworkTypeResult;
     private int mCellInfoRefreshRateIndex;
     private int mPhoneId = SubscriptionManager.INVALID_PHONE_INDEX;
+    private static final int DEFAULT_PHONE_ID = 0;
 
     private int mSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
 
@@ -570,7 +572,7 @@
         mActionEsos =
             r.getString(
                     com.android.internal.R.string
-                            .config_satellite_emergency_handover_intent_action);
+                            .config_satellite_test_with_esp_replies_intent_action);
 
         mActionEsosDemo =
             r.getString(
@@ -583,7 +585,15 @@
             mPhone = getPhone(SubscriptionManager.getDefaultSubscriptionId());
         }
         mSubId = SubscriptionManager.getDefaultSubscriptionId();
-        mPhoneId = SubscriptionManager.getPhoneId(mSubId);
+        if (mPhone != null) {
+            mPhoneId = mPhone.getPhoneId();
+        } else {
+            mPhoneId = SubscriptionManager.getPhoneId(mSubId);
+        }
+        if (!SubscriptionManager.isValidPhoneId(mPhoneId)) {
+            mPhoneId = DEFAULT_PHONE_ID;
+        }
+
         mTelephonyManager = getSystemService(TelephonyManager.class)
                 .createForSubscriptionId(mSubId);
         mEuiccManager = getSystemService(EuiccManager.class);
@@ -791,13 +801,15 @@
             }
             mSatelliteEnableNonEmergencyModeButton.setVisibility(View.GONE);
         } else {
-            mEsosButton.setOnClickListener(v -> startActivity(
+            mEsosButton.setOnClickListener(v -> startActivityAsUser(
                     new Intent(mActionEsos).addFlags(
-                            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK))
+                            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK),
+                    UserHandle.CURRENT)
             );
-            mEsosDemoButton.setOnClickListener(v -> startActivity(
+            mEsosDemoButton.setOnClickListener(v -> startActivityAsUser(
                     new Intent(mActionEsosDemo).addFlags(
-                            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK))
+                            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK),
+                    UserHandle.CURRENT)
             );
             mSatelliteEnableNonEmergencyModeButton.setOnClickListener(v ->
                     enableSatelliteNonEmergencyMode());
@@ -1023,10 +1035,6 @@
             if (mSimulateOos[mPhoneId])  {
                 mSimulateOosOnChangeListener.onCheckedChanged(mSimulateOutOfServiceSwitch, false);
             }
-            if (mOriginalSystemChannels[mPhoneId] != null) {
-                mForceSatelliteChannelOnChangeListener
-                        .onCheckedChanged(mEnforceSatelliteChannel, false);
-            }
             if (mCarrierSatelliteOriginalBundle[mPhoneId] != null) {
                 mMockSatelliteListener.onCheckedChanged(mMockSatellite, false);
             }
@@ -1676,49 +1684,50 @@
 
     private MenuItem.OnMenuItemClickListener mViewADNCallback =
             new MenuItem.OnMenuItemClickListener() {
-        public boolean onMenuItemClick(MenuItem item) {
-            Intent intent = new Intent(Intent.ACTION_VIEW);
-            // XXX We need to specify the component here because if we don't
-            // the activity manager will try to resolve the type by calling
-            // the content provider, which causes it to be loaded in a process
-            // other than the Dialer process, which causes a lot of stuff to
-            // break.
-            intent.setClassName("com.android.phone", "com.android.phone.SimContacts");
-            startActivity(intent);
-            return true;
-        }
-    };
+                public boolean onMenuItemClick(MenuItem item) {
+                    Intent intent = new Intent(Intent.ACTION_VIEW);
+                    // XXX We need to specify the component here because if we don't
+                    // the activity manager will try to resolve the type by calling
+                    // the content provider, which causes it to be loaded in a process
+                    // other than the Dialer process, which causes a lot of stuff to
+                    // break.
+                    intent.setClassName("com.android.phone", "com.android.phone.SimContacts");
+                    startActivityAsUser(intent, UserHandle.CURRENT);
+                    return true;
+                }
+            };
 
     private MenuItem.OnMenuItemClickListener mViewFDNCallback =
             new MenuItem.OnMenuItemClickListener() {
-        public boolean onMenuItemClick(MenuItem item) {
-            Intent intent = new Intent(Intent.ACTION_VIEW);
-            // XXX We need to specify the component here because if we don't
-            // the activity manager will try to resolve the type by calling
-            // the content provider, which causes it to be loaded in a process
-            // other than the Dialer process, which causes a lot of stuff to
-            // break.
-            intent.setClassName("com.android.phone", "com.android.phone.settings.fdn.FdnList");
-            startActivity(intent);
-            return true;
-        }
-    };
+                public boolean onMenuItemClick(MenuItem item) {
+                    Intent intent = new Intent(Intent.ACTION_VIEW);
+                    // XXX We need to specify the component here because if we don't
+                    // the activity manager will try to resolve the type by calling
+                    // the content provider, which causes it to be loaded in a process
+                    // other than the Dialer process, which causes a lot of stuff to
+                    // break.
+                    intent.setClassName("com.android.phone",
+                            "com.android.phone.settings.fdn.FdnList");
+                    startActivityAsUser(intent, UserHandle.CURRENT);
+                    return true;
+                }
+            };
 
     private MenuItem.OnMenuItemClickListener mViewSDNCallback =
             new MenuItem.OnMenuItemClickListener() {
-        public boolean onMenuItemClick(MenuItem item) {
-            Intent intent = new Intent(
-                    Intent.ACTION_VIEW, Uri.parse("content://icc/sdn"));
-            // XXX We need to specify the component here because if we don't
-            // the activity manager will try to resolve the type by calling
-            // the content provider, which causes it to be loaded in a process
-            // other than the Dialer process, which causes a lot of stuff to
-            // break.
-            intent.setClassName("com.android.phone", "com.android.phone.ADNList");
-            startActivity(intent);
-            return true;
-        }
-    };
+                public boolean onMenuItemClick(MenuItem item) {
+                    Intent intent = new Intent(
+                            Intent.ACTION_VIEW, Uri.parse("content://icc/sdn"));
+                    // XXX We need to specify the component here because if we don't
+                    // the activity manager will try to resolve the type by calling
+                    // the content provider, which causes it to be loaded in a process
+                    // other than the Dialer process, which causes a lot of stuff to
+                    // break.
+                    intent.setClassName("com.android.phone", "com.android.phone.ADNList");
+                    startActivityAsUser(intent, UserHandle.CURRENT);
+                    return true;
+                }
+            };
 
     private MenuItem.OnMenuItemClickListener mGetImsStatus =
             new MenuItem.OnMenuItemClickListener() {
@@ -1948,7 +1957,7 @@
     private static final int SATELLITE_CHANNEL = 8665;
     private final OnCheckedChangeListener mForceSatelliteChannelOnChangeListener =
             (buttonView, isChecked) -> {
-                if (SubscriptionManager.isValidSubscriptionId(mSubId)) {
+                if (!SubscriptionManager.isValidSubscriptionId(mSubId)) {
                     loge("Force satellite channel invalid subId " + mSubId);
                     return;
                 }
@@ -2297,7 +2306,7 @@
         public void onClick(View v) {
             Intent intent = new Intent(OEM_RADIO_INFO_INTENT);
             try {
-                startActivity(intent);
+                startActivityAsUser(intent, UserHandle.CURRENT);
             } catch (android.content.ActivityNotFoundException ex) {
                 log("OEM-specific Info/Settings Activity Not Found : " + ex);
                 // If the activity does not exist, there are no OEM
diff --git a/src/com/android/phone/settings/SuppServicesUiUtil.java b/src/com/android/phone/settings/SuppServicesUiUtil.java
index 4f1a79f..bf4df6b 100644
--- a/src/com/android/phone/settings/SuppServicesUiUtil.java
+++ b/src/com/android/phone/settings/SuppServicesUiUtil.java
@@ -22,6 +22,7 @@
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
+import android.os.UserHandle;
 import android.telephony.TelephonyManager;
 import android.text.TextUtils;
 import android.util.Log;
@@ -70,9 +71,9 @@
                         Intent intent = new Intent(Intent.ACTION_MAIN);
                         ComponentName mobileNetworkSettingsComponent = new ComponentName(
                                 context.getString(R.string.mobile_network_settings_package),
-                                context.getString(R.string.mobile_network_settings_class));
+                                context.getString(R.string.sims_settings_class));
                         intent.setComponent(mobileNetworkSettingsComponent);
-                        context.startActivity(intent);
+                        context.startActivityAsUser(intent, UserHandle.CURRENT);
                     }
                 };
         return builder.setMessage(message)
diff --git a/src/com/android/phone/settings/VoicemailSettingsActivity.java b/src/com/android/phone/settings/VoicemailSettingsActivity.java
index 817ca4c..909a3ad 100644
--- a/src/com/android/phone/settings/VoicemailSettingsActivity.java
+++ b/src/com/android/phone/settings/VoicemailSettingsActivity.java
@@ -42,7 +42,6 @@
 import android.text.TextUtils;
 import android.util.Log;
 import android.view.MenuItem;
-import android.view.WindowManager;
 import android.widget.ListAdapter;
 import android.widget.Toast;
 
@@ -495,7 +494,7 @@
                             Intent i = new Intent(ACTION_ADD_VOICEMAIL);
                             i.putExtra(IGNORE_PROVIDER_EXTRA, victim);
                             i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
-                            this.startActivity(i);
+                            this.startActivityAsUser(i, UserHandle.CURRENT);
                         }
                         return;
                     }
diff --git a/src/com/android/phone/settings/fdn/EditFdnContactScreen.java b/src/com/android/phone/settings/fdn/EditFdnContactScreen.java
index 0884e12..6bf41f3 100644
--- a/src/com/android/phone/settings/fdn/EditFdnContactScreen.java
+++ b/src/com/android/phone/settings/fdn/EditFdnContactScreen.java
@@ -346,7 +346,7 @@
             Intent intent = mSubscriptionInfoHelper.getIntent(DeleteFdnContactScreen.class);
             intent.putExtra(INTENT_EXTRA_NAME, mName);
             intent.putExtra(INTENT_EXTRA_NUMBER, mNumber);
-            startActivity(intent);
+            startActivityAsUser(intent, UserHandle.CURRENT);
         }
         finish();
     }
diff --git a/src/com/android/phone/settings/fdn/FdnList.java b/src/com/android/phone/settings/fdn/FdnList.java
index c2ecbc6..1b5a7af 100644
--- a/src/com/android/phone/settings/fdn/FdnList.java
+++ b/src/com/android/phone/settings/fdn/FdnList.java
@@ -23,6 +23,7 @@
 import android.net.Uri;
 import android.os.Bundle;
 import android.os.PersistableBundle;
+import android.os.UserHandle;
 import android.telecom.PhoneAccount;
 import android.telephony.CarrierConfigManager;
 import android.telephony.SubscriptionManager;
@@ -167,7 +168,7 @@
                 Intent intent = mSubscriptionInfoHelper.getIntent(FdnSetting.class);
                 intent.setAction(Intent.ACTION_MAIN);
                 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
-                startActivity(intent);
+                startActivityAsUser(intent, UserHandle.CURRENT);
                 finish();
                 return true;
 
@@ -200,7 +201,7 @@
     private void addContact() {
         //If there is no INTENT_EXTRA_NAME provided, EditFdnContactScreen treats it as an "add".
         Intent intent = mSubscriptionInfoHelper.getIntent(EditFdnContactScreen.class);
-        startActivity(intent);
+        startActivityAsUser(intent, UserHandle.CURRENT);
     }
 
     /**
@@ -224,7 +225,7 @@
             Intent intent = mSubscriptionInfoHelper.getIntent(EditFdnContactScreen.class);
             intent.putExtra(INTENT_EXTRA_NAME, name);
             intent.putExtra(INTENT_EXTRA_NUMBER, number);
-            startActivity(intent);
+            startActivityAsUser(intent, UserHandle.CURRENT);
         }
     }
 
@@ -240,7 +241,7 @@
             Intent intent = mSubscriptionInfoHelper.getIntent(DeleteFdnContactScreen.class);
             intent.putExtra(INTENT_EXTRA_NAME, name);
             intent.putExtra(INTENT_EXTRA_NUMBER, number);
-            startActivity(intent);
+            startActivityAsUser(intent, UserHandle.CURRENT);
         }
     }
 
@@ -254,7 +255,7 @@
             if (!TextUtils.isEmpty(number)) {
                 Uri uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, number, null);
                 final Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED, uri);
-                startActivity(intent);
+                startActivityAsUser(intent, UserHandle.CURRENT);
             }
         }
     }
diff --git a/src/com/android/phone/utils/CarrierAllowListInfo.java b/src/com/android/phone/utils/CarrierAllowListInfo.java
index 3ab9733..b230a9e 100644
--- a/src/com/android/phone/utils/CarrierAllowListInfo.java
+++ b/src/com/android/phone/utils/CarrierAllowListInfo.java
@@ -21,9 +21,11 @@
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.Signature;
+import android.os.Binder;
 import android.telephony.Rlog;
 import android.text.TextUtils;
 
+import com.android.internal.telephony.flags.Flags;
 import com.android.internal.telephony.uicc.IccUtils;
 
 import org.json.JSONArray;
@@ -155,7 +157,11 @@
             // package name is mandatory
             return false;
         }
-        final PackageManager packageManager = context.getPackageManager();
+        PackageManager packageManager = context.getPackageManager();
+        if (Flags.hsumPackageManager()) {
+            packageManager = context.createContextAsUser(Binder.getCallingUserHandle(), 0)
+                    .getPackageManager();
+        }
         try {
             MessageDigest sha256MDigest = MessageDigest.getInstance(MESSAGE_DIGEST_256_ALGORITHM);
             final PackageInfo packageInfo = packageManager.getPackageInfo(packageName,
diff --git a/src/com/android/services/telephony/DisconnectCauseUtil.java b/src/com/android/services/telephony/DisconnectCauseUtil.java
index 48786dc..e753e20 100644
--- a/src/com/android/services/telephony/DisconnectCauseUtil.java
+++ b/src/com/android/services/telephony/DisconnectCauseUtil.java
@@ -1046,7 +1046,7 @@
     }
 
     private static Integer getSatelliteErrorString() {
-        if (SatelliteController.getInstance().isSatelliteEnabled()) {
+        if (SatelliteController.getInstance().isSatelliteEnabledOrBeingEnabled()) {
             return R.string.incall_error_satellite_enabled;
         }
         return R.string.incall_error_carrier_roaming_satellite_mode;
diff --git a/src/com/android/services/telephony/PstnIncomingCallNotifier.java b/src/com/android/services/telephony/PstnIncomingCallNotifier.java
index d58c211..3b74c6f 100644
--- a/src/com/android/services/telephony/PstnIncomingCallNotifier.java
+++ b/src/com/android/services/telephony/PstnIncomingCallNotifier.java
@@ -82,30 +82,7 @@
     /**
      * Used to listen to events from {@link #mPhone}.
      */
-    private final Handler mHandler = new Handler() {
-        @Override
-        public void handleMessage(Message msg) {
-            switch(msg.what) {
-                case EVENT_NEW_RINGING_CONNECTION:
-                    handleNewRingingConnection((AsyncResult) msg.obj);
-                    break;
-                case EVENT_CDMA_CALL_WAITING:
-                    handleCdmaCallWaiting((AsyncResult) msg.obj);
-                    break;
-                case EVENT_UNKNOWN_CONNECTION:
-                    handleNewUnknownConnection((AsyncResult) msg.obj);
-                    break;
-                default:
-                    break;
-            }
-        }
-
-        @Override
-        public String toString() {
-            return String.format("[PstnIncomingCallNotifierHandler; phoneId=[%s]",
-                    getPhoneIdAsString());
-        }
-    };
+    private final Handler mHandler;
 
     /**
      * Persists the specified parameters and starts listening to phone events.
@@ -118,6 +95,30 @@
         }
 
         mPhone = phone;
+        mHandler = new Handler(phone.getLooper()) {
+            @Override
+            public void handleMessage(Message msg) {
+                switch(msg.what) {
+                    case EVENT_NEW_RINGING_CONNECTION:
+                        handleNewRingingConnection((AsyncResult) msg.obj);
+                        break;
+                    case EVENT_CDMA_CALL_WAITING:
+                        handleCdmaCallWaiting((AsyncResult) msg.obj);
+                        break;
+                    case EVENT_UNKNOWN_CONNECTION:
+                        handleNewUnknownConnection((AsyncResult) msg.obj);
+                        break;
+                    default:
+                        break;
+                }
+            }
+
+            @Override
+            public String toString() {
+                return String.format("[PstnIncomingCallNotifierHandler; phoneId=[%s]",
+                        getPhoneIdAsString());
+            }
+        };
 
         registerForNotifications();
     }
diff --git a/src/com/android/services/telephony/PstnPhoneCapabilitiesNotifier.java b/src/com/android/services/telephony/PstnPhoneCapabilitiesNotifier.java
index 4038dd1..e91af83 100644
--- a/src/com/android/services/telephony/PstnPhoneCapabilitiesNotifier.java
+++ b/src/com/android/services/telephony/PstnPhoneCapabilitiesNotifier.java
@@ -39,18 +39,7 @@
     private final Phone mPhone;
     private final Listener mListener;
 
-    private final Handler mHandler = new Handler() {
-        @Override
-        public void handleMessage(Message msg) {
-            switch (msg.what) {
-                case EVENT_VIDEO_CAPABILITIES_CHANGED:
-                    handleVideoCapabilitesChanged((AsyncResult) msg.obj);
-                    break;
-                default:
-                    break;
-            }
-        }
-    };
+    private final Handler mHandler;
 
     /*package*/
     PstnPhoneCapabilitiesNotifier(Phone phone, Listener listener) {
@@ -59,6 +48,18 @@
         }
 
         mPhone = phone;
+        mHandler = new Handler(phone.getLooper()) {
+            @Override
+            public void handleMessage(Message msg) {
+                switch (msg.what) {
+                    case EVENT_VIDEO_CAPABILITIES_CHANGED:
+                        handleVideoCapabilitesChanged((AsyncResult) msg.obj);
+                        break;
+                    default:
+                        break;
+                }
+            }
+        };
         mListener = listener;
 
         registerForNotifications();
diff --git a/src/com/android/services/telephony/TelephonyConnectionService.java b/src/com/android/services/telephony/TelephonyConnectionService.java
index 3a52406..e7f91d4 100644
--- a/src/com/android/services/telephony/TelephonyConnectionService.java
+++ b/src/com/android/services/telephony/TelephonyConnectionService.java
@@ -18,6 +18,8 @@
 
 import static android.telephony.CarrierConfigManager.KEY_USE_ONLY_DIALED_SIM_ECC_LIST_BOOL;
 import static android.telephony.DomainSelectionService.SELECTOR_TYPE_CALLING;
+import static android.telephony.ServiceState.STATE_EMERGENCY_ONLY;
+import static android.telephony.ServiceState.STATE_IN_SERVICE;
 import static android.telephony.TelephonyManager.HAL_SERVICE_VOICE;
 
 import static com.android.internal.telephony.PhoneConstants.PHONE_TYPE_GSM;
@@ -39,6 +41,7 @@
 import android.os.Bundle;
 import android.os.ParcelUuid;
 import android.os.PersistableBundle;
+import android.os.UserHandle;
 import android.telecom.Conference;
 import android.telecom.Conferenceable;
 import android.telecom.Connection;
@@ -1156,7 +1159,7 @@
             // so they will only need the special emergency call setup when the phone is out of
             // service.
             if (phone == null || phone.getServiceState().getState()
-                    != ServiceState.STATE_IN_SERVICE) {
+                    != STATE_IN_SERVICE) {
                 String convertedNumber = mPhoneNumberUtilsProxy.convertToEmergencyNumber(this,
                         number);
                 if (!TextUtils.equals(convertedNumber, number)) {
@@ -1182,8 +1185,7 @@
         boolean needToTurnOnRadio = (isEmergencyNumber && (!isRadioOn() || isAirplaneModeOn))
                 || (isRadioPowerDownOnBluetooth() && !isPhoneWifiCallingEnabled);
 
-        if (mSatelliteController.isSatelliteEnabled()
-                || mSatelliteController.isSatelliteBeingEnabled()) {
+        if (mSatelliteController.isSatelliteEnabledOrBeingEnabled()) {
             Log.d(this, "onCreateOutgoingConnection, "
                     + " needToTurnOnRadio=" + needToTurnOnRadio
                     + " needToTurnOffSatellite=" + needToTurnOffSatellite
@@ -1284,8 +1286,7 @@
                         // reporting the OUT_OF_SERVICE state.
                         return phone.getState() == PhoneConstants.State.OFFHOOK
                                 || (phone.getServiceStateTracker().isRadioOn()
-                                && (!mSatelliteController.isSatelliteEnabled()
-                                    && !mSatelliteController.isSatelliteBeingEnabled()));
+                                && !mSatelliteController.isSatelliteEnabledOrBeingEnabled());
                     } else {
                         SubscriptionInfoInternal subInfo = SubscriptionManagerService
                                 .getInstance().getSubscriptionInfoInternal(phone.getSubId());
@@ -1297,7 +1298,7 @@
                         return phone.getState() == PhoneConstants.State.OFFHOOK
                                 // Do not wait for voice in service on opportunistic SIMs.
                                 || subInfo != null && subInfo.isOpportunistic()
-                                || (serviceState == ServiceState.STATE_IN_SERVICE
+                                || (serviceState == STATE_IN_SERVICE
                                 && !needToTurnOffSatellite);
                     }
                 }
@@ -1586,7 +1587,7 @@
                                 simUnlockUiPackage, simUnlockUiClass));
                         simUnlockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                         try {
-                            context.startActivity(simUnlockIntent);
+                            context.startActivityAsUser(simUnlockIntent, UserHandle.CURRENT);
                         } catch (ActivityNotFoundException exception) {
                             Log.e(this, exception, "Unable to find SIM unlock UI activity.");
                         }
@@ -1638,8 +1639,8 @@
 
         if (!isEmergencyNumber) {
             switch (state) {
-                case ServiceState.STATE_IN_SERVICE:
-                case ServiceState.STATE_EMERGENCY_ONLY:
+                case STATE_IN_SERVICE:
+                case STATE_EMERGENCY_ONLY:
                     break;
                 case ServiceState.STATE_OUT_OF_SERVICE:
                     if (phone.isUtEnabled() && number.endsWith("#")) {
@@ -2137,7 +2138,7 @@
 
         return imsPhone != null
                 && (imsPhone.isVoiceOverCellularImsEnabled() || imsPhone.isWifiCallingEnabled())
-                && (imsPhone.getServiceState().getState() == ServiceState.STATE_IN_SERVICE);
+                && (imsPhone.getServiceState().getState() == STATE_IN_SERVICE);
     }
 
     private boolean isRadioOn() {
@@ -2149,8 +2150,7 @@
     }
 
     private boolean shouldExitSatelliteModeForEmergencyCall(boolean isEmergencyNumber) {
-        if (!mSatelliteController.isSatelliteEnabled()
-                && !mSatelliteController.isSatelliteBeingEnabled()) {
+        if (!mSatelliteController.isSatelliteEnabledOrBeingEnabled()) {
             return false;
         }
 
@@ -2482,7 +2482,7 @@
             if (SubscriptionManager.isValidSubscriptionId(subId)) {
                 SubscriptionManager.putSubscriptionIdExtra(intent, subId);
             }
-            startActivity(intent);
+            startActivityAsUser(intent, UserHandle.CURRENT);
         }
         return disconnectCause;
     }
@@ -3069,7 +3069,7 @@
         }
 
         ServiceState ss = phone.getServiceStateTracker().getServiceState();
-        if (ss.getState() != ServiceState.STATE_IN_SERVICE) return false;
+        if (ss.getState() != STATE_IN_SERVICE) return false;
 
         NetworkRegistrationInfo regState = ss.getNetworkRegistrationInfo(
                 NetworkRegistrationInfo.DOMAIN_PS, AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
@@ -4143,7 +4143,7 @@
     @VisibleForTesting
     public boolean isAvailableForEmergencyCalls(Phone phone,
             @EmergencyNumber.EmergencyCallRouting int routing) {
-        if (isCallDisallowedDueToSatellite(phone)) {
+        if (isCallDisallowedDueToSatellite(phone) && isTerrestrialNetworkAvailable()) {
             // Phone is connected to satellite due to which it is not preferred for emergency call.
             return false;
         }
@@ -4157,7 +4157,7 @@
         }
 
         // In service phones are always appropriate for emergency calls.
-        if (ServiceState.STATE_IN_SERVICE == phone.getServiceState().getState()) {
+        if (STATE_IN_SERVICE == phone.getServiceState().getState()) {
             return true;
         }
 
@@ -4168,6 +4168,23 @@
                 && phone.getServiceState().isEmergencyOnly());
     }
 
+    private boolean isTerrestrialNetworkAvailable() {
+        for (Phone phone : mPhoneFactoryProxy.getPhones()) {
+            ServiceState serviceState = phone.getServiceState();
+            if (serviceState != null) {
+                int state = serviceState.getState();
+                if ((state == STATE_IN_SERVICE || state == STATE_EMERGENCY_ONLY
+                        || serviceState.isEmergencyOnly())
+                        && !serviceState.isUsingNonTerrestrialNetwork()) {
+                    Log.d(this, "isTerrestrialNetworkAvailable true");
+                    return true;
+                }
+            }
+        }
+        Log.d(this, "isTerrestrialNetworkAvailable false");
+        return false;
+    }
+
     /**
      * Determines if the connection should allow mute.
      *
@@ -4362,9 +4379,9 @@
                                                 context.getString(
                                                     R.string.mobile_network_settings_package),
                                                 context.getString(
-                                                    R.string.mobile_network_settings_class));
+                                                    R.string.sims_settings_class));
                                     intent.setComponent(mobileNetworkSettingsComponent);
-                                    context.startActivity(intent);
+                                    context.startActivityAsUser(intent, UserHandle.CURRENT);
                                 }
                             };
                     Dialog dialog = builder.setMessage(message)
@@ -4807,8 +4824,12 @@
             mSatelliteSOSMessageRecommender = new SatelliteSOSMessageRecommender(phone.getContext(),
                     phone.getContext().getMainLooper());
         }
+
+        String number = connection.getAddress().getSchemeSpecificPart();
+        final boolean isTestEmergencyNumber = isEmergencyNumberTestNumber(number);
+
         connection.addTelephonyConnectionListener(mEmergencyConnectionSatelliteListener);
-        mSatelliteSOSMessageRecommender.onEmergencyCallStarted(connection);
+        mSatelliteSOSMessageRecommender.onEmergencyCallStarted(connection, isTestEmergencyNumber);
         mSatelliteSOSMessageRecommender.onEmergencyCallConnectionStateChanged(
                 connection.getTelecomCallId(), connection.STATE_DIALING);
     }
diff --git a/src/com/android/services/telephony/domainselection/NormalCallDomainSelector.java b/src/com/android/services/telephony/domainselection/NormalCallDomainSelector.java
index 37813e3..a7ed708 100644
--- a/src/com/android/services/telephony/domainselection/NormalCallDomainSelector.java
+++ b/src/com/android/services/telephony/domainselection/NormalCallDomainSelector.java
@@ -140,7 +140,10 @@
 
         if (subId == getSubId()) {
             logd("NormalCallDomainSelection triggered. Sub-id:" + subId);
-            sendEmptyMessageDelayed(MSG_WAIT_FOR_IMS_STATE_TIMEOUT, WAIT_FOR_IMS_STATE_TIMEOUT_MS);
+            if (!mReselectDomain) {
+                sendEmptyMessageDelayed(MSG_WAIT_FOR_IMS_STATE_TIMEOUT,
+                        WAIT_FOR_IMS_STATE_TIMEOUT_MS);
+            }
             post(() -> selectDomain());
         } else {
             mSelectorState = SelectorState.INACTIVE;
diff --git a/testapps/SmsManagerTestApp/src/com/android/phone/testapps/smsmanagertestapp/SmsManagerTestApp.java b/testapps/SmsManagerTestApp/src/com/android/phone/testapps/smsmanagertestapp/SmsManagerTestApp.java
index cc3769e..d599a86 100644
--- a/testapps/SmsManagerTestApp/src/com/android/phone/testapps/smsmanagertestapp/SmsManagerTestApp.java
+++ b/testapps/SmsManagerTestApp/src/com/android/phone/testapps/smsmanagertestapp/SmsManagerTestApp.java
@@ -184,7 +184,7 @@
         intent.setComponent(SETTINGS_SUB_PICK_ACTIVITY);
         intent.putExtra(DIALOG_TYPE_KEY, SMS_PICK);
         try {
-            startActivity(intent, null);
+            startActivity(intent);
         } catch (ActivityNotFoundException anfe) {
             // If Settings is not installed, only log the error as we do not want to break
             // legacy applications.
diff --git a/testapps/TestSatelliteApp/res/layout/activity_Datagram.xml b/testapps/TestSatelliteApp/res/layout/activity_Datagram.xml
index 9e53f41..ba61328 100644
--- a/testapps/TestSatelliteApp/res/layout/activity_Datagram.xml
+++ b/testapps/TestSatelliteApp/res/layout/activity_Datagram.xml
@@ -15,12 +15,14 @@
   ~ limitations under the License
   -->
 
-<LinearLayout
+<ScrollView
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical"
     android:gravity="center"
+    android:paddingTop="10dp"
+    android:paddingBottom="10dp"
     android:paddingLeft="4dp">
 
     <LinearLayout
@@ -125,4 +127,4 @@
             android:textColor="@android:color/holo_blue_light"
             android:textSize="15dp" />
     </LinearLayout>
-</LinearLayout>
+</ScrollView>
diff --git a/testapps/TestSatelliteApp/res/layout/activity_MultipleSendReceive.xml b/testapps/TestSatelliteApp/res/layout/activity_MultipleSendReceive.xml
index 3632ecb..c81eb3b 100644
--- a/testapps/TestSatelliteApp/res/layout/activity_MultipleSendReceive.xml
+++ b/testapps/TestSatelliteApp/res/layout/activity_MultipleSendReceive.xml
@@ -15,12 +15,14 @@
   ~ limitations under the License
   -->
 
-<LinearLayout
+<ScrollView
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical"
     android:gravity="center"
+    android:paddingTop="10dp"
+    android:paddingBottom="10dp"
     android:paddingLeft="4dp">
 
     <LinearLayout
@@ -95,4 +97,4 @@
             android:layout_centerVertical="true"
             android:textSize="15dp" />
     </LinearLayout>
-</LinearLayout>
+</ScrollView>
diff --git a/testapps/TestSatelliteApp/res/layout/activity_NbIotSatellite.xml b/testapps/TestSatelliteApp/res/layout/activity_NbIotSatellite.xml
index c33522e..fef4292 100644
--- a/testapps/TestSatelliteApp/res/layout/activity_NbIotSatellite.xml
+++ b/testapps/TestSatelliteApp/res/layout/activity_NbIotSatellite.xml
@@ -15,79 +15,86 @@
   ~ limitations under the License
   -->
 
-<LinearLayout
+<ScrollView
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical"
     android:gravity="center"
-    android:paddingStart="4dp"
-    android:paddingEnd="4dp">
+    android:paddingTop="10dp"
+    android:paddingBottom="10dp"
+    android:paddingLeft="4dp">
 
-    <TextView
-        android:layout_width="wrap_content"
-        android:layout_height="0dp"
-        android:layout_weight="0"
-        android:textColor="@android:color/holo_blue_dark"
-        android:textSize="20sp"
-        android:text="@string/NbIotSatellite"/>
-    <Button
-        android:id="@+id/testRegisterForSupportedStateChanged"
+    <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
-        android:paddingStart="4dp"
-        android:paddingEnd="4dp"
-        android:text="@string/testRegisterForSupportedStateChanged"/>
-    <Button
-        android:id="@+id/testUnregisterForSupportedStateChanged"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:paddingStart="4dp"
-        android:paddingEnd="4dp"
-        android:text="@string/testUnregisterForSupportedStateChanged"/>
-    <Button
-        android:id="@+id/testRequestIsSupported"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:paddingStart="4dp"
-        android:paddingEnd="4dp"
-        android:text="@string/testRequestIsSupported"/>
-     <Button
-        android:id="@+id/reportSatelliteSupportedFromModem"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:paddingStart="4dp"
-        android:paddingEnd="4dp"
-        android:text="@string/reportSatelliteSupportedFromModem"/>
-    <Button
-        android:id="@+id/reportSatelliteNotSupportedFromModem"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:paddingStart="4dp"
-        android:paddingEnd="4dp"
-        android:text="@string/reportSatelliteNotSupportedFromModem"/>
-    <Button
-        android:id="@+id/showCurrentSatelliteSupportedStated"
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:paddingStart="4dp"
-        android:paddingEnd="4dp"
-        android:text="@string/showCurrentSatelliteSupportedStated"/>
-    <Button
-        android:id="@+id/Back"
-        android:onClick="Back"
-        android:textColor="@android:color/holo_blue_dark"
-        android:layout_marginTop="100dp"
-        android:layout_gravity="center"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:paddingStart="4dp"
-        android:paddingEnd="4dp"
-        android:text="@string/Back"/>
-    <TextView
-        android:id="@+id/text_id"
-        android:layout_width="300dp"
-        android:layout_height="200dp"
-        android:textColor="@android:color/holo_blue_light"
-        android:textSize="15sp" />
-</LinearLayout>
+        android:orientation="vertical">
+
+        <TextView
+            android:layout_width="wrap_content"
+            android:layout_height="0dp"
+            android:layout_weight="0"
+            android:textColor="@android:color/holo_blue_dark"
+            android:textSize="20sp"
+            android:text="@string/NbIotSatellite"/>
+        <Button
+            android:id="@+id/testRegisterForSupportedStateChanged"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:paddingStart="4dp"
+            android:paddingEnd="4dp"
+            android:text="@string/testRegisterForSupportedStateChanged"/>
+        <Button
+            android:id="@+id/testUnregisterForSupportedStateChanged"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:paddingStart="4dp"
+            android:paddingEnd="4dp"
+            android:text="@string/testUnregisterForSupportedStateChanged"/>
+        <Button
+            android:id="@+id/testRequestIsSupported"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:paddingStart="4dp"
+            android:paddingEnd="4dp"
+            android:text="@string/testRequestIsSupported"/>
+         <Button
+            android:id="@+id/reportSatelliteSupportedFromModem"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:paddingStart="4dp"
+            android:paddingEnd="4dp"
+            android:text="@string/reportSatelliteSupportedFromModem"/>
+        <Button
+            android:id="@+id/reportSatelliteNotSupportedFromModem"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:paddingStart="4dp"
+            android:paddingEnd="4dp"
+            android:text="@string/reportSatelliteNotSupportedFromModem"/>
+        <Button
+            android:id="@+id/showCurrentSatelliteSupportedStated"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:paddingStart="4dp"
+            android:paddingEnd="4dp"
+            android:text="@string/showCurrentSatelliteSupportedStated"/>
+        <Button
+            android:id="@+id/Back"
+            android:onClick="Back"
+            android:textColor="@android:color/holo_blue_dark"
+            android:layout_marginTop="100dp"
+            android:layout_gravity="center"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:paddingStart="4dp"
+            android:paddingEnd="4dp"
+            android:text="@string/Back"/>
+        <TextView
+            android:id="@+id/text_id"
+            android:layout_width="300dp"
+            android:layout_height="200dp"
+            android:textColor="@android:color/holo_blue_light"
+            android:textSize="15sp" />
+    </LinearLayout>
+</ScrollView>
diff --git a/testapps/TestSatelliteApp/res/layout/activity_Provisioning.xml b/testapps/TestSatelliteApp/res/layout/activity_Provisioning.xml
index da5105d..afcc706 100644
--- a/testapps/TestSatelliteApp/res/layout/activity_Provisioning.xml
+++ b/testapps/TestSatelliteApp/res/layout/activity_Provisioning.xml
@@ -15,12 +15,14 @@
   ~ limitations under the License
   -->
 
-<LinearLayout
+<ScrollView
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical"
     android:gravity="center"
+    android:paddingTop="10dp"
+    android:paddingBottom="10dp"
     android:paddingLeft="4dp">
 
     <LinearLayout
@@ -90,4 +92,4 @@
             android:layout_centerVertical="true"
             android:textSize="15dp" />
     </LinearLayout>
-</LinearLayout>
+</ScrollView>
diff --git a/testapps/TestSatelliteApp/res/layout/activity_SatelliteControl.xml b/testapps/TestSatelliteApp/res/layout/activity_SatelliteControl.xml
index 9bb8d3f..2ace0ad 100644
--- a/testapps/TestSatelliteApp/res/layout/activity_SatelliteControl.xml
+++ b/testapps/TestSatelliteApp/res/layout/activity_SatelliteControl.xml
@@ -21,6 +21,8 @@
     android:layout_height="wrap_content"
     android:orientation="vertical"
     android:gravity="center"
+    android:paddingTop="10dp"
+    android:paddingBottom="10dp"
     android:paddingLeft="4dp">
 
     <LinearLayout
@@ -36,11 +38,17 @@
             android:textSize="20dp"
             android:text="Satellite Control APIs"/>
         <Button
-            android:id="@+id/enableSatellite"
+            android:id="@+id/enableSatelliteDemoMode"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:paddingRight="4dp"
-            android:text="@string/enableSatellite"/>
+            android:text="@string/enableSatelliteDemoMode"/>
+        <Button
+            android:id="@+id/enableSatelliteRealMode"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:paddingRight="4dp"
+            android:text="@string/enableSatelliteRealMode"/>
         <Button
             android:id="@+id/disableSatellite"
             android:layout_width="match_parent"
diff --git a/testapps/TestSatelliteApp/res/layout/activity_SatelliteTestApp.xml b/testapps/TestSatelliteApp/res/layout/activity_SatelliteTestApp.xml
index 5ba7946..26b45e3 100644
--- a/testapps/TestSatelliteApp/res/layout/activity_SatelliteTestApp.xml
+++ b/testapps/TestSatelliteApp/res/layout/activity_SatelliteTestApp.xml
@@ -15,11 +15,14 @@
   ~ limitations under the License
   -->
 
-<LinearLayout
+<ScrollView
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical"
+    android:gravity="center"
+    android:paddingTop="10dp"
+    android:paddingBottom="10dp"
     android:paddingLeft="4dp">
 
     <LinearLayout
@@ -79,4 +82,4 @@
             android:paddingEnd="4dp"
             android:text="@string/TestSatelliteWrapper"/>
     </LinearLayout>
-</LinearLayout>
+</ScrollView>
diff --git a/testapps/TestSatelliteApp/res/layout/activity_SendReceive.xml b/testapps/TestSatelliteApp/res/layout/activity_SendReceive.xml
index 6490e5d..4ac3483 100644
--- a/testapps/TestSatelliteApp/res/layout/activity_SendReceive.xml
+++ b/testapps/TestSatelliteApp/res/layout/activity_SendReceive.xml
@@ -15,12 +15,14 @@
   ~ limitations under the License
   -->
 
-<LinearLayout
+<ScrollView
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical"
     android:gravity="center"
+    android:paddingTop="10dp"
+    android:paddingBottom="10dp"
     android:paddingLeft="4dp">
 
     <LinearLayout
@@ -94,4 +96,4 @@
             android:layout_centerVertical="true"
             android:textSize="15dp" />
     </LinearLayout>
-</LinearLayout>
+</ScrollView>
diff --git a/testapps/TestSatelliteApp/res/layout/activity_TestSatelliteWrapper.xml b/testapps/TestSatelliteApp/res/layout/activity_TestSatelliteWrapper.xml
index 39a4bd6..f4ed82e 100644
--- a/testapps/TestSatelliteApp/res/layout/activity_TestSatelliteWrapper.xml
+++ b/testapps/TestSatelliteApp/res/layout/activity_TestSatelliteWrapper.xml
@@ -14,10 +14,16 @@
   ~ See the License for the specific language governing permissions and
   ~ limitations under the License
   -->
+
 <ScrollView
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
-    android:layout_height="match_parent">
+    android:layout_height="wrap_content"
+    android:orientation="vertical"
+    android:gravity="center"
+    android:paddingTop="10dp"
+    android:paddingBottom="10dp"
+    android:paddingLeft="4dp">
 
     <LinearLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
@@ -203,5 +209,4 @@
             android:layout_centerVertical="true"
             android:textSize="8dp" />
     </LinearLayout>
-
-</ScrollView>
\ No newline at end of file
+</ScrollView>
diff --git a/testapps/TestSatelliteApp/res/values/donottranslate_strings.xml b/testapps/TestSatelliteApp/res/values/donottranslate_strings.xml
index 728576a..b0aa492 100644
--- a/testapps/TestSatelliteApp/res/values/donottranslate_strings.xml
+++ b/testapps/TestSatelliteApp/res/values/donottranslate_strings.xml
@@ -23,7 +23,8 @@
     <string name="SendReceive">Send and Receive datagrams</string>
     <string name="NbIotSatellite">NB IoT Satellite modem interface test</string>
 
-    <string name="enableSatellite">enableSatellite</string>
+    <string name="enableSatelliteRealMode">enableSatellite Real Mode</string>
+    <string name="enableSatelliteDemoMode">enableSatellite Demo Mode</string>
     <string name="disableSatellite">disableSatellite</string>
     <string name="requestIsSatelliteEnabled">requestIsSatelliteEnabled</string>
     <string name="requestIsDemoModeEnabled">requestIsDemoModeEnabled</string>
diff --git a/testapps/TestSatelliteApp/src/com/android/phone/testapps/satellitetestapp/SatelliteControl.java b/testapps/TestSatelliteApp/src/com/android/phone/testapps/satellitetestapp/SatelliteControl.java
index 379fc74..5d47929 100644
--- a/testapps/TestSatelliteApp/src/com/android/phone/testapps/satellitetestapp/SatelliteControl.java
+++ b/testapps/TestSatelliteApp/src/com/android/phone/testapps/satellitetestapp/SatelliteControl.java
@@ -58,8 +58,10 @@
         mSubscriptionManager = getSystemService(SubscriptionManager.class);
 
         setContentView(R.layout.activity_SatelliteControl);
-        findViewById(R.id.enableSatellite)
-                .setOnClickListener(this::enableSatelliteApp);
+        findViewById(R.id.enableSatelliteDemoMode)
+                .setOnClickListener(v -> enableSatelliteApp(/* isDemoMode */ true));
+        findViewById(R.id.enableSatelliteRealMode)
+                .setOnClickListener(v -> enableSatelliteApp(/* isDemoMode */ false));
         findViewById(R.id.disableSatellite)
                 .setOnClickListener(this::disableSatelliteApp);
         findViewById(R.id.requestIsSatelliteEnabled)
@@ -100,10 +102,12 @@
         });
     }
 
-    private void enableSatelliteApp(View view) {
+    private void enableSatelliteApp(boolean isDemoMode) {
         LinkedBlockingQueue<Integer> error = new LinkedBlockingQueue<>(1);
         mSatelliteManager.requestEnabled(
-                new EnableRequestAttributes.Builder(true).setDemoMode(true).setEmergencyMode(true)
+                new EnableRequestAttributes.Builder(true)
+                        .setDemoMode(isDemoMode)
+                        .setEmergencyMode(true)
                         .build(), Runnable::run, error::offer);
         TextView textView = findViewById(R.id.text_id);
         try {
diff --git a/tests/src/com/android/TestContext.java b/tests/src/com/android/TestContext.java
index a96ce2e..e464ad5 100644
--- a/tests/src/com/android/TestContext.java
+++ b/tests/src/com/android/TestContext.java
@@ -33,6 +33,7 @@
 import android.os.Looper;
 import android.os.PersistableBundle;
 import android.os.Process;
+import android.os.UserHandle;
 import android.os.UserManager;
 import android.telecom.TelecomManager;
 import android.telephony.CarrierConfigManager;
@@ -112,6 +113,11 @@
     }
 
     @Override
+    public void startActivityAsUser(Intent intent, UserHandle user) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
     public void sendBroadcast(Intent intent) {
         mIntent = intent;
     }
diff --git a/tests/src/com/android/phone/LocationAccessPolicyTest.java b/tests/src/com/android/phone/LocationAccessPolicyTest.java
index 58e7fbd..551c2cb 100644
--- a/tests/src/com/android/phone/LocationAccessPolicyTest.java
+++ b/tests/src/com/android/phone/LocationAccessPolicyTest.java
@@ -225,6 +225,8 @@
         try {
             when(mPackageManager.getApplicationInfo(anyString(), anyInt()))
                     .thenReturn(fakeAppInfo);
+            when(mPackageManager.getApplicationInfoAsUser(anyString(), anyInt(),
+                    any(UserHandle.class))).thenReturn(fakeAppInfo);
         } catch (Exception e) {
             // this is a formality
         }
diff --git a/tests/src/com/android/phone/PhoneInterfaceManagerTest.java b/tests/src/com/android/phone/PhoneInterfaceManagerTest.java
index 2d46c80..7464ba2 100644
--- a/tests/src/com/android/phone/PhoneInterfaceManagerTest.java
+++ b/tests/src/com/android/phone/PhoneInterfaceManagerTest.java
@@ -21,6 +21,7 @@
 import static org.junit.Assert.assertThrows;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.eq;
@@ -41,6 +42,7 @@
 import android.content.pm.PackageManager;
 import android.content.res.Resources;
 import android.os.Build;
+import android.os.UserHandle;
 import android.permission.flags.Flags;
 import android.platform.test.flag.junit.SetFlagsRule;
 import android.telephony.RadioAccessFamily;
@@ -111,6 +113,9 @@
         // alive on a test devices. You must use the spy to mock behavior. Mocks stemming from the
         // passed context will remain unused.
         mPhoneInterfaceManager = spy(PhoneInterfaceManager.init(mPhoneGlobals, mFeatureFlags));
+        doReturn(mPhoneGlobals).when(mPhoneGlobals).getBaseContext();
+        doReturn(mPhoneGlobals).when(mPhoneGlobals).createContextAsUser(
+                any(UserHandle.class), anyInt());
         doReturn(mSubscriptionManagerService).when(mPhoneInterfaceManager)
                 .getSubscriptionManagerService();
         TelephonyManager.setupISubForTest(mSubscriptionManagerService);
@@ -123,6 +128,7 @@
         // and disabled enforce_telephony_feature_mapping_for_public_apis feature flag
         mPhoneInterfaceManager.setFeatureFlags(mFeatureFlags);
         doReturn(false).when(mFeatureFlags).enforceTelephonyFeatureMappingForPublicApis();
+        doReturn(true).when(mFeatureFlags).hsumPackageManager();
         mPhoneInterfaceManager.setPackageManager(mPackageManager);
         doReturn(true).when(mPackageManager).hasSystemFeature(anyString());
 
diff --git a/tests/src/com/android/phone/euicc/EuiccUiDispatcherActivityTest.java b/tests/src/com/android/phone/euicc/EuiccUiDispatcherActivityTest.java
index 817220c..1bd118a 100644
--- a/tests/src/com/android/phone/euicc/EuiccUiDispatcherActivityTest.java
+++ b/tests/src/com/android/phone/euicc/EuiccUiDispatcherActivityTest.java
@@ -24,6 +24,7 @@
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
 import android.service.euicc.EuiccService;
+import android.telephony.TelephonyManager;
 import android.telephony.euicc.EuiccManager;
 
 import androidx.test.InstrumentationRegistry;
@@ -50,6 +51,7 @@
 
     @Mock private Context mMockContext;
     @Mock private EuiccManager mMockEuiccManager;
+    @Mock private TelephonyManager mTelephonyManager;
     private ActivityInfo mActivityInfo = ACTIVITY_INFO;
     private Intent mIntent = MANAGE_INTENT;
     private EuiccUiDispatcherActivity mActivity;
@@ -59,6 +61,8 @@
         MockitoAnnotations.initMocks(this);
         when(mMockEuiccManager.isEnabled()).thenReturn(true);
         when(mMockContext.getSystemService(Context.EUICC_SERVICE)).thenReturn(mMockEuiccManager);
+        when(mMockContext.getSystemService(Context.TELEPHONY_SERVICE))
+                .thenReturn(mTelephonyManager);
         InstrumentationRegistry.getInstrumentation().runOnMainSync(
                 new Runnable() {
                     @Override
diff --git a/tests/src/com/android/phone/satellite/accesscontrol/SatelliteAccessControllerTest.java b/tests/src/com/android/phone/satellite/accesscontrol/SatelliteAccessControllerTest.java
index 9e5d9e7..3d2c953 100644
--- a/tests/src/com/android/phone/satellite/accesscontrol/SatelliteAccessControllerTest.java
+++ b/tests/src/com/android/phone/satellite/accesscontrol/SatelliteAccessControllerTest.java
@@ -34,6 +34,7 @@
 import static com.android.phone.satellite.accesscontrol.SatelliteAccessController.DEFAULT_DELAY_MINUTES_BEFORE_VALIDATING_POSSIBLE_CHANGE_IN_ALLOWED_REGION;
 import static com.android.phone.satellite.accesscontrol.SatelliteAccessController.DEFAULT_THROTTLE_INTERVAL_FOR_LOCATION_QUERY_MINUTES;
 import static com.android.phone.satellite.accesscontrol.SatelliteAccessController.EVENT_CONFIG_DATA_UPDATED;
+import static com.android.phone.satellite.accesscontrol.SatelliteAccessController.EVENT_WAIT_FOR_CURRENT_LOCATION_TIMEOUT;
 import static com.android.phone.satellite.accesscontrol.SatelliteAccessController.GOOGLE_US_SAN_SAT_S2_FILE_NAME;
 import static com.android.phone.satellite.accesscontrol.SatelliteAccessController.DEFAULT_MAX_RETRY_COUNT_FOR_VALIDATING_POSSIBLE_CHANGE_IN_ALLOWED_REGION;
 
@@ -369,6 +370,49 @@
     }
 
     @Test
+    public void testOnCurrentLocationNotAvailable() throws Exception {
+        // Verify the cache is used when the location is null and the cache is valid and true.
+        mSatelliteAccessControllerUT.elapsedRealtimeNanos =
+                ALLOWED_STATE_CACHE_VALID_DURATION_NANOS - 1;
+        mSatelliteAccessControllerUT
+                .setIsSatelliteCommunicationAllowedForCurrentLocationCache("cache_allowed");
+        mSatelliteAccessControllerUT.setLocationRequestCancellationSignalAsNull(false);
+
+        sendCurrentLocationTimeoutEvent();
+        assertTrue(mSatelliteAccessControllerUT.isCurrentSatelliteAllowedState());
+
+        // Verify the cache is used when the location is null and the cache is valid and false.
+        mSatelliteAccessControllerUT
+                .setIsSatelliteCommunicationAllowedForCurrentLocationCache("cache_not_allowed");
+        mSatelliteAccessControllerUT.setLocationRequestCancellationSignalAsNull(false);
+
+        sendCurrentLocationTimeoutEvent();
+        assertFalse(mSatelliteAccessControllerUT.isCurrentSatelliteAllowedState());
+
+        // Verify the result code is SATELLITE_RESULT_LOCATION_NOT_AVAILABLE
+        // and allowedState is false when the location is null and the cache is expired
+        mSatelliteAccessControllerUT.elapsedRealtimeNanos =
+                ALLOWED_STATE_CACHE_VALID_DURATION_NANOS + 1;
+        Iterator<ResultReceiver> mockIterator = mock(Iterator.class);
+        doReturn(mockIterator).when(mMockSatelliteAllowResultReceivers).iterator();
+        doReturn(true, false).when(mockIterator).hasNext();
+        doNothing().when(mMockSatelliteAllowResultReceivers).clear();
+        doReturn(mMockSatelliteSupportedResultReceiver).when(mockIterator).next();
+        replaceInstance(SatelliteAccessController.class, "mSatelliteAllowResultReceivers",
+                mSatelliteAccessControllerUT, mMockSatelliteAllowResultReceivers);
+        mSatelliteAccessControllerUT.setIsSatelliteCommunicationAllowedForCurrentLocationCache(
+                "cache_clear_and_not_allowed");
+        mSatelliteAccessControllerUT.setLocationRequestCancellationSignalAsNull(false);
+
+        sendCurrentLocationTimeoutEvent();
+        verify(mMockSatelliteSupportedResultReceiver)
+                .send(mResultCodeIntCaptor.capture(), any());
+        assertEquals(Integer.valueOf(SATELLITE_RESULT_LOCATION_NOT_AVAILABLE),
+                mResultCodeIntCaptor.getValue());
+        assertFalse(mSatelliteAccessControllerUT.isCurrentSatelliteAllowedState());
+    }
+
+    @Test
     public void testIsSatelliteAccessAllowedForLocation() {
         when(mMockFeatureFlags.oemEnabledSatelliteFlag()).thenReturn(true);
 
@@ -463,7 +507,7 @@
                 .thenReturn(List.of(TEST_SATELLITE_COUNTRY_CODE_US));
         mSatelliteAccessControllerUT.loadOverlayConfigs(mMockContext);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         verify(mMockCachedAccessRestrictionMap, times(0)).containsKey(any());
         assertFalse(mQueriedSatelliteAllowed);
@@ -474,7 +518,7 @@
         when(mMockCountryDetector.getCurrentNetworkCountryIso()).thenReturn(List.of());
         mSatelliteAccessControllerUT.loadOverlayConfigs(mMockContext);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         verify(mMockCachedAccessRestrictionMap, times(1)).containsKey(any());
         assertTrue(mQueriedSatelliteAllowed);
@@ -491,7 +535,7 @@
                 .thenReturn(List.of(TEST_SATELLITE_COUNTRY_CODES));
         mSatelliteAccessControllerUT.loadOverlayConfigs(mMockContext);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         verify(mMockCachedAccessRestrictionMap, times(1)).containsKey(any());
         assertTrue(mQueriedSatelliteAllowed);
@@ -503,7 +547,7 @@
                 .thenReturn(List.of(TEST_SATELLITE_COUNTRY_CODE_US));
         mSatelliteAccessControllerUT.loadOverlayConfigs(mMockContext);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         verify(mMockCachedAccessRestrictionMap, times(1)).containsKey(any());
         assertTrue(mQueriedSatelliteAllowed);
@@ -515,7 +559,7 @@
                 List.of(TEST_SATELLITE_COUNTRY_CODE_US, TEST_SATELLITE_COUNTRY_CODE_KR));
         mSatelliteAccessControllerUT.loadOverlayConfigs(mMockContext);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         verify(mMockCachedAccessRestrictionMap, times(1)).containsKey(any());
         assertTrue(mQueriedSatelliteAllowed);
@@ -526,7 +570,7 @@
         when(mMockCountryDetector.getCurrentNetworkCountryIso()).thenReturn(List.of());
         mSatelliteAccessControllerUT.loadOverlayConfigs(mMockContext);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         verify(mMockCachedAccessRestrictionMap, times(1)).containsKey(any());
         assertTrue(mQueriedSatelliteAllowed);
@@ -538,7 +582,7 @@
                 List.of(TEST_SATELLITE_COUNTRY_CODE_KR, TEST_SATELLITE_COUNTRY_CODE_JP));
         mSatelliteAccessControllerUT.loadOverlayConfigs(mMockContext);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         verify(mMockCachedAccessRestrictionMap, times(0)).containsKey(any());
         assertFalse(mQueriedSatelliteAllowed);
@@ -550,7 +594,7 @@
                 .thenReturn(List.of(TEST_SATELLITE_COUNTRY_CODE_KR));
         mSatelliteAccessControllerUT.loadOverlayConfigs(mMockContext);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         verify(mMockCachedAccessRestrictionMap, times(0)).containsKey(any());
         assertFalse(mQueriedSatelliteAllowed);
@@ -572,7 +616,7 @@
                 .thenReturn(List.of(TEST_SATELLITE_COUNTRY_CODE_US));
         mSatelliteAccessControllerUT.loadOverlayConfigs(mMockContext);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         verify(mMockCachedAccessRestrictionMap, times(1)).containsKey(any());
         assertTrue(mQueriedSatelliteAllowed);
@@ -589,7 +633,7 @@
                 .thenReturn(List.of(TEST_SATELLITE_COUNTRY_CODES_EMPTY));
         mSatelliteAccessControllerUT.loadOverlayConfigs(mMockContext);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         verify(mMockCachedAccessRestrictionMap, times(1)).containsKey(any());
         assertTrue(mQueriedSatelliteAllowed);
@@ -601,7 +645,7 @@
                 List.of(TEST_SATELLITE_COUNTRY_CODE_US, TEST_SATELLITE_COUNTRY_CODE_JP));
         mSatelliteAccessControllerUT.loadOverlayConfigs(mMockContext);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         verify(mMockCachedAccessRestrictionMap, times(1)).containsKey(any());
         assertTrue(mQueriedSatelliteAllowed);
@@ -613,7 +657,7 @@
                 .thenReturn(List.of(TEST_SATELLITE_COUNTRY_CODE_JP));
         mSatelliteAccessControllerUT.loadOverlayConfigs(mMockContext);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         verify(mMockCachedAccessRestrictionMap, times(1)).containsKey(any());
         assertTrue(mQueriedSatelliteAllowed);
@@ -625,7 +669,7 @@
                 .thenReturn(List.of(TEST_SATELLITE_COUNTRY_CODE_US));
         mSatelliteAccessControllerUT.loadOverlayConfigs(mMockContext);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         verify(mMockCachedAccessRestrictionMap, times(0)).containsKey(any());
         assertFalse(mQueriedSatelliteAllowed);
@@ -636,7 +680,7 @@
         // OEM-enabled satellite is not supported
         when(mMockFeatureFlags.oemEnabledSatelliteFlag()).thenReturn(false);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         assertTrue(waitForRequestIsSatelliteAllowedForCurrentLocationResult(
                 mSatelliteAllowedSemaphore, 1));
@@ -649,7 +693,7 @@
         setUpResponseForRequestIsSatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
         clearAllInvocations();
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         assertTrue(waitForRequestIsSatelliteAllowedForCurrentLocationResult(
                 mSatelliteAllowedSemaphore, 1));
@@ -660,7 +704,7 @@
         setUpResponseForRequestIsSatelliteSupported(false, SATELLITE_RESULT_MODEM_ERROR);
         clearAllInvocations();
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         assertTrue(waitForRequestIsSatelliteAllowedForCurrentLocationResult(
                 mSatelliteAllowedSemaphore, 1));
@@ -677,7 +721,7 @@
         when(mMockLocation0.getElapsedRealtimeNanos()).thenReturn(2L);
         when(mMockLocation1.getElapsedRealtimeNanos()).thenReturn(0L);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         assertTrue(
                 mSatelliteAccessControllerUT.isKeepOnDeviceAccessControllerResourcesTimerStarted());
@@ -715,7 +759,7 @@
         when(mMockLocation0.getElapsedRealtimeNanos()).thenReturn(0L);
         when(mMockLocation1.getElapsedRealtimeNanos()).thenReturn(0L);
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         assertFalse(
                 mSatelliteAccessControllerUT.isKeepOnDeviceAccessControllerResourcesTimerStarted());
@@ -746,7 +790,7 @@
         when(mMockCountryDetector.getCachedLocationCountryIsoInfo()).thenReturn(new Pair<>("", 0L));
         when(mMockCountryDetector.getCachedNetworkCountryIsoInfo()).thenReturn(new HashMap<>());
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         assertFalse(
                 mSatelliteAccessControllerUT.isKeepOnDeviceAccessControllerResourcesTimerStarted());
@@ -779,7 +823,7 @@
         when(mMockLocation1.getElapsedRealtimeNanos()).thenReturn(0L);
         doReturn(false).when(mMockLocationManager).isLocationEnabled();
         mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
-                mSatelliteAllowedReceiver);
+                mSatelliteAllowedReceiver, false);
         mTestableLooper.processAllMessages();
         verify(mMockLocationManager, never()).getCurrentLocation(anyString(),
                 any(LocationRequest.class), any(CancellationSignal.class), any(Executor.class),
@@ -1056,8 +1100,9 @@
         // In emergency case,
         // verify if the location manager get FUSED provider and ignore location settings
         doReturn(true).when(mMockTelecomManager).isInEmergencyCall();
-        mSatelliteAccessControllerUT.setLocationRequestCancellationSignalAsNull();
-        mSatelliteAccessControllerUT.queryCurrentLocation();
+        mSatelliteAccessControllerUT.setLocationRequestCancellationSignalAsNull(true);
+        mSatelliteAccessControllerUT.elapsedRealtimeNanos = TEST_LOCATION_FRESH_DURATION_NANOS + 1;
+        mSatelliteAccessControllerUT.checkSatelliteAccessRestrictionUsingGPS();
 
         verify(mMockLocationManager, times(1))
                 .getCurrentLocation(mLocationProviderStringCaptor.capture(),
@@ -1072,8 +1117,9 @@
         doReturn(false).when(mMockPhone).isInEcm();
         doReturn(false).when(mMockPhone2).isInEcm();
         doReturn(false).when(mMockSatelliteController).isInEmergencyMode();
-        mSatelliteAccessControllerUT.setLocationRequestCancellationSignalAsNull();
-        mSatelliteAccessControllerUT.queryCurrentLocation();
+        doReturn(true).when(mMockLocationManager).isLocationEnabled();
+        mSatelliteAccessControllerUT.setLocationRequestCancellationSignalAsNull(true);
+        mSatelliteAccessControllerUT.checkSatelliteAccessRestrictionUsingGPS();
 
         verify(mMockLocationManager, times(1))
                 .getCurrentLocation(mLocationProviderStringCaptor.capture(),
@@ -1159,6 +1205,43 @@
                 mResultDataBundleCaptor.getValue().getBoolean(KEY_SATELLITE_COMMUNICATION_ALLOWED));
     }
 
+    @Test
+    public void testRequestIsCommunicationAllowedForCurrentLocationWithEnablingSatellite() {
+        // Set non-emergency case
+        when(mMockFeatureFlags.oemEnabledSatelliteFlag()).thenReturn(true);
+        setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
+        setUpResponseForRequestIsSatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
+        when(mMockCountryDetector.getCurrentNetworkCountryIso()).thenReturn(EMPTY_STRING_LIST);
+        doReturn(false).when(mMockTelecomManager).isInEmergencyCall();
+        doReturn(false).when(mMockPhone).isInEcm();
+        doReturn(false).when(mMockPhone2).isInEcm();
+        doReturn(false).when(mMockSatelliteController).isInEmergencyMode();
+        doReturn(true).when(mMockLocationManager).isLocationEnabled();
+        mSatelliteAccessControllerUT.setLocationRequestCancellationSignalAsNull(true);
+        mSatelliteAccessControllerUT.elapsedRealtimeNanos = TEST_LOCATION_FRESH_DURATION_NANOS + 1;
+
+        // Invoking requestIsCommunicationAllowedForCurrentLocation(resultReceiver, "false");
+        // verify that mLocationManager.isLocationEnabled() is invoked
+        mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
+                mSatelliteAllowedReceiver, false);
+        mTestableLooper.processAllMessages();
+        verify(mMockLocationManager, times(1)).isLocationEnabled();
+        verify(mMockLocationManager, times(1)).getCurrentLocation(anyString(),
+                any(LocationRequest.class), any(CancellationSignal.class), any(Executor.class),
+                any(Consumer.class));
+
+        // Invoking requestIsCommunicationAllowedForCurrentLocation(resultReceiver, "true");
+        // verify that mLocationManager.isLocationEnabled() is not invoked
+        clearInvocations(mMockLocationManager);
+        mSatelliteAccessControllerUT.requestIsCommunicationAllowedForCurrentLocation(
+                mSatelliteAllowedReceiver, true);
+        mTestableLooper.processAllMessages();
+        verify(mMockLocationManager, times(1)).isLocationEnabled();
+        verify(mMockLocationManager, never()).getCurrentLocation(anyString(),
+                any(LocationRequest.class), any(CancellationSignal.class), any(Executor.class),
+                any(Consumer.class));
+    }
+
     private void sendSatelliteCommunicationAllowedEvent() {
         Pair<Integer, ResultReceiver> requestPair =
                 new Pair<>(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID,
@@ -1178,6 +1261,13 @@
         mTestableLooper.processAllMessages();
     }
 
+    private void sendCurrentLocationTimeoutEvent() {
+        Message msg = mSatelliteAccessControllerUT
+                .obtainMessage(EVENT_WAIT_FOR_CURRENT_LOCATION_TIMEOUT);
+        msg.sendToTarget();
+        mTestableLooper.processAllMessages();
+    }
+
     private void sendCommandValidateCountryCodeChangeEvent(Context context) {
         Message msg = mSatelliteAccessControllerUT.obtainMessage(EVENT_COUNTRY_CODE_CHANGED);
         msg.obj = new AsyncResult(context, SATELLITE_RESULT_SUCCESS, null);
@@ -1343,9 +1433,15 @@
             return mLocationModeChangedBroadcastReceiver;
         }
 
-        public void setLocationRequestCancellationSignalAsNull() {
+        public void setLocationRequestCancellationSignalAsNull(boolean isNull) {
             synchronized (mLock) {
-                mLocationRequestCancellationSignal = null;
+                mLocationRequestCancellationSignal = isNull ? null : new CancellationSignal();
+            }
+        }
+
+        public boolean isCurrentSatelliteAllowedState() {
+            synchronized (mSatelliteCommunicationAllowStateLock) {
+                return mCurrentSatelliteAllowedState;
             }
         }
     }
diff --git a/tests/src/com/android/phone/tests/CallDialTest.java b/tests/src/com/android/phone/tests/CallDialTest.java
index 6e78be0..cafa7f2 100644
--- a/tests/src/com/android/phone/tests/CallDialTest.java
+++ b/tests/src/com/android/phone/tests/CallDialTest.java
@@ -22,6 +22,7 @@
 import android.net.Uri;
 import android.os.Bundle;
 import android.os.RemoteException;
+import android.os.UserHandle;
 import android.telecom.PhoneAccount;
 import android.telephony.PhoneNumberUtils;
 import android.telephony.TelephonyFrameworkInitializer;
@@ -136,13 +137,13 @@
         log("==> intent: " + intent);
 
         try {
-            startActivity(intent);
+            startActivityAsUser(intent, UserHandle.CURRENT);
             Toast.makeText(this, "Starting activity...", Toast.LENGTH_SHORT).show();
         } catch (ActivityNotFoundException e) {
             Log.w(LOG_TAG, "testCall: ActivityNotFoundException for intent: " + intent);
             Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
         } catch (Exception e) {
-            Log.w(LOG_TAG, "testCall: Unexpected exception from startActivity(): " + e);
+            Log.w(LOG_TAG, "testCall: Unexpected exception from startActivityAsUser(): " + e);
             Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
         }
     }
diff --git a/tests/src/com/android/services/telephony/TelecomAccountRegistryTest.java b/tests/src/com/android/services/telephony/TelecomAccountRegistryTest.java
new file mode 100644
index 0000000..fc544b0
--- /dev/null
+++ b/tests/src/com/android/services/telephony/TelecomAccountRegistryTest.java
@@ -0,0 +1,314 @@
+/*
+ * Copyright (C) 2024 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 static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.BroadcastReceiver;
+import android.content.ContentProvider;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.Resources;
+import android.graphics.drawable.Drawable;
+import android.os.PersistableBundle;
+import android.os.UserHandle;
+import android.platform.test.flag.junit.SetFlagsRule;
+import android.telecom.PhoneAccount;
+import android.telecom.TelecomManager;
+import android.telephony.CarrierConfigManager;
+import android.telephony.ServiceState;
+import android.telephony.SubscriptionManager;
+import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener;
+import android.telephony.TelephonyCallback;
+import android.telephony.TelephonyManager;
+import android.telephony.ims.ImsManager;
+import android.testing.AndroidTestingRunner;
+import android.testing.TestableLooper;
+
+import com.android.TelephonyTestBase;
+import com.android.internal.telephony.Phone;
+import com.android.internal.telephony.PhoneConstants;
+import com.android.internal.telephony.PhoneFactory;
+import com.android.internal.telephony.flags.Flags;
+import com.android.phone.PhoneGlobals;
+import com.android.phone.PhoneInterfaceManager;
+import com.android.phone.R;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@RunWith(AndroidTestingRunner.class)
+@TestableLooper.RunWithLooper(setAsMainLooper = true)
+public class TelecomAccountRegistryTest extends TelephonyTestBase {
+
+    private static final String TAG = "TelecomAccountRegistryTest";
+    private static final int TEST_SUB_ID = 1;
+
+    @Rule
+    public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
+
+    // We need more functions that what TelephonyTestBase.mContext supports.
+    // Use a local mocked Context to make life easier.
+    @Mock Context mMockedContext;
+    @Mock TelecomManager mTelecomManager;
+    @Mock TelephonyManager mTelephonyManager;
+    @Mock ImsManager mImsManager;
+    @Mock SubscriptionManager mSubscriptionManager;
+    @Mock ContentProvider mContentProvider;
+    @Mock PhoneGlobals mPhoneGlobals;
+    @Mock Phone mPhone;
+    @Mock Resources mResources;
+    @Mock Drawable mDrawable;
+    @Mock PhoneInterfaceManager mPhoneInterfaceManager;
+
+    private TelecomAccountRegistry mTelecomAccountRegistry;
+
+    private OnSubscriptionsChangedListener mOnSubscriptionsChangedListener;
+    private TelephonyCallback mTelephonyCallback;
+    private BroadcastReceiver mUserSwitchedAndConfigChangedReceiver;
+    private BroadcastReceiver mLocaleChangedBroadcastReceiver;
+    private ContentResolver mContentResolver;
+    private Phone[] mPhones;
+    private TestableLooper mTestableLooper;
+
+    @Before
+    public void setUp() throws Exception {
+        super.setUp();
+        mSetFlagsRule.disableFlags(Flags.FLAG_DELAY_PHONE_ACCOUNT_REGISTRATION);
+        MockitoAnnotations.initMocks(this);
+
+        mPhones = new Phone[]{mPhone};
+        replaceInstance(PhoneFactory.class, "sPhones", null, mPhones);
+        replaceInstance(PhoneGlobals.class, "sMe", null, mPhoneGlobals);
+        replaceInstance(PhoneInterfaceManager.class, "sInstance", null, mPhoneInterfaceManager);
+        when(mPhone.getPhoneType()).thenReturn(PhoneConstants.PHONE_TYPE_GSM);
+        when(mPhone.getContext()).thenReturn(mMockedContext);
+        when(mPhone.getSubId()).thenReturn(TEST_SUB_ID);
+        when(mPhoneInterfaceManager.isRttEnabled(anyInt())).thenReturn(false);
+
+        when(mMockedContext.getResources()).thenReturn(mResources);
+        // Enable PSTN PhoneAccount which can place emergency call by default
+        when(mResources.getBoolean(R.bool.config_pstn_phone_accounts_enabled)).thenReturn(true);
+        when(mResources.getBoolean(R.bool.config_pstnCanPlaceEmergencyCalls)).thenReturn(true);
+        when(mResources.getDrawable(anyInt(), any())).thenReturn(mDrawable);
+        when(mDrawable.getIntrinsicWidth()).thenReturn(5);
+        when(mDrawable.getIntrinsicHeight()).thenReturn(5);
+
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putBoolean(CarrierConfigManager.KEY_SUPPORT_IMS_CONFERENCE_CALL_BOOL, false);
+        bundle.putIntArray(CarrierConfigManager.KEY_CELLULAR_SERVICE_CAPABILITIES_INT_ARRAY,
+                new int[]{
+                        SubscriptionManager.SERVICE_CAPABILITY_VOICE,
+                        SubscriptionManager.SERVICE_CAPABILITY_SMS,
+                        SubscriptionManager.SERVICE_CAPABILITY_DATA
+                });
+        when(mPhoneGlobals.getCarrierConfigForSubId(anyInt())).thenReturn(bundle);
+
+        // Mock system services used by TelecomAccountRegistry
+        when(mMockedContext.getSystemServiceName(TelecomManager.class))
+                .thenReturn(Context.TELECOM_SERVICE);
+        when(mMockedContext.getSystemService(TelecomManager.class))
+                .thenReturn(mTelecomManager);
+        when(mMockedContext.getSystemServiceName(TelephonyManager.class))
+                .thenReturn(Context.TELEPHONY_SERVICE);
+        when(mMockedContext.getSystemService(TelephonyManager.class))
+                .thenReturn(mTelephonyManager);
+        when(mMockedContext.getSystemServiceName(ImsManager.class))
+                .thenReturn(Context.TELEPHONY_IMS_SERVICE);
+        when(mMockedContext.getSystemService(ImsManager.class))
+                .thenReturn(mImsManager);
+        when(mMockedContext.getSystemServiceName(SubscriptionManager.class))
+                .thenReturn(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
+        when(mMockedContext.getSystemService(SubscriptionManager.class))
+                .thenReturn(mSubscriptionManager);
+
+        // Use mocked ContentProvider since we can't really mock ContentResolver
+        mContentResolver = ContentResolver.wrap(mContentProvider);
+        when(mMockedContext.getContentResolver()).thenReturn(mContentResolver);
+
+        mTestableLooper = TestableLooper.get(this);
+        when(mMockedContext.getMainLooper()).thenReturn(mTestableLooper.getLooper());
+        mTelecomAccountRegistry = new TelecomAccountRegistry(mMockedContext);
+        mTelecomAccountRegistry.setupOnBoot();
+
+        // Capture OnSubscriptionsChangedListener
+        ArgumentCaptor<OnSubscriptionsChangedListener> subChangeListenerCaptor =
+                ArgumentCaptor.forClass(OnSubscriptionsChangedListener.class);
+        verify(mSubscriptionManager).addOnSubscriptionsChangedListener(
+                subChangeListenerCaptor.capture());
+        mOnSubscriptionsChangedListener = subChangeListenerCaptor.getValue();
+
+        // Capture TelephonyCallback
+        ArgumentCaptor<TelephonyCallback> telephonyCallbackArgumentCaptor =
+                ArgumentCaptor.forClass(TelephonyCallback.class);
+        verify(mTelephonyManager).registerTelephonyCallback(anyInt(), any(),
+                telephonyCallbackArgumentCaptor.capture());
+        mTelephonyCallback = telephonyCallbackArgumentCaptor.getValue();
+
+        // Capture BroadcastReceivers
+        ArgumentCaptor<BroadcastReceiver> broadcastReceiverArgumentCaptor =
+                ArgumentCaptor.forClass(BroadcastReceiver.class);
+        verify(mMockedContext, times(2)).registerReceiver(broadcastReceiverArgumentCaptor.capture(),
+                any());
+        mUserSwitchedAndConfigChangedReceiver =
+                broadcastReceiverArgumentCaptor.getAllValues().get(0);
+        mLocaleChangedBroadcastReceiver = broadcastReceiverArgumentCaptor.getAllValues().get(1);
+
+        mTestableLooper.processAllMessages();
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    @Test
+    public void userSwitched_withPSTNAccount_shouldRegisterPSTNAccount() {
+        onUserSwitched(UserHandle.CURRENT);
+
+        PhoneAccount phoneAccount = verifyAndCaptureRegisteredPhoneAccount();
+
+        assertThat(phoneAccount.hasCapabilities(
+                PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)).isTrue();
+        assertThat(phoneAccount.hasCapabilities(
+                PhoneAccount.CAPABILITY_CALL_PROVIDER)).isTrue();
+        assertThat(phoneAccount.hasCapabilities(
+                PhoneAccount.CAPABILITY_PLACE_EMERGENCY_CALLS)).isTrue();
+    }
+
+    @Test
+    public void onLocaleChanged_withPSTNAccountDisabled_shouldRegisterEmergencyOnlyAccount() {
+        when(mResources.getBoolean(R.bool.config_pstn_phone_accounts_enabled)).thenReturn(false);
+        when(mResources.getBoolean(
+                R.bool.config_emergency_account_emergency_calls_only)).thenReturn(true);
+        onLocaleChanged();
+
+        PhoneAccount phoneAccount = verifyAndCaptureRegisteredPhoneAccount();
+
+        assertThat(phoneAccount.hasCapabilities(
+                PhoneAccount.CAPABILITY_EMERGENCY_CALLS_ONLY)).isTrue();
+    }
+
+    @Test
+    public void onLocaleChanged_withSubVoiceCapable_shouldNotRegisterEmergencyOnlyAccount() {
+        overrideSubscriptionServiceCapabilities(
+                new int[]{SubscriptionManager.SERVICE_CAPABILITY_VOICE});
+        onLocaleChanged();
+
+        PhoneAccount phoneAccount = verifyAndCaptureRegisteredPhoneAccount();
+
+        assertThat(phoneAccount.hasCapabilities(
+                PhoneAccount.CAPABILITY_EMERGENCY_CALLS_ONLY)).isFalse();
+    }
+
+    @Test
+    public void onLocaleChanged_withSubNotVoiceCapable_shouldRegisterEmergencyOnlyAccount() {
+        overrideSubscriptionServiceCapabilities(
+                new int[]{SubscriptionManager.SERVICE_CAPABILITY_DATA});
+        onLocaleChanged();
+
+        PhoneAccount phoneAccount = verifyAndCaptureRegisteredPhoneAccount();
+
+        assertThat(phoneAccount.hasCapabilities(
+                PhoneAccount.CAPABILITY_EMERGENCY_CALLS_ONLY)).isTrue();
+    }
+
+    private PhoneAccount verifyAndCaptureRegisteredPhoneAccount() {
+        ArgumentCaptor<PhoneAccount> phoneAccountArgumentCaptor =
+                ArgumentCaptor.forClass(PhoneAccount.class);
+        verify(mTelecomManager, atLeastOnce()).registerPhoneAccount(
+                phoneAccountArgumentCaptor.capture());
+        return phoneAccountArgumentCaptor.getValue();
+    }
+
+    private void onUserSwitched(UserHandle userHandle) {
+        Log.d(TAG, "Broadcast ACTION_USER_SWITCHED...");
+        Intent intent = new Intent(Intent.ACTION_USER_SWITCHED);
+        intent.putExtra(Intent.EXTRA_USER, userHandle);
+        mUserSwitchedAndConfigChangedReceiver.onReceive(mMockedContext, intent);
+        mTestableLooper.processAllMessages();
+    }
+
+    private void onCarrierConfigChanged(int subId) {
+        Log.d(TAG, "Broadcast ACTION_CARRIER_CONFIG_CHANGED...");
+        Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
+        intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
+        mUserSwitchedAndConfigChangedReceiver.onReceive(mMockedContext, intent);
+        mTestableLooper.processAllMessages();
+    }
+
+    private void onSubscriptionsChanged() {
+        Log.d(TAG, "Change subscriptions...");
+        mOnSubscriptionsChangedListener.onSubscriptionsChanged();
+    }
+
+    private void onAddSubscriptionListenerFailed() {
+        Log.d(TAG, "Add subscription listener failed...");
+        mOnSubscriptionsChangedListener.onAddListenerFailed();
+    }
+
+    private void onServiceStateChanged(ServiceState serviceState) {
+        if (mTelephonyCallback instanceof TelephonyCallback.ServiceStateListener) {
+            TelephonyCallback.ServiceStateListener listener =
+                    (TelephonyCallback.ServiceStateListener) mTelephonyCallback;
+            listener.onServiceStateChanged(serviceState);
+        }
+    }
+
+    private void onActiveDataSubscriptionIdChanged(int subId) {
+        if (mTelephonyCallback instanceof TelephonyCallback.ActiveDataSubscriptionIdListener) {
+            TelephonyCallback.ActiveDataSubscriptionIdListener listener =
+                    (TelephonyCallback.ActiveDataSubscriptionIdListener) mTelephonyCallback;
+            listener.onActiveDataSubscriptionIdChanged(subId);
+        }
+    }
+
+    private void onLocaleChanged() {
+        Log.d(TAG, "Broadcast ACTION_LOCALE_CHANGED...");
+        Intent intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
+        mLocaleChangedBroadcastReceiver.onReceive(mMockedContext, intent);
+    }
+
+    private void onNetworkCountryChanged() {
+        Log.d(TAG, "Broadcast ACTION_NETWORK_COUNTRY_CHANGED...");
+        Intent intent = new Intent(TelephonyManager.ACTION_NETWORK_COUNTRY_CHANGED);
+        mLocaleChangedBroadcastReceiver.onReceive(mMockedContext, intent);
+    }
+
+    private void overrideSubscriptionServiceCapabilities(int[] capabilities) {
+        PersistableBundle bundle = new PersistableBundle();
+        bundle.putIntArray(CarrierConfigManager.KEY_CELLULAR_SERVICE_CAPABILITIES_INT_ARRAY,
+                capabilities);
+
+        when(mPhoneGlobals.getCarrierConfigForSubId(anyInt())).thenReturn(bundle);
+        mTestableLooper.processAllMessages();
+    }
+}
diff --git a/tests/src/com/android/services/telephony/TelephonyConnectionServiceTest.java b/tests/src/com/android/services/telephony/TelephonyConnectionServiceTest.java
index 6990e29..a3497b6 100644
--- a/tests/src/com/android/services/telephony/TelephonyConnectionServiceTest.java
+++ b/tests/src/com/android/services/telephony/TelephonyConnectionServiceTest.java
@@ -314,7 +314,8 @@
                 mTestConnectionService, mEmergencyStateTracker);
         replaceInstance(TelephonyConnectionService.class, "mSatelliteSOSMessageRecommender",
                 mTestConnectionService, mSatelliteSOSMessageRecommender);
-        doNothing().when(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any());
+        doNothing().when(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any(),
+                anyBoolean());
         doNothing().when(mSatelliteSOSMessageRecommender).onEmergencyCallConnectionStateChanged(
                 anyString(), anyInt());
         doReturn(CompletableFuture.completedFuture(NOT_DISCONNECTED))
@@ -1347,13 +1348,13 @@
         callback.getValue().onComplete(null, true);
 
         try {
-            doAnswer(invocation -> null).when(mContext).startActivity(any());
+            doAnswer(invocation -> null).when(mContext).startActivityAsUser(any(), any());
             verify(testPhone).dial(anyString(), any(), any());
         } catch (CallStateException e) {
             // This shouldn't happen
             fail();
         }
-        verify(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any(), anyBoolean());
     }
 
     /**
@@ -1439,7 +1440,7 @@
     @Test
     @SmallTest
     public void testCreateOutgoingEmergencyConnection_exitingSatellite_placeCall() {
-        when(mSatelliteController.isSatelliteEnabled()).thenReturn(true);
+        when(mSatelliteController.isSatelliteEnabledOrBeingEnabled()).thenReturn(true);
         doReturn(true).when(mMockResources).getBoolean(anyInt());
         doReturn(true).when(mTelephonyManagerProxy).isCurrentEmergencyNumber(
                 anyString());
@@ -1455,20 +1456,20 @@
         when(mSST.isRadioOn()).thenReturn(true);
         assertFalse(callback.getValue()
                 .isOkToCall(testPhone, ServiceState.STATE_OUT_OF_SERVICE, false));
-        when(mSatelliteController.isSatelliteEnabled()).thenReturn(false);
+        when(mSatelliteController.isSatelliteEnabledOrBeingEnabled()).thenReturn(false);
         assertTrue(callback.getValue()
                 .isOkToCall(testPhone, ServiceState.STATE_OUT_OF_SERVICE, false));
 
         callback.getValue().onComplete(null, true);
 
         try {
-            doAnswer(invocation -> null).when(mContext).startActivity(any());
+            doAnswer(invocation -> null).when(mContext).startActivityAsUser(any(), any());
             verify(testPhone).dial(anyString(), any(), any());
         } catch (CallStateException e) {
             // This shouldn't happen
             fail();
         }
-        verify(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any(), anyBoolean());
     }
 
     /**
@@ -1480,7 +1481,7 @@
     public void testCreateOutgoingEmergencyConnection_exitingSatellite_EmergencySatellite()
             throws Exception {
         doReturn(true).when(mFeatureFlags).carrierRoamingNbIotNtn();
-        doReturn(true).when(mSatelliteController).isSatelliteEnabled();
+        doReturn(true).when(mSatelliteController).isSatelliteEnabledOrBeingEnabled();
 
         // Set config_turn_off_oem_enabled_satellite_during_emergency_call as false
         doReturn(true).when(mTelephonyManagerProxy).isCurrentEmergencyNumber(anyString());
@@ -1499,7 +1500,7 @@
     @SmallTest
     public void testCreateOutgoingEmergencyConnection_exitingSatellite_OEM() throws Exception {
         doReturn(true).when(mFeatureFlags).carrierRoamingNbIotNtn();
-        doReturn(true).when(mSatelliteController).isSatelliteEnabled();
+        doReturn(true).when(mSatelliteController).isSatelliteEnabledOrBeingEnabled();
 
         // Set config_turn_off_oem_enabled_satellite_during_emergency_call as false
         doReturn(false).when(mMockResources).getBoolean(anyInt());
@@ -1538,7 +1539,7 @@
     @SmallTest
     public void testCreateOutgoingEmergencyConnection_exitingSatellite_Carrier() throws Exception {
         doReturn(true).when(mFeatureFlags).carrierRoamingNbIotNtn();
-        doReturn(true).when(mSatelliteController).isSatelliteEnabled();
+        doReturn(true).when(mSatelliteController).isSatelliteEnabledOrBeingEnabled();
 
         // Set config_turn_off_oem_enabled_satellite_during_emergency_call as false
         doReturn(false).when(mMockResources).getBoolean(anyInt());
@@ -2158,7 +2159,7 @@
             throws Exception {
         setupForCallTest();
         when(mTelephonyManagerProxy.isConcurrentCallsPossible()).thenReturn(true);
-        doNothing().when(mContext).startActivity(any());
+        doNothing().when(mContext).startActivityAsUser(any(), any());
 
         mBinderStub.createConnection(PHONE_ACCOUNT_HANDLE_1, "TC@1",
                 new ConnectionRequest(PHONE_ACCOUNT_HANDLE_1, Uri.parse("tel:16505551212"),
@@ -2191,7 +2192,7 @@
             throws Exception {
         setupForCallTest();
         when(mTelephonyManagerProxy.isConcurrentCallsPossible()).thenReturn(true);
-        doNothing().when(mContext).startActivity(any());
+        doNothing().when(mContext).startActivityAsUser(any(), any());
 
         doReturn(true).when(mTelephonyManagerProxy).isCurrentEmergencyNumber(anyString());
         mBinderStub.createConnection(PHONE_ACCOUNT_HANDLE_1, "TC@1",
@@ -2227,7 +2228,7 @@
             throws Exception {
         setupForCallTest();
         when(mTelephonyManagerProxy.isConcurrentCallsPossible()).thenReturn(true);
-        doNothing().when(mContext).startActivity(any());
+        doNothing().when(mContext).startActivityAsUser(any(), any());
 
         doReturn(true).when(mTelephonyManagerProxy).isCurrentEmergencyNumber(anyString());
         getTestContext().getCarrierConfig(0 /*subId*/).putBoolean(
@@ -2291,7 +2292,8 @@
                 .getDomainSelectionConnection(eq(mPhone0), eq(SELECTOR_TYPE_CALLING), eq(true));
         verify(mEmergencyStateTracker)
                 .startEmergencyCall(eq(mPhone0), connectionCaptor.capture(), eq(false));
-        verify(mSatelliteSOSMessageRecommender, times(2)).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender, times(2)).onEmergencyCallStarted(any(),
+                anyBoolean());
         verify(mEmergencyCallDomainSelectionConnection).createEmergencyConnection(any(), any());
 
         android.telecom.Connection tc = connectionCaptor.getValue();
@@ -2330,7 +2332,8 @@
                 .getDomainSelectionConnection(eq(mPhone0), eq(SELECTOR_TYPE_CALLING), eq(true));
         verify(mEmergencyStateTracker)
                 .startEmergencyCall(eq(mPhone0), connectionCaptor.capture(), eq(false));
-        verify(mSatelliteSOSMessageRecommender, times(2)).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender, times(2)).onEmergencyCallStarted(any(),
+                anyBoolean());
         verify(mEmergencyCallDomainSelectionConnection).createEmergencyConnection(any(), any());
 
         android.telecom.Connection tc = connectionCaptor.getValue();
@@ -2374,7 +2377,8 @@
                 .getDomainSelectionConnection(eq(mPhone0), eq(SELECTOR_TYPE_CALLING), eq(true));
         verify(mEmergencyStateTracker)
                 .startEmergencyCall(eq(mPhone0), connectionCaptor.capture(), eq(false));
-        verify(mSatelliteSOSMessageRecommender, times(2)).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender, times(2)).onEmergencyCallStarted(any(),
+                anyBoolean());
         verify(mEmergencyCallDomainSelectionConnection).createEmergencyConnection(any(), any());
 
         android.telecom.Connection tc = connectionCaptor.getValue();
@@ -2522,7 +2526,8 @@
 
         listener.onDisconnect(0);
 
-        verify(mSatelliteSOSMessageRecommender, times(2)).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender, times(2)).onEmergencyCallStarted(any(),
+                anyBoolean());
 
         ArgumentCaptor<DialArgs> argsCaptor = ArgumentCaptor.forClass(DialArgs.class);
 
@@ -2628,7 +2633,7 @@
         verify(mDomainSelectionResolver)
                 .getDomainSelectionConnection(eq(mPhone0), eq(SELECTOR_TYPE_CALLING), eq(false));
         verify(mNormalCallDomainSelectionConnection).createNormalConnection(any(), any());
-        verify(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any(), anyBoolean());
 
         ArgumentCaptor<DialArgs> argsCaptor = ArgumentCaptor.forClass(DialArgs.class);
 
@@ -2725,7 +2730,8 @@
                 .getDomainSelectionConnection(eq(mPhone0), eq(SELECTOR_TYPE_CALLING), eq(true));
         verify(mEmergencyStateTracker)
                 .startEmergencyCall(eq(mPhone0), connectionCaptor.capture(), eq(false));
-        verify(mSatelliteSOSMessageRecommender, times(2)).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender, times(2)).onEmergencyCallStarted(any(),
+                anyBoolean());
         verify(mEmergencyCallDomainSelectionConnection).createEmergencyConnection(any(), any());
 
         android.telecom.Connection tc = connectionCaptor.getValue();
@@ -2796,7 +2802,7 @@
         verify(mDomainSelectionResolver)
                 .getDomainSelectionConnection(eq(mPhone0), eq(SELECTOR_TYPE_CALLING), eq(false));
         verify(mNormalCallDomainSelectionConnection).createNormalConnection(any(), any());
-        verify(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any(), anyBoolean());
 
         ArgumentCaptor<DialArgs> argsCaptor = ArgumentCaptor.forClass(DialArgs.class);
 
@@ -3029,7 +3035,7 @@
                 .getDomainSelectionConnection(eq(mPhone0), eq(SELECTOR_TYPE_CALLING), eq(true));
         verify(mEmergencyStateTracker)
                 .startEmergencyCall(eq(mPhone0), connectionCaptor.capture(), eq(false));
-        verify(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any(), anyBoolean());
         verify(mEmergencyCallDomainSelectionConnection).createEmergencyConnection(any(), any());
 
         android.telecom.Connection tc = connectionCaptor.getValue();
@@ -3082,7 +3088,7 @@
                 .getDomainSelectionConnection(eq(mPhone0), eq(SELECTOR_TYPE_CALLING), eq(true));
         verify(mEmergencyStateTracker)
                 .startEmergencyCall(eq(mPhone0), connectionCaptor.capture(), eq(false));
-        verify(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any(), anyBoolean());
         verify(mEmergencyCallDomainSelectionConnection).createEmergencyConnection(any(), any());
 
         android.telecom.Connection tc = connectionCaptor.getValue();
@@ -3417,7 +3423,7 @@
 
         verify(mEmergencyStateTracker)
                 .startEmergencyCall(eq(mPhone0), connectionCaptor.capture(), eq(false));
-        verify(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender).onEmergencyCallStarted(any(), anyBoolean());
 
         android.telecom.Connection tc = connectionCaptor.getValue();
 
@@ -3493,7 +3499,8 @@
                 .getDomainSelectionConnection(eq(mPhone0), eq(SELECTOR_TYPE_CALLING), eq(true));
         verify(mEmergencyStateTracker)
                 .startEmergencyCall(eq(mPhone0), connectionCaptor.capture(), eq(false));
-        verify(mSatelliteSOSMessageRecommender, times(2)).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender, times(2)).onEmergencyCallStarted(any(),
+                anyBoolean());
         verify(mEmergencyCallDomainSelectionConnection).createEmergencyConnection(any(), any());
         verify(mPhone0).dial(anyString(), any(), any());
 
@@ -3682,7 +3689,7 @@
     @Test
     public void testDomainSelectionWithMmiCode() {
         //UT domain selection should not be handled by new domain selector.
-        doNothing().when(mContext).startActivity(any());
+        doNothing().when(mContext).startActivityAsUser(any(), any());
         setupForCallTest();
         setupForDialForDomainSelection(mPhone0, 0, false);
         mTestConnectionService.onCreateOutgoingConnection(PHONE_ACCOUNT_HANDLE_1,
@@ -3703,7 +3710,8 @@
         verify(mDomainSelectionResolver)
                 .getDomainSelectionConnection(eq(mPhone0), eq(SELECTOR_TYPE_CALLING), eq(false));
         verify(mNormalCallDomainSelectionConnection).createNormalConnection(any(), any());
-        verify(mSatelliteSOSMessageRecommender, never()).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender, never()).onEmergencyCallStarted(any(),
+                anyBoolean());
 
         ArgumentCaptor<DialArgs> argsCaptor = ArgumentCaptor.forClass(DialArgs.class);
 
@@ -3728,7 +3736,8 @@
         verify(mDomainSelectionResolver)
                 .getDomainSelectionConnection(eq(mPhone0), eq(SELECTOR_TYPE_CALLING), eq(false));
         verify(mNormalCallDomainSelectionConnection).createNormalConnection(any(), any());
-        verify(mSatelliteSOSMessageRecommender, never()).onEmergencyCallStarted(any());
+        verify(mSatelliteSOSMessageRecommender, never()).onEmergencyCallStarted(any(),
+                anyBoolean());
 
         ArgumentCaptor<DialArgs> argsCaptor = ArgumentCaptor.forClass(DialArgs.class);
 
@@ -3744,7 +3753,7 @@
     @Test
     public void testNormalCallSatelliteEnabled() {
         setupForCallTest();
-        doReturn(true).when(mSatelliteController).isSatelliteEnabled();
+        doReturn(true).when(mSatelliteController).isSatelliteEnabledOrBeingEnabled();
 
         mConnection = mTestConnectionService.onCreateOutgoingConnection(PHONE_ACCOUNT_HANDLE_1,
                 createConnectionRequest(PHONE_ACCOUNT_HANDLE_1, "1234", TELECOM_CALL_ID1));
@@ -3757,7 +3766,7 @@
     @Test
     public void testEmergencyCallSatelliteEnabled_blockEmergencyCall() {
         setupForCallTest();
-        doReturn(true).when(mSatelliteController).isSatelliteEnabled();
+        doReturn(true).when(mSatelliteController).isSatelliteEnabledOrBeingEnabled();
         doReturn(false).when(mMockResources).getBoolean(anyInt());
         doReturn(true).when(mTelephonyManagerProxy).isCurrentEmergencyNumber(
                 anyString());
@@ -3888,6 +3897,7 @@
         ss.setEmergencyOnly(true);
         ss.setState(ServiceState.STATE_EMERGENCY_ONLY);
         when(mockPhone.getServiceState()).thenReturn(ss);
+        when(mPhoneFactoryProxy.getPhones()).thenReturn(new Phone[] {mockPhone});
 
         assertFalse(mTestConnectionService.isAvailableForEmergencyCalls(mockPhone,
                 EmergencyNumber.EMERGENCY_CALL_ROUTING_EMERGENCY));
@@ -3911,6 +3921,79 @@
         ss.setState(ServiceState.STATE_EMERGENCY_ONLY);
         when(mockPhone.getServiceState()).thenReturn(ss);
 
+        when(mPhoneFactoryProxy.getPhones()).thenReturn(new Phone[] {mockPhone});
+
+        assertTrue(mTestConnectionService.isAvailableForEmergencyCalls(mockPhone,
+                EmergencyNumber.EMERGENCY_CALL_ROUTING_EMERGENCY));
+        assertFalse(mTestConnectionService.isAvailableForEmergencyCalls(mockPhone,
+                EmergencyNumber.EMERGENCY_CALL_ROUTING_NORMAL));
+        assertTrue(mTestConnectionService.isAvailableForEmergencyCalls(mockPhone,
+                EmergencyNumber.EMERGENCY_CALL_ROUTING_UNKNOWN));
+    }
+
+    @Test
+    public void testIsAvailableForEmergencyCallsUsingNTN_CellularAvailable() {
+        mSetFlagsRule.enableFlags(Flags.FLAG_CARRIER_ENABLED_SATELLITE_FLAG);
+
+        // Call is not supported while using satellite
+        when(mSatelliteController.isInSatelliteModeForCarrierRoaming(any())).thenReturn(true);
+        when(mSatelliteController.getCapabilitiesForCarrierRoamingSatelliteMode(any()))
+                .thenReturn(List.of(NetworkRegistrationInfo.SERVICE_TYPE_DATA));
+
+        Phone mockPhone = Mockito.mock(Phone.class);
+        ServiceState ss = new ServiceState();
+        ss.setEmergencyOnly(true);
+        ss.setState(ServiceState.STATE_EMERGENCY_ONLY);
+        when(mockPhone.getServiceState()).thenReturn(ss);
+
+        // Phone2 is in limited service
+        Phone mockPhone2 = Mockito.mock(Phone.class);
+        ServiceState ss2 = new ServiceState();
+        ss2.setEmergencyOnly(true);
+        ss2.setState(ServiceState.STATE_EMERGENCY_ONLY);
+        when(mockPhone2.getServiceState()).thenReturn(ss2);
+
+        Phone[] phones = {mockPhone, mockPhone2};
+        when(mPhoneFactoryProxy.getPhones()).thenReturn(phones);
+
+        assertFalse(mTestConnectionService.isAvailableForEmergencyCalls(mockPhone,
+                EmergencyNumber.EMERGENCY_CALL_ROUTING_EMERGENCY));
+        assertFalse(mTestConnectionService.isAvailableForEmergencyCalls(mockPhone,
+                EmergencyNumber.EMERGENCY_CALL_ROUTING_NORMAL));
+        assertFalse(mTestConnectionService.isAvailableForEmergencyCalls(mockPhone,
+                EmergencyNumber.EMERGENCY_CALL_ROUTING_UNKNOWN));
+    }
+
+    @Test
+    public void testIsAvailableForEmergencyCallsUsingNTN_CellularNotAvailable() {
+        mSetFlagsRule.enableFlags(Flags.FLAG_CARRIER_ENABLED_SATELLITE_FLAG);
+
+        // Call is not supported while using satellite
+        when(mSatelliteController.isInSatelliteModeForCarrierRoaming(any())).thenReturn(true);
+        when(mSatelliteController.getCapabilitiesForCarrierRoamingSatelliteMode(any()))
+                .thenReturn(List.of(NetworkRegistrationInfo.SERVICE_TYPE_DATA));
+
+        NetworkRegistrationInfo nri = new NetworkRegistrationInfo.Builder()
+                .setIsNonTerrestrialNetwork(true)
+                .setAvailableServices(List.of(NetworkRegistrationInfo.SERVICE_TYPE_DATA))
+                .build();
+        Phone mockPhone = Mockito.mock(Phone.class);
+        ServiceState ss = new ServiceState();
+        ss.addNetworkRegistrationInfo(nri);
+        ss.setEmergencyOnly(true);
+        ss.setState(ServiceState.STATE_EMERGENCY_ONLY);
+        when(mockPhone.getServiceState()).thenReturn(ss);
+
+        // Phone2 is out of service
+        Phone mockPhone2 = Mockito.mock(Phone.class);
+        ServiceState ss2 = new ServiceState();
+        ss2.setEmergencyOnly(false);
+        ss2.setState(ServiceState.STATE_OUT_OF_SERVICE);
+        when(mockPhone2.getServiceState()).thenReturn(ss2);
+
+        Phone[] phones = {mockPhone, mockPhone2};
+        when(mPhoneFactoryProxy.getPhones()).thenReturn(phones);
+
         assertTrue(mTestConnectionService.isAvailableForEmergencyCalls(mockPhone,
                 EmergencyNumber.EMERGENCY_CALL_ROUTING_EMERGENCY));
         assertFalse(mTestConnectionService.isAvailableForEmergencyCalls(mockPhone,
diff --git a/tests/src/com/android/services/telephony/domainselection/NormalCallDomainSelectorTest.java b/tests/src/com/android/services/telephony/domainselection/NormalCallDomainSelectorTest.java
index 49411bd..7acc7d6 100644
--- a/tests/src/com/android/services/telephony/domainselection/NormalCallDomainSelectorTest.java
+++ b/tests/src/com/android/services/telephony/domainselection/NormalCallDomainSelectorTest.java
@@ -743,6 +743,27 @@
                 mNormalCallDomainSelector.getSelectorState());
     }
 
+    @Test
+    public void testReselectDomainNoTimeoutMessage() {
+        final TestTransportSelectorCallback transportSelectorCallback =
+                new TestTransportSelectorCallback(mNormalCallDomainSelector);
+
+        DomainSelectionService.SelectionAttributes attributes =
+                new DomainSelectionService.SelectionAttributes.Builder(
+                        SLOT_ID, SUB_ID_1, SELECTOR_TYPE_CALLING)
+                        .setAddress(TEST_URI)
+                        .setCallId(TEST_CALLID)
+                        .setEmergency(false)
+                        .setVideoCall(false)
+                        .setExitedFromAirplaneMode(false)
+                        .build();
+
+        mNormalCallDomainSelector.selectDomain(null, transportSelectorCallback);
+        mNormalCallDomainSelector.reselectDomain(attributes);
+        assertFalse(mNormalCallDomainSelector.hasMessages(
+                NormalCallDomainSelector.MSG_WAIT_FOR_IMS_STATE_TIMEOUT));
+    }
+
     static class TestTransportSelectorCallback implements TransportSelectorCallback,
             WwanSelectorCallback {
         public boolean mCreated;