Merge "ServiceStateProvider:Enforce location permissino check with targetSdkVersion R-"
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 75b9d49..da61c80 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -10,6 +10,46 @@
     },
     {
       "name": "CarrierAppIntegrationTestCases"
+    },
+    {
+      "name": "CtsTelephonySdk28TestCases",
+      "options": [
+        {
+          "exclude-annotation": "androidx.test.filters.FlakyTest"
+        }
+      ]
+    },
+    {
+      "name": "CtsSimRestrictedApisTestCases",
+      "options": [
+        {
+          "exclude-annotation": "androidx.test.filters.FlakyTest"
+        }
+      ]
+    },
+    {
+      "name": "CtsTelephony2TestCases",
+      "options": [
+        {
+          "exclude-annotation": "androidx.test.filters.FlakyTest"
+        }
+      ]
+    },
+    {
+      "name": "CtsTelephony3TestCases",
+      "options": [
+        {
+          "exclude-annotation": "androidx.test.filters.FlakyTest"
+        }
+      ]
+    },
+    {
+      "name": "CtsTelephonyProviderTestCases",
+      "options": [
+        {
+          "exclude-annotation": "androidx.test.filters.FlakyTest"
+        }
+      ]
     }
   ]
 }
diff --git a/src/com/android/phone/PhoneInterfaceManager.java b/src/com/android/phone/PhoneInterfaceManager.java
index d7cdbc2..8d946f5 100755
--- a/src/com/android/phone/PhoneInterfaceManager.java
+++ b/src/com/android/phone/PhoneInterfaceManager.java
@@ -134,6 +134,7 @@
 import com.android.ims.ImsManager;
 import com.android.ims.internal.IImsServiceFeatureCallback;
 import com.android.ims.rcs.uce.eab.EabUtil;
+import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.telephony.CallForwardInfo;
 import com.android.internal.telephony.CallManager;
 import com.android.internal.telephony.CallStateException;
@@ -7303,13 +7304,7 @@
                         getDefaultDataEnabled());
                 setNetworkSelectionModeAutomatic(subId);
                 Phone phone = getPhone(subId);
-                if (phone != null) {
-                    SubscriptionManager.setSubscriptionProperty(subId,
-                            SubscriptionManager.ALLOWED_NETWORK_TYPES,
-                            "user=" + RadioAccessFamily.getRafFromNetworkType(
-                                    RILConstants.PREFERRED_NETWORK_MODE));
-                    phone.loadAllowedNetworksFromSubscriptionDatabase();
-                }
+                cleanUpAllowedNetworkTypes(phone, subId);
                 setDataRoamingEnabled(subId, getDefaultDataRoamingEnabled(subId));
                 CarrierInfoManager.deleteAllCarrierKeysForImsiEncryption(mApp);
             }
@@ -7335,6 +7330,21 @@
         }
     }
 
+    @VisibleForTesting
+    void cleanUpAllowedNetworkTypes(Phone phone, int subId) {
+        if (phone == null || !SubscriptionManager.isUsableSubscriptionId(subId)) {
+            return;
+        }
+        long defaultNetworkType = RadioAccessFamily.getRafFromNetworkType(
+                RILConstants.PREFERRED_NETWORK_MODE);
+        SubscriptionManager.setSubscriptionProperty(subId,
+                SubscriptionManager.ALLOWED_NETWORK_TYPES,
+                "user=" + defaultNetworkType);
+        phone.loadAllowedNetworksFromSubscriptionDatabase();
+        phone.setAllowedNetworkTypes(TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER,
+                defaultNetworkType, null);
+    }
+
     private void cleanUpSmsRawTable(Context context) {
         ContentResolver resolver = context.getContentResolver();
         Uri uri = Uri.withAppendedPath(Telephony.Sms.CONTENT_URI, "raw/permanentDelete");
@@ -9519,6 +9529,24 @@
         return sThermalMitigationAllowlistedPackages;
     }
 
