Purge invalid SIP phone accounts at startup.

Adding changes to verify all the SIP phone accounts registered with
telecom and delete any invalid SIP accounts detected. SipAccountRegistry
will re-register phoneAccounts corresponding to the SIP profiles
present in the device.
This will also fix the recent change in SIP phone accounts to use
the SIP username as account handle ID instead of SIP URI. So, any
devices upgrading from L or lower releases will have new SIP
accounts automatically recreated with the new account Handle ID.

BUG: 23028921
Change-Id: I560569b4746605b1f0e7698f29178e18abf7019b
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);
+            }
+        }
     }
 
     /**