Merge "Speculative fix for BT race condition"
diff --git a/src/com/android/server/telecom/bluetooth/BluetoothDeviceManager.java b/src/com/android/server/telecom/bluetooth/BluetoothDeviceManager.java
index 72e5244..4800832 100644
--- a/src/com/android/server/telecom/bluetooth/BluetoothDeviceManager.java
+++ b/src/com/android/server/telecom/bluetooth/BluetoothDeviceManager.java
@@ -194,6 +194,10 @@
                 mHearingAidDeviceSyncIds.put(device, hiSyncId);
                 targetDeviceMap = mHearingAidDevicesByAddress;
             } else {
+                if (mBluetoothHeadsetService == null) {
+                    Log.w(this, "Headset service null when receiving device added broadcast");
+                    return;
+                }
                 targetDeviceMap = mHfpDevicesByAddress;
             }
             if (!targetDeviceMap.containsKey(device.getAddress())) {
diff --git a/tests/src/com/android/server/telecom/tests/BluetoothDeviceManagerTest.java b/tests/src/com/android/server/telecom/tests/BluetoothDeviceManagerTest.java
index c9b608e..9fd97f8 100644
--- a/tests/src/com/android/server/telecom/tests/BluetoothDeviceManagerTest.java
+++ b/tests/src/com/android/server/telecom/tests/BluetoothDeviceManagerTest.java
@@ -108,6 +108,20 @@
 
     @SmallTest
     @Test
+    public void testAddDeviceFailsWhenServicesAreNull() {
+        mBluetoothDeviceManager.setHeadsetServiceForTesting(null);
+        mBluetoothDeviceManager.setHearingAidServiceForTesting(null);
+
+        receiverUnderTest.onReceive(mContext,
+                buildConnectionActionIntent(BluetoothHeadset.STATE_CONNECTED, device1, false));
+        receiverUnderTest.onReceive(mContext,
+                buildConnectionActionIntent(BluetoothHeadset.STATE_CONNECTED, device2, true));
+
+        assertEquals(0, mBluetoothDeviceManager.getNumConnectedDevices());
+    }
+    
+    @SmallTest
+    @Test
     public void testMultiDeviceConnectAndDisconnect() {
         receiverUnderTest.onReceive(mContext,
                 buildConnectionActionIntent(BluetoothHeadset.STATE_CONNECTED, device1, false));