+    private boolean isAnyPhoneInEmergencyState() {
+        TelecomManager tm = mApp.getSystemService(TelecomManager.class);
+        if (tm.isInEmergencyCall()) {
+            Log.e(LOG_TAG , "Phone state is not valid. One of the phones is in an emergency call");
+            return true;
+        }
+        for (Phone phone : PhoneFactory.getPhones()) {
+            if (phone.isInEmergencySmsMode() || phone.isInEcm()) {
+                Log.e(LOG_TAG, "Phone state is not valid. isInEmergencySmsMode = "
+                    + phone.isInEmergencySmsMode() + " isInEmergencyCallbackMode = "
+                    + phone.isInEcm());
+                return true;
+            }
+        }
+
+        return false;
+    }
+
     /**
      * Used by shell commands to add an authorized package name for thermal mitigation.
      * @param packageName name of package to be allowlisted
@@ -9601,8 +9629,6 @@
 
                     TelecomAccountRegistry registry = TelecomAccountRegistry.getInstance(null);
                     if (registry != null) {
-                        TelephonyConnectionService service =
-                                registry.getTelephonyConnectionService();
                         Phone phone = getPhone(subId);
                         if (phone == null) {
                             thermalMitigationResult =
@@ -9610,19 +9636,20 @@
                             break;
                         }
 
-                        if (PhoneConstantConversions.convertCallState(phone.getState())
-                                != TelephonyManager.CALL_STATE_IDLE
-                                || phone.isInEmergencySmsMode() || phone.isInEcm()
-                                || (service != null && service.isEmergencyCallPending())) {
-                            String errorMessage = "Phone state is not valid. call state = "
-                                    + PhoneConstantConversions.convertCallState(phone.getState())
-                                    + " isInEmergencySmsMode = " + phone.isInEmergencySmsMode()
-                                    + " isInEmergencyCallbackMode = " + phone.isInEcm();
-                            errorMessage += service == null
-                                    ? " TelephonyConnectionService is null"
-                                    : " isEmergencyCallPending = "
-                                            + service.isEmergencyCallPending();
-                            Log.e(LOG_TAG, errorMessage);
+                        TelephonyConnectionService service =
+                                registry.getTelephonyConnectionService();
+                        if (service == null) {
+                            Log.e(LOG_TAG, "TelephonyConnectionService is null");
+                            thermalMitigationResult =
+                                    TelephonyManager.THERMAL_MITIGATION_RESULT_INVALID_STATE;
+                            break;
+
+                        } else if (service.isEmergencyCallPending()) {
+                            Log.e(LOG_TAG, "An emergency call is pending");
+                            thermalMitigationResult =
+                                    TelephonyManager.THERMAL_MITIGATION_RESULT_INVALID_STATE;
+                            break;
+                        } else if (isAnyPhoneInEmergencyState()) {
                             thermalMitigationResult =
                                     TelephonyManager.THERMAL_MITIGATION_RESULT_INVALID_STATE;
                             break;
diff --git a/src/com/android/services/telephony/RadioOnHelper.java b/src/com/android/services/telephony/RadioOnHelper.java
index 25ac220..be2ddb2 100644
--- a/src/com/android/services/telephony/RadioOnHelper.java
+++ b/src/com/android/services/telephony/RadioOnHelper.java
@@ -78,7 +78,7 @@
      * serialized, and runs on the main looper.)
      */
     public void triggerRadioOnAndListen(RadioOnStateListener.Callback callback,
-            boolean forEmergencyCall, Phone phoneForEmergencyCall) {
+            boolean forEmergencyCall, Phone phoneForEmergencyCall, boolean isTestEmergencyNumber) {
         setupListeners();
         mCallback = callback;
         mInProgressListeners.clear();
@@ -90,17 +90,17 @@
             }
 
             mInProgressListeners.add(mListeners.get(i));
-            mListeners.get(i).waitForRadioOn(phone, this, forEmergencyCall,
-                    forEmergencyCall && phone == phoneForEmergencyCall);
+            mListeners.get(i).waitForRadioOn(phone, this, forEmergencyCall, forEmergencyCall
+                    && phone == phoneForEmergencyCall);
         }
-
-        powerOnRadio(forEmergencyCall, phoneForEmergencyCall);
+        powerOnRadio(forEmergencyCall, phoneForEmergencyCall, isTestEmergencyNumber);
     }
     /**
      * Attempt to power on the radio (i.e. take the device out of airplane mode). We'll eventually
      * get an onServiceStateChanged() callback when the radio successfully comes up.
      */
-    private void powerOnRadio(boolean forEmergencyCall, Phone phoneForEmergencyCall) {
+    private void powerOnRadio(boolean forEmergencyCall, Phone phoneForEmergencyCall,
+            boolean isTestEmergencyNumber) {
 
         // If airplane mode is on, we turn it off the same way that the Settings activity turns it
         // off.
@@ -114,7 +114,12 @@
 
             for (Phone phone : PhoneFactory.getPhones()) {
                 Log.d(this, "powerOnRadio, enabling Radio");
-                phone.setRadioPower(true, forEmergencyCall, phone == phoneForEmergencyCall, false);
+                if (isTestEmergencyNumber) {
+                    phone.setRadioPowerOnForTestEmergencyCall(phone == phoneForEmergencyCall);
+                } else {
+                    phone.setRadioPower(true, forEmergencyCall, phone == phoneForEmergencyCall,
+                            false);
+                }
             }
 
             // Post the broadcast intend for change in airplane mode
diff --git a/src/com/android/services/telephony/TelephonyConnectionService.java b/src/com/android/services/telephony/TelephonyConnectionService.java
index 581a23a..d2b0c50 100644
--- a/src/com/android/services/telephony/TelephonyConnectionService.java
+++ b/src/com/android/services/telephony/TelephonyConnectionService.java
@@ -842,7 +842,7 @@
                                 || serviceState == ServiceState.STATE_IN_SERVICE;
                     }
                 }
