DO NOT MERGE Use E PhoneAccount for MT ECM Call

Use the correct Emergency PhoneAccount for a MT call on a phone with no
SIM that is in ECM. Also, reject incoming SIP calls that are received on
a disabled PhoneAccount instead of crashing the Phone process.

Bug: 27820226
Change-Id: I79aa1eb9d07760a6d31d97ec2e2cd3c430a43215
diff --git a/sip/src/com/android/services/telephony/sip/SipBroadcastReceiver.java b/sip/src/com/android/services/telephony/sip/SipBroadcastReceiver.java
index 545854d..d1bd4e2 100644
--- a/sip/src/com/android/services/telephony/sip/SipBroadcastReceiver.java
+++ b/sip/src/com/android/services/telephony/sip/SipBroadcastReceiver.java
@@ -21,6 +21,7 @@
 import android.content.Intent;
 import android.net.sip.SipManager;
 import android.os.Bundle;
+import android.telecom.PhoneAccount;
 import android.telecom.PhoneAccountHandle;
 import android.telecom.TelecomManager;
 import android.util.Log;
@@ -68,7 +69,13 @@
         if (accountHandle != null) {
             Bundle extras = new Bundle();
             extras.putParcelable(SipUtil.EXTRA_INCOMING_CALL_INTENT, intent);
-            TelecomManager.from(context).addNewIncomingCall(accountHandle, extras);
+            TelecomManager tm = TelecomManager.from(context);
+            PhoneAccount phoneAccount = tm.getPhoneAccount(accountHandle);
+            if (phoneAccount != null && phoneAccount.isEnabled()) {
+                tm.addNewIncomingCall(accountHandle, extras);
+            } else {
+                log("takeCall, PhoneAccount is disabled. Not accepting incoming call...");
+            }
         }
     }
 
diff --git a/src/com/android/phone/PhoneUtils.java b/src/com/android/phone/PhoneUtils.java
index e1f8036..26a5109 100644
--- a/src/com/android/phone/PhoneUtils.java
+++ b/src/com/android/phone/PhoneUtils.java
@@ -73,6 +73,7 @@
  * Misc utilities for the Phone app.
  */
 public class PhoneUtils {
+    public static final String EMERGENCY_ACCOUNT_HANDLE_ID = "E";
     private static final String LOG_TAG = "PhoneUtils";
     private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
 
@@ -2469,7 +2470,8 @@
             Phone phone, String prefix, boolean isEmergency) {
         // TODO: Should use some sort of special hidden flag to decorate this account as
         // an emergency-only account
-        String id = isEmergency ? "E" : prefix + String.valueOf(phone.getIccSerialNumber());
+        String id = isEmergency ? EMERGENCY_ACCOUNT_HANDLE_ID : prefix +
+                String.valueOf(phone.getIccSerialNumber());
         return makePstnPhoneAccountHandleWithPrefix(id, prefix, isEmergency);
     }
 
diff --git a/src/com/android/services/telephony/PstnIncomingCallNotifier.java b/src/com/android/services/telephony/PstnIncomingCallNotifier.java
index 5f64f6d..7dcfb06 100644
--- a/src/com/android/services/telephony/PstnIncomingCallNotifier.java
+++ b/src/com/android/services/telephony/PstnIncomingCallNotifier.java
@@ -26,16 +26,19 @@
 import android.os.Handler;
 import android.os.Message;
 import android.telecom.PhoneAccount;
+import android.telecom.PhoneAccountHandle;
 import android.telecom.TelecomManager;
 import android.telephony.TelephonyManager;
 import android.text.TextUtils;
 
 import com.android.internal.telephony.Call;
+import com.android.internal.telephony.CallStateException;
 import com.android.internal.telephony.Connection;
 import com.android.internal.telephony.Phone;
 import com.android.internal.telephony.PhoneConstants;
 import com.android.internal.telephony.PhoneProxy;
 import com.android.internal.telephony.TelephonyIntents;
+import com.android.internal.telephony.cdma.CDMAPhone;
 import com.android.internal.telephony.cdma.CdmaCallWaitingNotification;
 import com.android.phone.PhoneUtils;
 
@@ -230,8 +233,16 @@
                 Uri uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, connection.getAddress(), null);
                 extras.putParcelable(TelecomManager.EXTRA_UNKNOWN_CALL_HANDLE, uri);
             }
-            TelecomManager.from(mPhoneProxy.getContext()).addNewUnknownCall(
-                    PhoneUtils.makePstnPhoneAccountHandle(mPhoneProxy), extras);
+            PhoneAccountHandle handle = findCorrectPhoneAccountHandle();
+            if (handle == null) {
+                try {
+                    connection.hangup();
+                } catch (CallStateException e) {
+                    // connection already disconnected. Do nothing
+                }
+            } else {
+                TelecomManager.from(mPhoneProxy.getContext()).addNewUnknownCall(handle, extras);
+            }
         } else {
             Log.i(this, "swapped an old connection, new one is: %s", connection);
         }
@@ -248,8 +259,44 @@
             Uri uri = Uri.fromParts(PhoneAccount.SCHEME_TEL, connection.getAddress(), null);
             extras.putParcelable(TelecomManager.EXTRA_INCOMING_CALL_ADDRESS, uri);
         }
