title: How to use a specific bluetooth device's microphone on Android?
body: <p>So, I have an app which needs to use a speaker and a microphone. It has to work with and without Bluetooth. Basically, when bluetooth headset or car's handsfree system are connected I want the app to use both the speaker and the microphone (this is the tricky part) via bluetooth and when not - the handset's speaker and microphone.</p>
  
  <p>Initially I was hoping to get away the platform's manager, but...it works well for the speaker, but not for the microphone. Even when the speaker is switched to bluetooth, it still continues using the handset's mic. </p>
  
  <p>I added calls to <code>startBluetoothSco() and setBluetoothScoOn()</code> and it got better - now it actually works well with a headset, but...not with the car's handsfree system. While with the headset it does use the bluetooth mic, it does not with the car's handsfree system.</p>
  
  <p>I suspect (but I don't even know how to check) that this has something to do with the fact that the car presents itself as two bluetooth devices - media player and headset.</p>
  
  <p>Any words of wisdom? I'm totally lost here...Android's AudioManager bluetooth control API is a total mess...</p>
  
  <p>UPDATE - this is the code I'm using:</p>
  
  <pre><code>private static boolean isBluetoothHeadsetConnected() {
      BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
      return mBluetoothAdapter != null &amp;&amp; mBluetoothAdapter.isEnabled()
              &amp;&amp; mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED;
  }
  
  private boolean checkBlueTooth()  {
      if (!isBluetoothHeadsetConnected()) {
          return false;
      }
  
      return true;
  }
  
  private void useBluetooth() {
      AudioManager audioManager;
      audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
      audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
      audioManager.startBluetoothSco();
      audioManager.setBluetoothScoOn(true);
  }
  
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
  
      if (checkBlueTooth()) {
          start();
      } else {
          BroadcastReceiver scoReceiver = new BroadcastReceiver() {
              @Override
              public void onReceive(Context context, Intent intent) {
                  if (intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1) ==
                          AudioManager.SCO_AUDIO_STATE_CONNECTED) {
                      start();
                  }
              }
          };
          IntentFilter intentFilter = new IntentFilter();
          intentFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
  
          this.registerReceiver(scoReceiver, intentFilter);
          useBluetooth();
      }
  }
  </code></pre>