Merge "[MEP] set removable eSIM as default eUICC to pass GCF/PTCRB" into tm-dev
diff --git a/apex/Android.bp b/apex/Android.bp
deleted file mode 100644
index fbb70db..0000000
--- a/apex/Android.bp
+++ /dev/null
@@ -1,40 +0,0 @@
-package {
-    // See: http://go/android-license-faq
-    default_applicable_licenses: ["Android-Apache-2.0"],
-}
-
-apex_defaults {
-    name: "com.android.telephony-defaults",
-
-    // optional. if unspecified, a default one is auto-generated
-    androidManifest: "AndroidManifest.xml",
-
-    //java_libs: ["telephony-common", "ims-common", "voip-common"],
-    //apps: ["TeleService", "StkLib", "ONSLib"],
-
-    key: "com.android.telephony.key",
-    certificate: ":com.android.telephony.certificate",
-
-    updatable: false,
-}
-
-apex {
-    name: "com.android.telephony",
-    manifest: "apex_manifest.json",
-    //apps: ["StkLib"],
-
-    defaults:["com.android.telephony-defaults"],
-}
-
-apex_key {
-    name: "com.android.telephony.key",
-    public_key: "com.android.telephony.avbpubkey",
-    private_key: "com.android.telephony.pem",
-}
-
-android_app_certificate {
-    name: "com.android.telephony.certificate",
-    // This will use com.android.telephony.x509.pem (the cert) and
-    // com.android.telephony.pk8 (the private key)
-    certificate: "com.android.telephony",
-}
diff --git a/apex/AndroidManifest.xml b/apex/AndroidManifest.xml
deleted file mode 100644
index 6f25d7c..0000000
--- a/apex/AndroidManifest.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          package="com.android.telephony">
-    <!-- APEX does not have classes.dex -->
-    <application android:hasCode="false" />
-    <!-- Setting maxSdk to lock the module to R. minSdk is auto-set by build system -->
-</manifest>
diff --git a/apex/apex_manifest.json b/apex/apex_manifest.json
deleted file mode 100644
index 493d6fd..0000000
--- a/apex/apex_manifest.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
-  "name": "com.android.telephony",
-  "version": 1
-}
\ No newline at end of file
diff --git a/apex/com.android.telephony.avbpubkey b/apex/com.android.telephony.avbpubkey
deleted file mode 100644
index cba14427..0000000
--- a/apex/com.android.telephony.avbpubkey
+++ /dev/null
Binary files differ
diff --git a/apex/com.android.telephony.pem b/apex/com.android.telephony.pem
deleted file mode 100644
index 19d8c05..0000000
--- a/apex/com.android.telephony.pem
+++ /dev/null
@@ -1,51 +0,0 @@
------BEGIN RSA PRIVATE KEY-----
-MIIJKQIBAAKCAgEAvEOU0eLO65uykCUYoLBXxjsIB7pCIXahtyIMYiGuUl6tnYb2
-gjPxsD9fNrqgdT+WgzHlfMPr4GqkT7prSI4/y9NglnFk2nAKZLQwiwtLOmm54Cnp
-OqqQZ9+g4MvA2rsrmstJ/Pdu4t+9Bv9bZHYLEPCW4LV1v5S2jY7ie/C+SbZm8yFz
-X9RgTX7loH7oSNDqvVMRUeyrlH3gRHxPMQxIMfLMro1NCfkA4q8QnwPpM2+YEBf0
-kktXkvbfJUB0Ywo6BCVAoqxkghNQQTLBuBDFnho13gQSMOLu8C62pzdAyPm/n5Yv
-aqEdmmGkBsy2qiHTiRuiWWl9aGDhd0U6e+hYK4OM3ISDQiTr5OuraIKt8EH7jo8H
-Zb/WqJFygOq5RqXmAvbtq+eBAgLlUNAl5F9RwLU6zPTREsSGG/g1fqUSD4ZS2qHt
-d9aBdSepvL4xDCg9BDTFMt4Xjc83hk+v7nIIPB4cayA9s2kgjXwjZhiMOJuoNMmr
-Wu2GP9zw37WmUF5jXKgICVtoq//qofA3KA+YZ8NcmPRmeBzCEks5fCAZN64AIh5l
-vi8pPv+s8lbhGui/dk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F25FC85r0gKCz
-5t45PHa6YpL/WL8M3YdNVDjsmgIQZ0hYMQwAOWMU5pQG/tMFLDWYo9CvqNTCf7Im
-6CNqU0PlMABBE4iSIMqR+ooPQlIjMzQZAoIBAQC9JulZdQJzjZSI5tBj+zPScJJQ
-s/+sRfQBy7SalPtc+oLYBP2Js9c1JsR4Dk2vC3V5z7BaL4Lg4YcFVRcz9B4yUVRm
-BL/E34XGLfn5KBI8NeqIvHiivvlAPgoHwHAVsqtE35E2sYjOYbnn1FEaNm6EKiL3
-Dv1auVdLlP3jALJIEwHPzc2ZOc/Sh/LolfajR427j5YlgbMAk5DdXuxz7t9qEcyk
-Nc8HFaoXiBP1jK+L5C4mVvGeI9xghNoJXhNywEmMa2Shab0pmtOMQWuvNMQa3gRC
-OKbaM3A6zjvAl3rjFRBrGORqbu1E/InLOSXWuB8knYVf8LkWEDRjOHqMO3pJ
------END RSA PRIVATE KEY-----
diff --git a/apex/com.android.telephony.pk8 b/apex/com.android.telephony.pk8
deleted file mode 100644
index b15a884..0000000
--- a/apex/com.android.telephony.pk8
+++ /dev/null
Binary files differ
diff --git a/apex/com.android.telephony.x509.pem b/apex/com.android.telephony.x509.pem
deleted file mode 100644
index 8b45823..0000000
--- a/apex/com.android.telephony.x509.pem
+++ /dev/null
@@ -1,35 +0,0 @@
------BEGIN CERTIFICATE-----
-MIIGKTCCBBGgAwIBAgIUCmopA1YmjspwjjHHjmtsDPqxBxgwDQYJKoZIhvcNAQEL
-BQAwgaIxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQH
-DA1Nb3VudGFpbiBWaWV3MRAwDgYDVQQKDAdBbmRyb2lkMRAwDgYDVQQLDAdBbmRy
-b2lkMR4wHAYDVQQDDBVjb20uYW5kcm9pZC50ZWxlcGhvbnkxIjAgBgkqhkiG9w0B
-CQEWE2FuZHJvaWRAYW5kcm9pZC5jb20wIBcNMTkxMjA0MDAzNjAxWhgPNDc1NzEw
-MzAw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KYrj6MA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZI
-hvcNAQELBQADggIBABoGWqoOfPBsXFYzP7aNhywhuCr6ddjAi3ss9vwod6JuVuVg
-Inuw1i/qPb/bO1JFEwYVH3w0JASMwzIl9h5sQv++z0P+cWsLW02AXyszb0jGD3CI
-ni/irO5PO0DdaTSHQWc8DEv0293EcqpKWmQDQ2XWH19rJ5f+Gx1046sFlUi633D2
-sFO5dG94pCtT/TcqwwkeEwA6cV2Re8F1AW8elal3sINBU5MI/OJ3GQDe+pqp9VTg
-xIEQfZ9oP6Ewl6Ect+M2hVG5X4mCk9HQL7aSuPKo2Ej6l3Xq4aQYlpO4wOVZgCJC
-chMbdAn2pjuk8+mDSR39hdIusOgr7zLZscmaGKyoxVz9KVNwd/mmu+9/mftGfYae
-RomF15hVnkhZAw21fSnhKry62+DuKt2WIyu5LqvTvRxFs0Hvoy3wrQY/oruHlgk1
-J1v1rXm3ZTrh2qv1XG8mOdTegurEvjkYQm0E38jdlkhByIHmhDdBARX2Aeb7Lrd8
-9k/7tr9+58+45punZBBMX6iW1xfwaCDF8xfZrrC96azXP6Kv/JZTxbfNm/dqHyKK
-zM2WhELaoJg7uFO9TC5eMsnBQzDoYXsr3Mu7nC7V1Bs/D7jYmFG0dG0LQJwUUGr1
-WqJT4LB0BMnzNrMH1hTQTBVYDlfn7c6fnihNBOWQt72x2GGFQsGAMUWb7pxC
------END CERTIFICATE-----
diff --git a/apex/testing/Android.bp b/apex/testing/Android.bp
deleted file mode 100644
index 1c6f4a3..0000000
--- a/apex/testing/Android.bp
+++ /dev/null
@@ -1,30 +0,0 @@
-// Copyright (C) 2019 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 {
-    // See: http://go/android-license-faq
-    default_applicable_licenses: ["Android-Apache-2.0"],
-}
-
-apex {
-    name: "test_com.android.telephony",
-    visibility: [
-        "//system/apex/tests",
-    ],
-    defaults: ["com.android.telephony-defaults"],
-    manifest: "test_manifest.json",
-    file_contexts: ":com.android.telephony-file_contexts",
-    // Test APEX, should never be installed
-    installable: false,
-}
diff --git a/apex/testing/AndroidManifest.xml b/apex/testing/AndroidManifest.xml
deleted file mode 100644
index e2af9f5..0000000
--- a/apex/testing/AndroidManifest.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-          package="com.android.telephony">
-    <!-- APEX does not have classes.dex -->
-    <application android:hasCode="false" />
-    <uses-sdk
-        android:targetSdkVersion="30"
-    />
-</manifest>
\ No newline at end of file
diff --git a/apex/testing/test_manifest.json b/apex/testing/test_manifest.json
deleted file mode 100644
index 30bfda2..0000000
--- a/apex/testing/test_manifest.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
-  "name": "com.android.telephony",
-  "version": 2147483647
-}
\ No newline at end of file
diff --git a/src/com/android/phone/CallBarringEditPreference.java b/src/com/android/phone/CallBarringEditPreference.java
index 757600e..34c017c 100644
--- a/src/com/android/phone/CallBarringEditPreference.java
+++ b/src/com/android/phone/CallBarringEditPreference.java
@@ -101,9 +101,8 @@
     }
 
     void init(TimeConsumingPreferenceListener listener, boolean skipReading, Phone phone) {
-        if (DBG) {
-            Log.d(LOG_TAG, "init: phone id = " + phone.getPhoneId());
-        }
+        Log.d(LOG_TAG, "init: phone id = " + phone.getPhoneId());
+
         mPhone = phone;
 
         mTcpListener = listener;
@@ -184,10 +183,9 @@
     @Override
     protected void onDialogClosed(boolean positiveResult) {
         super.onDialogClosed(positiveResult);
-        if (DBG) {
-            Log.d(LOG_TAG, "onDialogClosed: mButtonClicked=" + mButtonClicked + ", positiveResult="
-                    + positiveResult);
-        }
+        Log.d(LOG_TAG, "onDialogClosed: mButtonClicked=" + mButtonClicked + ", positiveResult="
+                + positiveResult);
+
         if (mButtonClicked != DialogInterface.BUTTON_NEGATIVE) {
             String password = getEditText().getText().toString();
 
@@ -199,9 +197,8 @@
                 return;
             }
 
-            if (DBG) {
-                Log.d(LOG_TAG, "onDialogClosed: password=" + password);
-            }
+            Log.d(LOG_TAG, "onDialogClosed");
+
             // Send set call barring message to RIL layer.
             mPhone.setCallBarring(mFacility, !mIsActivated, password,
                     mHandler.obtainMessage(MyHandler.MESSAGE_SET_CALL_BARRING),
@@ -214,9 +211,7 @@
 
     void handleCallBarringResult(boolean status) {
         mIsActivated = status;
-        if (DBG) {
-            Log.d(LOG_TAG, "handleCallBarringResult: mIsActivated=" + mIsActivated);
-        }
+        Log.i(LOG_TAG, "handleCallBarringResult: mIsActivated=" + mIsActivated);
     }
 
     private static int getServiceClassForCallBarring(Phone phone) {
@@ -277,9 +272,7 @@
                 return;
             }
 
-            if (DBG) {
-                Log.d(LOG_TAG, "handleGetCallBarringResponse: done");
-            }
+            Log.i(LOG_TAG, "handleGetCallBarringResponse: done");
 
             AsyncResult ar = (AsyncResult) msg.obj;
 
@@ -291,9 +284,7 @@
 
             // Unsuccessful query for call barring.
             if (ar.exception != null) {
-                if (DBG) {
-                    Log.d(LOG_TAG, "handleGetCallBarringResponse: ar.exception=" + ar.exception);
-                }
+                Log.i(LOG_TAG, "handleGetCallBarringResponse: ar.exception=" + ar.exception);
                 pref.mTcpListener.onException(pref, (CommandException) ar.exception);
             } else {
                 if (ar.userObj instanceof Throwable) {
@@ -301,18 +292,14 @@
                 }
                 int[] ints = (int[]) ar.result;
                 if (ints.length == 0) {
-                    if (DBG) {
-                        Log.d(LOG_TAG, "handleGetCallBarringResponse: ar.result.length==0");
-                    }
+                    Log.i(LOG_TAG, "handleGetCallBarringResponse: ar.result.length==0");
                     pref.setEnabled(false);
                     pref.mTcpListener.onError(pref, RESPONSE_ERROR);
                 } else {
                     pref.handleCallBarringResult(ints[0] != 0);
-                    if (DBG) {
-                        Log.d(LOG_TAG,
-                                "handleGetCallBarringResponse: CB state successfully queried: "
-                                        + ints[0]);
-                    }
+                    Log.i(LOG_TAG,
+                            "handleGetCallBarringResponse: CB state successfully queried: "
+                                    + ints[0]);
                 }
             }
             // Update call barring status.
@@ -329,13 +316,9 @@
             AsyncResult ar = (AsyncResult) msg.obj;
 
             if (ar.exception != null || ar.userObj instanceof Throwable) {
-                if (DBG) {
-                    Log.d(LOG_TAG, "handleSetCallBarringResponse: ar.exception=" + ar.exception);
-                }
+                Log.i(LOG_TAG, "handleSetCallBarringResponse: ar.exception=" + ar.exception);
             }
-            if (DBG) {
-                Log.d(LOG_TAG, "handleSetCallBarringResponse: re-get call barring option");
-            }
+            Log.i(LOG_TAG, "handleSetCallBarringResponse: re-get call barring option");
             pref.mPhone.getCallBarring(
                     pref.mFacility,
                     "",
diff --git a/src/com/android/phone/PhoneGlobals.java b/src/com/android/phone/PhoneGlobals.java
index 426c473..99e73ff 100644
--- a/src/com/android/phone/PhoneGlobals.java
+++ b/src/com/android/phone/PhoneGlobals.java
@@ -32,7 +32,6 @@
 import android.net.ConnectivityManager;
 import android.net.Uri;
 import android.os.AsyncResult;
-import android.os.Bundle;
 import android.os.Handler;
 import android.os.Message;
 import android.os.PersistableBundle;
@@ -47,6 +46,7 @@
 import android.telephony.ServiceState;
 import android.telephony.SubscriptionInfo;
 import android.telephony.SubscriptionManager;
+import android.telephony.TelephonyCallback;
 import android.telephony.TelephonyLocalConnection;
 import android.telephony.TelephonyManager;
 import android.telephony.data.ApnSetting;
@@ -60,6 +60,7 @@
 import com.android.internal.telephony.IccCardConstants;
 import com.android.internal.telephony.MmiCode;
 import com.android.internal.telephony.Phone;
+import com.android.internal.telephony.PhoneConfigurationManager;
 import com.android.internal.telephony.PhoneConstants;
 import com.android.internal.telephony.PhoneFactory;
 import com.android.internal.telephony.SettingsObserver;
@@ -124,6 +125,7 @@
     private static final int EVENT_DATA_ROAMING_SETTINGS_CHANGED = 15;
     private static final int EVENT_MOBILE_DATA_SETTINGS_CHANGED = 16;
     private static final int EVENT_CARRIER_CONFIG_CHANGED = 17;
+    private static final int EVENT_MULTI_SIM_CONFIG_CHANGED = 18;
 
     // The MMI codes are also used by the InCallScreen.
     public static final int MMI_INITIATE = 51;
@@ -208,6 +210,30 @@
     private final SettingsObserver mSettingsObserver;
     private BinderCallsStats.SettingsObserver mBinderCallsSettingsObserver;
 
+    // Mapping of phone ID to the associated TelephonyCallback. These should be registered without
+    // fine or coarse location since we only use ServiceState for
+    private PhoneAppCallback[] mTelephonyCallbacks;
+
+    private class PhoneAppCallback extends TelephonyCallback implements
+            TelephonyCallback.ServiceStateListener {
+        private final int mSubId;
+
+        PhoneAppCallback(int subId) {
+            mSubId = subId;
+        }
+
+        @Override
+        public void onServiceStateChanged(ServiceState serviceState) {
+            // Note when registering that we should be registering with INCLUDE_LOCATION_DATA_NONE.
+            // PhoneGlobals only uses the state and roaming status, which does not require location.
+            handleServiceStateChanged(serviceState, mSubId);
+        }
+
+        public int getSubId() {
+            return mSubId;
+        }
+    }
+
     private static class EventSimStateChangedBag {
         final int mPhoneId;
         final String mIccStatus;
@@ -339,10 +365,44 @@
                     // refresh the message waiting (voicemail) indicator.
                     refreshMwiIndicator(subId);
                     phone = getPhone(subId);
-                    if (phone != null && isSimLocked(phone)) {
-                        // pass in subType=-1 so handleSimLock can find the actual subType if
-                        // needed. This is safe as valid values for subType are >= 0
-                        handleSimLock(-1, phone);
+                    if (phone != null) {
+                        if (isSimLocked(phone)) {
+                            // pass in subType=-1 so handleSimLock can find the actual subType if
+                            // needed. This is safe as valid values for subType are >= 0
+                            handleSimLock(-1, phone);
+                        }
+                        TelephonyManager tm = getSystemService(TelephonyManager.class);
+                        PhoneAppCallback callback = mTelephonyCallbacks[phone.getPhoneId()];
+                        // TODO: We may need to figure out a way to unregister if subId is invalid
+                        tm.createForSubscriptionId(callback.getSubId())
+                                .unregisterTelephonyCallback(callback);
+                        callback = new PhoneAppCallback(subId);
+                        tm.createForSubscriptionId(subId).registerTelephonyCallback(
+                                TelephonyManager.INCLUDE_LOCATION_DATA_NONE, mHandler::post,
+                                callback);
+                        mTelephonyCallbacks[phone.getPhoneId()] = callback;
+                    }
+                    break;
+                case EVENT_MULTI_SIM_CONFIG_CHANGED:
+                    int activeModems = (int) ((AsyncResult) msg.obj).result;
+                    TelephonyManager tm = getSystemService(TelephonyManager.class);
+                    // Unregister all previous callbacks
+                    for (int phoneId = 0; phoneId < mTelephonyCallbacks.length; phoneId++) {
+                        PhoneAppCallback callback = mTelephonyCallbacks[phoneId];
+                        if (callback != null) {
+                            tm.createForSubscriptionId(callback.getSubId())
+                                    .unregisterTelephonyCallback(callback);
+                            mTelephonyCallbacks[phoneId] = null;
+                        }
+                    }
+                    // Register callbacks for all active modems
+                    for (int phoneId = 0; phoneId < activeModems; phoneId++) {
+                        int sub = PhoneFactory.getPhone(phoneId).getSubId();
+                        PhoneAppCallback callback = new PhoneAppCallback(sub);
+                        tm.createForSubscriptionId(sub).registerTelephonyCallback(
+                                TelephonyManager.INCLUDE_LOCATION_DATA_NONE, mHandler::post,
+                                callback);
+                        mTelephonyCallbacks[phoneId] = callback;
                     }
                     break;
             }
@@ -363,11 +423,11 @@
         // Initialize the shim from frameworks/opt/telephony into packages/services/Telephony.
         TelephonyLocalConnection.setInstance(new LocalConnectionImpl(this));
 
+        TelephonyManager tm = getSystemService(TelephonyManager.class);
         // Cache the "voice capable" flag.
         // This flag currently comes from a resource (which is
         // overrideable on a per-product basis):
-        sVoiceCapable = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE))
-                .isVoiceCapable();
+        sVoiceCapable = tm.isVoiceCapable();
         // ...but this might eventually become a PackageManager "system
         // feature" instead, in which case we'd do something like:
         // sVoiceCapable =
@@ -480,12 +540,24 @@
                     new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
             intentFilter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
             intentFilter.addAction(TelephonyIntents.ACTION_RADIO_TECHNOLOGY_CHANGED);
-            intentFilter.addAction(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED);
             intentFilter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
             intentFilter.addAction(TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED);
             intentFilter.addAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
             registerReceiver(mReceiver, intentFilter);
 
+            PhoneConfigurationManager.registerForMultiSimConfigChange(
+                    mHandler, EVENT_MULTI_SIM_CONFIG_CHANGED, null);
+
+            mTelephonyCallbacks = new PhoneAppCallback[tm.getSupportedModemCount()];
+
+            for (Phone phone : PhoneFactory.getPhones()) {
+                int subId = phone.getSubId();
+                PhoneAppCallback callback = new PhoneAppCallback(subId);
+                tm.createForSubscriptionId(subId).registerTelephonyCallback(
+                        TelephonyManager.INCLUDE_LOCATION_DATA_NONE, mHandler::post, callback);
+                mTelephonyCallbacks[phone.getPhoneId()] = callback;
+            }
+
             mCarrierVvmPackageInstalledReceiver.register(this);
 
             //set the default values for the preferences in the phone.
@@ -731,8 +803,6 @@
                 String newPhone = intent.getStringExtra(PhoneConstants.PHONE_NAME_KEY);
                 Log.d(LOG_TAG, "Radio technology switched. Now " + newPhone + " is active.");
                 initForNewRadioTechnology();
-            } else if (action.equals(TelephonyIntents.ACTION_SERVICE_STATE_CHANGED)) {
-                handleServiceStateChanged(intent);
             } else if (action.equals(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED)) {
                 int phoneId = intent.getIntExtra(PhoneConstants.PHONE_KEY, 0);
                 phoneInEcm = PhoneFactory.getPhone(phoneId);
@@ -782,33 +852,17 @@
         }
     }
 
-    private void handleServiceStateChanged(Intent intent) {
-        /**
-         * This used to handle updating EriTextWidgetProvider this routine
-         * and and listening for ACTION_SERVICE_STATE_CHANGED intents could
-         * be removed. But leaving just in case it might be needed in the near
-         * future.
-         */
-
+    private void handleServiceStateChanged(ServiceState serviceState, int subId) {
         if (VDBG) Log.v(LOG_TAG, "handleServiceStateChanged");
-        // If service just returned, start sending out the queued messages
-        Bundle extras = intent.getExtras();
-        if (extras != null) {
-            ServiceState ss = ServiceState.newFromBundle(extras);
-            if (ss != null) {
-                int state = ss.getState();
-                int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY,
-                        SubscriptionManager.INVALID_SUBSCRIPTION_ID);
-                notificationMgr.updateNetworkSelection(state, subId);
+        int state = serviceState.getState();
+        notificationMgr.updateNetworkSelection(state, subId);
 
-                if (VDBG) {
-                    Log.v(LOG_TAG, "subId=" + subId + ",mDefaultDataSubId="
-                            + mDefaultDataSubId + ",ss roaming=" + ss.getDataRoaming());
-                }
-                if (subId == mDefaultDataSubId) {
-                    updateDataRoamingStatus();
-                }
-            }
+        if (VDBG) {
+            Log.v(LOG_TAG, "subId=" + subId + ", mDefaultDataSubId="
+                    + mDefaultDataSubId + ", ss roaming=" + serviceState.getDataRoaming());
+        }
+        if (subId == mDefaultDataSubId) {
+            updateDataRoamingStatus();
         }
     }
 
diff --git a/src/com/android/phone/PhoneInterfaceManager.java b/src/com/android/phone/PhoneInterfaceManager.java
index acf9db5..66cef64 100755
--- a/src/com/android/phone/PhoneInterfaceManager.java
+++ b/src/com/android/phone/PhoneInterfaceManager.java
@@ -751,10 +751,14 @@
                                 IccOpenLogicalChannelResponse.STATUS_NO_ERROR, selectResponse);
 
                         uiccPort = getUiccPortFromRequest(request);
-                        IccLogicalChannelRequest channelRequest =
-                                (IccLogicalChannelRequest) request.argument;
-                        channelRequest.channel = channelId;
-                        uiccPort.onLogicalChannelOpened(channelRequest);
+                        if (uiccPort == null) {
+                            loge("EVENT_OPEN_CHANNEL_DONE: UiccPort is null");
+                        } else {
+                            IccLogicalChannelRequest channelRequest =
+                                    (IccLogicalChannelRequest) request.argument;
+                            channelRequest.channel = channelId;
+                            uiccPort.onLogicalChannelOpened(channelRequest);
+                        }
                     } else {
                         if (ar.result == null) {
                             loge("iccOpenLogicalChannel: Empty response");
@@ -800,8 +804,12 @@
                     if (ar.exception == null) {
                         request.result = true;
                         uiccPort = getUiccPortFromRequest(request);
-                        final int channelId = (Integer) request.argument;
-                        uiccPort.onLogicalChannelClosed(channelId);
+                        if (uiccPort == null) {
+                            loge("EVENT_CLOSE_CHANNEL_DONE: UiccPort is null");
+                        } else {
+                            final int channelId = (Integer) request.argument;
+                            uiccPort.onLogicalChannelClosed(channelId);
+                        }
                     } else {
                         request.result = false;
                         Exception exception = null;
@@ -2369,7 +2377,8 @@
                 ? getDefaultPhone() : getPhone(subId);
     }
 
-    private UiccPort getUiccPortFromRequest(MainThreadRequest request) {
+    @Nullable
+    private UiccPort getUiccPortFromRequest(@NonNull MainThreadRequest request) {
         Phone phone = getPhoneFromRequest(request);
         return phone == null ? null :
                 UiccController.getInstance().getUiccPort(phone.getPhoneId());
diff --git a/src/com/android/phone/TimeConsumingPreferenceActivity.java b/src/com/android/phone/TimeConsumingPreferenceActivity.java
index caef176..d21f6a8 100644
--- a/src/com/android/phone/TimeConsumingPreferenceActivity.java
+++ b/src/com/android/phone/TimeConsumingPreferenceActivity.java
@@ -197,6 +197,7 @@
 
     @Override
     public void onException(Preference preference, CommandException exception) {
+        Log.i(LOG_TAG, "onError, preference=" + preference.getKey() + ", exception=" + exception);
         if (exception.getCommandError() == CommandException.Error.FDN_CHECK_FAILURE) {
             onError(preference, FDN_CHECK_FAILURE);
         } else if (exception.getCommandError() == CommandException.Error.RADIO_NOT_AVAILABLE) {
@@ -210,6 +211,10 @@
             onError(preference, STK_CC_SS_TO_USSD_ERROR);
         } else if (exception.getCommandError() == CommandException.Error.SS_MODIFIED_TO_SS) {
             onError(preference, STK_CC_SS_TO_SS_ERROR);
+        } else if (exception.getCommandError() == CommandException.Error.REQUEST_NOT_SUPPORTED) {
+            preference.setEnabled(false);
+            // Don't show an error dialog; just disable it if the request is not supported.
+            Log.i(LOG_TAG, "onError, suppress error dialog as not supported");
         } else {
             preference.setEnabled(false);
             onError(preference, EXCEPTION_ERROR);
diff --git a/tests/src/com/android/phone/LocationAccessPolicyTest.java b/tests/src/com/android/phone/LocationAccessPolicyTest.java
index 84bf619..58e7fbd 100644
--- a/tests/src/com/android/phone/LocationAccessPolicyTest.java
+++ b/tests/src/com/android/phone/LocationAccessPolicyTest.java
@@ -29,6 +29,7 @@
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
+import android.content.res.Resources;
 import android.location.LocationManager;
 import android.os.Build;
 import android.os.UserHandle;
@@ -149,11 +150,13 @@
 
     private static final int TESTING_UID = 10001;
     private static final int TESTING_PID = 8009;
+    private static final String TESTING_CALLING_PACKAGE = "com.android.phone";
 
     @Mock Context mContext;
     @Mock AppOpsManager mAppOpsManager;
     @Mock LocationManager mLocationManager;
     @Mock PackageManager mPackageManager;
+    @Mock Resources mResources;
     Scenario mScenario;
 
     @Before
@@ -163,6 +166,10 @@
         mockContextSystemService(LocationManager.class, mLocationManager);
         mockContextSystemService(PackageManager.class, mPackageManager);
         when(mContext.getPackageManager()).thenReturn(mPackageManager);
+        when(mContext.getResources()).thenReturn(mResources);
+        when(mResources.getStringArray(
+                com.android.internal.R.array.config_serviceStateLocationAllowedPackages))
+                .thenReturn(new String[]{TESTING_CALLING_PACKAGE});
     }
 
     private <T> void mockContextSystemService(Class<T> clazz , T obj) {
@@ -249,6 +256,20 @@
                 .build());
 
         scenarios.add(new Scenario.Builder()
+                .setName("System location is off but package is allowlisted for location")
+                .setAppHasFineManifest(true)
+                .setFineAppOp(AppOpsManager.MODE_ALLOWED)
+                .setAppSdkLevel(Build.VERSION_CODES.P)
+                .setIsDynamicLocationEnabled(false)
+                .setQuery(getDefaultQueryBuilder()
+                        .setMinSdkVersionForEnforcement(Build.VERSION_CODES.N)
+                        .setMinSdkVersionForFine(Build.VERSION_CODES.N)
+                        .setMinSdkVersionForCoarse(Build.VERSION_CODES.N)
+                        .setCallingPackage(TESTING_CALLING_PACKAGE).build())
+                .setExpectedResult(LocationAccessPolicy.LocationPermissionResult.ALLOWED)
+                .build());
+
+        scenarios.add(new Scenario.Builder()
                 .setName("App on latest SDK level has all proper permissions for fine")
                 .setAppHasFineManifest(true)
                 .setFineAppOp(AppOpsManager.MODE_ALLOWED)