-        TelecomManager.from(mPhoneProxy.getContext()).addNewIncomingCall(
-                PhoneUtils.makePstnPhoneAccountHandle(mPhoneProxy), extras);
+        PhoneAccountHandle handle = findCorrectPhoneAccountHandle();
+        if (handle == null) {
+            try {
+                connection.hangup();
+            } catch (CallStateException e) {
+                // connection already disconnected. Do nothing
+            }
+        } else {
+            TelecomManager.from(mPhoneProxy.getContext()).addNewIncomingCall(handle, extras);
+        }
+    }
+
+    /**
+     * Returns the PhoneAccount associated with this {@code PstnIncomingCallNotifier}'s phone. On a
+     * device with No SIM or in airplane mode, it can return an Emergency-only PhoneAccount. If no
+     * PhoneAccount is registered with telecom, return null.
+     * @return A valid PhoneAccountHandle that is registered to Telecom or null if there is none
+     * registered.
+     */
+    private PhoneAccountHandle findCorrectPhoneAccountHandle() {
+        TelecomAccountRegistry telecomAccountRegistry = TelecomAccountRegistry.getInstance(null);
+        // Check to see if a the SIM PhoneAccountHandle Exists for the Call.
+        PhoneAccountHandle handle = PhoneUtils.makePstnPhoneAccountHandle(mPhoneBase);
+        if (telecomAccountRegistry.hasAccountEntryForPhoneAccount(handle)) {
+            return handle;
+        }
+        // The PhoneAccountHandle does not match any PhoneAccount registered in Telecom.
+        // This is only known to happen if there is no SIM card in the device and the device
+        // receives an MT call while in ECM. Use the Emergency PhoneAccount to receive the account.
+        PhoneAccountHandle emergencyHandle =
+                PhoneUtils.makePstnPhoneAccountHandleWithPrefix(mPhoneBase, "",
+                        true /* isEmergency */);
+        if(telecomAccountRegistry.hasAccountEntryForPhoneAccount(emergencyHandle)) {
+            Log.i(this, "Receiving MT call in ECM. Using Emergency PhoneAccount Instead.");
+            return emergencyHandle;
+        }
+        Log.w(this, "PhoneAccount not found.");
+        return null;
     }
 
     /**
diff --git a/src/com/android/services/telephony/TelecomAccountRegistry.java b/src/com/android/services/telephony/TelecomAccountRegistry.java
index 154fc33..474a76d 100644
--- a/src/com/android/services/telephony/TelecomAccountRegistry.java
+++ b/src/com/android/services/telephony/TelecomAccountRegistry.java
@@ -403,7 +403,7 @@
      * @param handle The {@link PhoneAccountHandle}.
      * @return {@code True} if an entry exists.
      */
-    private boolean hasAccountEntryForPhoneAccount(PhoneAccountHandle handle) {
+    boolean hasAccountEntryForPhoneAccount(PhoneAccountHandle handle) {
         for (AccountEntry entry : mAccounts) {
             if (entry.getPhoneAccountHandle().equals(handle)) {
                 return true;
diff --git a/src/com/android/services/telephony/TelephonyConnectionService.java b/src/com/android/services/telephony/TelephonyConnectionService.java
index 3d177af..f1b62c0 100644
--- a/src/com/android/services/telephony/TelephonyConnectionService.java
+++ b/src/com/android/services/telephony/TelephonyConnectionService.java
@@ -290,8 +290,17 @@
             PhoneAccountHandle connectionManagerPhoneAccount,
             ConnectionRequest request) {
         Log.i(this, "onCreateIncomingConnection, request: " + request);
-
-        Phone phone = getPhoneForAccount(request.getAccountHandle(), false);
+        // If there is an incoming emergency CDMA Call (while the phone is in ECBM w/ No SIM),
+        // make sure the PhoneAccount lookup retrieves the default Emergency Phone.
+        PhoneAccountHandle accountHandle = request.getAccountHandle();
+        boolean isEmergency = false;
+        if (accountHandle != null && PhoneUtils.EMERGENCY_ACCOUNT_HANDLE_ID.equals(
+                accountHandle.getId())) {
+            Log.i(this, "Emergency PhoneAccountHandle is being used for incoming call... " +
+                    "Treat as an Emergency Call.");
+            isEmergency = true;
+        }
+        Phone phone = getPhoneForAccount(accountHandle, isEmergency);
         if (phone == null) {
             return Connection.createFailedConnection(
                     DisconnectCauseUtil.toTelecomDisconnectCause(
@@ -337,8 +346,17 @@
     public Connection onCreateUnknownConnection(PhoneAccountHandle connectionManagerPhoneAccount,
             ConnectionRequest request) {
         Log.i(this, "onCreateUnknownConnection, request: " + request);
-
-        Phone phone = getPhoneForAccount(request.getAccountHandle(), false);
+        // Use the registered emergency Phone if the PhoneAccountHandle is set to Telephony's
+        // Emergency PhoneAccount
+        PhoneAccountHandle accountHandle = request.getAccountHandle();
+        boolean isEmergency = false;
+        if (accountHandle != null && PhoneUtils.EMERGENCY_ACCOUNT_HANDLE_ID.equals(
+                accountHandle.getId())) {
+            Log.i(this, "Emergency PhoneAccountHandle is being used for unknown call... " +
+                    "Treat as an Emergency Call.");
+            isEmergency = true;
+        }
+        Phone phone = getPhoneForAccount(accountHandle, isEmergency);
         if (phone == null) {
             return Connection.createFailedConnection(
                     DisconnectCauseUtil.toTelecomDisconnectCause(