Merge "Purge invalid SIP phone accounts at startup." into mnc-dev
diff --git a/sip/src/com/android/services/telephony/sip/SipAccountRegistry.java b/sip/src/com/android/services/telephony/sip/SipAccountRegistry.java
index 0a08c61..dd76c27 100644
--- a/sip/src/com/android/services/telephony/sip/SipAccountRegistry.java
+++ b/sip/src/com/android/services/telephony/sip/SipAccountRegistry.java
@@ -113,9 +113,30 @@
     }
 
     void setup(Context context) {
+        verifyAndPurgeInvalidPhoneAccounts(context);
         startSipProfilesAsync(context, (String) null, false);
+    }
 
-        // TODO: remove orphaned SIP Accounts
+    /**
+     * Checks the existing SIP phone {@link PhoneAccount}s registered with telecom and deletes any
+     * invalid accounts.
+     *
+     * @param context The context.
+     */
+    void verifyAndPurgeInvalidPhoneAccounts(Context context) {
+        TelecomManager telecomManager = TelecomManager.from(context);
+        SipProfileDb profileDb = new SipProfileDb(context);
+        List<PhoneAccountHandle> accountHandles = telecomManager.getPhoneAccountsSupportingScheme(
+                PhoneAccount.SCHEME_SIP);
+
+        for (PhoneAccountHandle accountHandle : accountHandles) {
+            String profileName = SipUtil.getSipProfileNameFromPhoneAccount(accountHandle);
+            SipProfile profile = profileDb.retrieveSipProfileFromName(profileName);
+            if (profile == null) {
+                log("verifyAndPurgeInvalidPhoneAccounts, deleting account: " + accountHandle);
+                telecomManager.unregisterPhoneAccount(accountHandle);
+            }
+        }
     }
 
     /**