title: Using a Bluetooth Headset as a Mic and Speaker in a Voice Chat App
body: <p>I have a voice chat app, which works just fine. Currently I'm trying to make the app support bluetooth headsets in case any was connected. There are two cases that I need to handle:</p>
  
  <ol>
  <li>The bluetooth headset is connected before the call starts.</li>
  <li>The bluetooth headset connects to the device during the call.</li>
  </ol>
  
  <p>For the first case, the app should automatically starts using the headset as its default input/output audio device. On the other hand, the app, upon headset connection to the device, should switch from the current input/output audio device to the bluetooth headset.</p>
  
  <p>I was able to handle the first case successfully using the following code:</p>
  
  <pre><code>mAudioManager.setMode(0);
  mAudioManager.startBluetoothSco();
  mAudioManager.setBluetoothScoOn(true);
  mAudioManager.setMode(android.media.AudioManager.MODE_IN_CALL);
  </code></pre>
  
  <p>As for the second case, I created a <code>BroadcastReciever</code> that listens when a bluetooth headset is connected as follows:</p>
  
  <pre><code>mBroadcastReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
          String action = intent.getAction();
          if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
              mAudioManager.setMode(0);
              mAudioManager.startBluetoothSco();
              mAudioManager.setBluetoothScoOn(true);
              mAudioManager.setMode(android.media.AudioManager.MODE_IN_CALL);
          } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
              mAudioManager.setMode(0);
              mAudioManager.startBluetoothSco();
              mAudioManager.setBluetoothScoOn(false);
              mAudioManager.setMode(android.media.AudioManager.MODE_IN_CALL);
          }
      }
  };
  </code></pre>
  
  <p>The <code>BroadcastReciever</code> was able to detect headset connections/disconnections, and the call was directing the sound to the headset rather than the phone's earpiece. <strong>The issue is that the app keeps using the device's mic as the input audio device rather than the headset's</strong>. After a very long inspection, I realized that when the <code>BroadcastReciever</code> gets a notification that a headset is connected, <strong>I need to wait a little bit before calling <code>mAudioManager.startBluetoothSco();</code></strong> to get the app to use the headset's mic. </p>
  
  <p>The question is, what kind of event should I be listening to, after knowing that the bluetooth headset is connected, so that I can start capturing the voice from the headset's mic?</p>