Call onPhoneDestroyed when the service is unbound.

Bug: 17253031
Change-Id: I1a74e0f2fe1ec9172268638dba531c17d22dee99
diff --git a/telecomm/java/android/telecomm/Call.java b/telecomm/java/android/telecomm/Call.java
index a71f739..ecb0d4b 100644
--- a/telecomm/java/android/telecomm/Call.java
+++ b/telecomm/java/android/telecomm/Call.java
@@ -743,6 +743,16 @@
         fireStartActivity(intent);
     }
 
+    /** {@hide} */
+    final void internalSetDisconnected() {
+        if (mState != Call.STATE_DISCONNECTED) {
+            mState = Call.STATE_DISCONNECTED;
+            fireStateChanged(mState);
+            fireCallDestroyed();
+            mPhone.internalRemoveCall(this);
+        }
+    }
+
     private void fireStateChanged(int newState) {
         for (Listener listener : mListeners) {
             listener.onStateChanged(this, newState);
diff --git a/telecomm/java/android/telecomm/InCallService.java b/telecomm/java/android/telecomm/InCallService.java
index a062632..cbcee75 100644
--- a/telecomm/java/android/telecomm/InCallService.java
+++ b/telecomm/java/android/telecomm/InCallService.java
@@ -163,6 +163,16 @@
         return new InCallServiceBinder();
     }
 
+    @Override
+    public boolean onUnbind(Intent intent) {
+        Phone oldPhone = mPhone;
+        mPhone = null;
+
+        oldPhone.destroy();
+        onPhoneDestroyed(oldPhone);
+        return false;
+    }
+
     /**
      * Obtain the {@code Phone} associated with this {@code InCallService}.
      *
diff --git a/telecomm/java/android/telecomm/Phone.java b/telecomm/java/android/telecomm/Phone.java
index e125342..d90d954 100644
--- a/telecomm/java/android/telecomm/Phone.java
+++ b/telecomm/java/android/telecomm/Phone.java
@@ -20,7 +20,6 @@
 import android.app.PendingIntent;
 import android.util.ArrayMap;
 
-import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
@@ -83,7 +82,7 @@
 
     // A List allows us to keep the Calls in a stable iteration order so that casually developed
     // user interface components do not incur any spurious jank
-    private final List<Call> mCalls = new ArrayList<>();
+    private final List<Call> mCalls = new CopyOnWriteArrayList<>();
 
     // An unmodifiable view of the above List can be safely shared with subclass implementations
     private final List<Call> mUnmodifiableCalls = Collections.unmodifiableList(mCalls);
@@ -160,6 +159,18 @@
     }
 
     /**
+     * Called to destroy the phone and cleanup any lingering calls.
+     * @hide
+     */
+    final void destroy() {
+        for (Call call : mCalls) {
+            if (call.getState() != Call.STATE_DISCONNECTED) {
+                call.internalSetDisconnected();
+            }
+        }
+    }
+
+    /**
      * Adds a listener to this {@code Phone}.
      *
      * @param listener A {@code Listener} object.