-            }, isEmergencyNumber && !isTestEmergencyNumber, phone);
+            }, isEmergencyNumber && !isTestEmergencyNumber, phone, isTestEmergencyNumber);
             // Return the still unconnected GsmConnection and wait for the Radios to boot before
             // connecting it to the underlying Phone.
             return resultConnection;
diff --git a/tests/src/com/android/phone/PhoneInterfaceManagerTest.java b/tests/src/com/android/phone/PhoneInterfaceManagerTest.java
new file mode 100644
index 0000000..fe5d013
--- /dev/null
+++ b/tests/src/com/android/phone/PhoneInterfaceManagerTest.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.phone;
+
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+
+import android.content.pm.PackageManager;
+import android.telephony.RadioAccessFamily;
+import android.telephony.TelephonyManager;
+
+import androidx.test.annotation.UiThreadTest;
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+
+import com.android.TelephonyTestBase;
+import com.android.internal.telephony.Phone;
+import com.android.internal.telephony.RILConstants;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+
+/**
+ * Unit Test for CarrierConfigLoader.
+ */
+@RunWith(AndroidJUnit4.class)
+public class PhoneInterfaceManagerTest extends TelephonyTestBase {
+    private PhoneInterfaceManager mPhoneInterfaceManager;
+
+    @Mock
+    PhoneGlobals mPhoneGlobals;
+    @Mock
+    Phone mPhone;
+    @Mock
+    PackageManager mPackageManager;
+
+    @Before
+    @UiThreadTest
+    public void setUp() throws Exception {
+        super.setUp();
+        doReturn(mPackageManager).when(mPhoneGlobals).getPackageManager();
+        doReturn(false).when(mPackageManager).hasSystemFeature(
+                PackageManager.FEATURE_TELEPHONY_IMS);
+        mPhoneInterfaceManager = PhoneInterfaceManager.init(mPhoneGlobals);
+    }
+
+    @Test
+    public void cleanUpAllowedNetworkTypes_validPhoneAndSubId_doSetAllowedNetwork() {
+        long defaultNetworkType = RadioAccessFamily.getRafFromNetworkType(
+                RILConstants.PREFERRED_NETWORK_MODE);
+
+        mPhoneInterfaceManager.cleanUpAllowedNetworkTypes(mPhone, 1);
+
+        verify(mPhone).loadAllowedNetworksFromSubscriptionDatabase();
+        verify(mPhone).setAllowedNetworkTypes(TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER,
+                defaultNetworkType, null);
+    }
+
+    @Test
+    public void cleanUpAllowedNetworkTypes_validPhoneAndInvalidSubId_doNotSetAllowedNetwork() {
+        long defaultNetworkType = RadioAccessFamily.getRafFromNetworkType(
+                RILConstants.PREFERRED_NETWORK_MODE);
+
+        mPhoneInterfaceManager.cleanUpAllowedNetworkTypes(mPhone, -1);
+
+        verify(mPhone, never()).loadAllowedNetworksFromSubscriptionDatabase();
+        verify(mPhone, never()).setAllowedNetworkTypes(
+                TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER, defaultNetworkType, null);
+    }
+}
diff --git a/tests/src/com/android/services/telephony/TelephonyConnectionServiceTest.java b/tests/src/com/android/services/telephony/TelephonyConnectionServiceTest.java
index 07fe6a8..b761959 100644
--- a/tests/src/com/android/services/telephony/TelephonyConnectionServiceTest.java
+++ b/tests/src/com/android/services/telephony/TelephonyConnectionServiceTest.java
@@ -964,7 +964,7 @@
         ArgumentCaptor<RadioOnStateListener.Callback> callback =
                 ArgumentCaptor.forClass(RadioOnStateListener.Callback.class);
         verify(mRadioOnHelper).triggerRadioOnAndListen(callback.capture(), eq(true),
-                eq(testPhone));
+                eq(testPhone), eq(false));
 
         assertFalse(callback.getValue().isOkToCall(testPhone, ServiceState.STATE_OUT_OF_SERVICE));
         when(mSST.isRadioOn()).thenReturn(true);
@@ -990,7 +990,7 @@
         ArgumentCaptor<RadioOnStateListener.Callback> callback =
                 ArgumentCaptor.forClass(RadioOnStateListener.Callback.class);
         verify(mRadioOnHelper).triggerRadioOnAndListen(callback.capture(), eq(true),
-                eq(testPhone));
+                eq(testPhone), eq(false));
 
         assertFalse(callback.getValue().isOkToCall(testPhone, ServiceState.STATE_OUT_OF_SERVICE));
         when(mSST.isRadioOn()).thenReturn(true);