ContextMap: Remove connection references when an app is removed

This fixes an issue which could cause a stale Bluetooth address to be
used. The issue would manifest itself when an app is added with a
connection ID, then the app is removed and app is re-added, causing
the original connection ID (which could be stale) to be used.

Bug: 30765855
Change-Id: Idacbbfb07d895bf9276fdd986100e832a54d81b0
diff --git a/src/com/android/bluetooth/gatt/ContextMap.java b/src/com/android/bluetooth/gatt/ContextMap.java
index e3044d5..0245727 100644
--- a/src/com/android/bluetooth/gatt/ContextMap.java
+++ b/src/com/android/bluetooth/gatt/ContextMap.java
@@ -190,6 +190,7 @@
             while (i.hasNext()) {
                 App entry = i.next();
                 if (entry.id == id) {
+                    removeConnectionsByAppId(id);
                     entry.unlinkToDeath();
                     entry.appScanStats.isRegistered = false;
                     i.remove();
@@ -205,7 +206,7 @@
     void addConnection(int id, int connId, String address) {
         synchronized (mConnections) {
             App entry = getById(id);
-            if (entry != null){
+            if (entry != null) {
                 mConnections.add(new Connection(connId, address, id));
             }
         }
@@ -228,6 +229,19 @@
     }
 
     /**
+     * Remove all connections for a given application ID.
+     */
+    void removeConnectionsByAppId(int appId) {
+        Iterator<Connection> i = mConnections.iterator();
+        while (i.hasNext()) {
+            Connection connection = i.next();
+            if (connection.appId == appId) {
+                i.remove();
+            }
+        }
+    }
+
+    /**
      * Get an application context by ID.
      */
     App getById(int id) {