title: Bluetooth : Service discovery failed
body: <p>I try to establish a Bluetooth connection between my Android App (on a Samsung phone running 4.1.2: the client) and my Laptop (Win7, 64bits: the server). It has always failed with a <em>Service discovery failed</em>.</p>
  
  <p>I read various topics about this (<a href="https://stackoverflow.com/questions/2207975/bluetooth-service-discovery-failed">here</a> and <a href="http://developer.android.com/guide/topics/connectivity/bluetooth.html" rel="nofollow noreferrer">there</a>) but it didn't solve my problem.</p>
  
  <p>I have two questions:</p>
  
  <ul>
  <li>what means the <em>well known UUID "00001101-0000-1000-8000-00805F9B34FB"</em> . Why/when should it be used ?</li>
  <li>any suggestion to investigate/solve my problem would be appreciated.</li>
  </ul>
  
  <p>Remarks:</p>
  
  <ul>
  <li>I tried to establish a secured and unsecured connection (same failure with both)</li>
  <li>I'm able to pair my laptop and my device from Settings>Bluetooth</li>
  <li>As suggested in comments : I tried with a randomly generated UUID (but the same on both side) instead of the <em>well known one</em>, but I still have exactly the same behavior.</li>
  </ul>
  
  <p>I have those permissions </p>
  
  <pre><code>&lt;uses-permission android:name="android.permission.BLUETOOTH"/&gt;
  &lt;uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/&gt;
  </code></pre>
  
  <p><strong>EDIT</strong></p>
  
  <p>Instead of harcoding the UUID on client side, I tried the following (but still get the same error):</p>
  
  <pre><code>UUID uuid = bluetoothDevice.getUuids()[bluetoothDevice.getUuids().length-1].getUuid();
  </code></pre>
  
  <p>The UUID of the echo-server is always the last one in the array.</p>
  
  <p><strong>END EDIT</strong></p>
  
  <p>Here are the relevant logs on the client:</p>
  
  <pre><code>08-22 12:30:28.627: ERROR/BluetoothService.cpp(12008): stopDiscoveryNative: D-Bus error in StopDiscovery: org.bluez.Error.Failed (Invalid discovery session)
  08-22 12:30:28.647: INFO/BluetoothSocket.cpp(18030): Setting Master socket option
  08-22 12:30:28.647: VERBOSE/BluetoothSocket.cpp(18030): ...fd 43 created (RFCOMM, lm = 7)
  08-22 12:30:28.687: DEBUG/BluetoothPolicyService(12008): getAllowBluetoothDataTransfer - showMsg: true
  08-22 12:30:28.687: DEBUG/BluetoothPolicyService(12008): MDM: isProfileEnabled = true
  08-22 12:30:28.697: DEBUG/BluetoothUtils(18030): isSocketAllowedBySecurityPolicy start : device null
  08-22 12:30:28.727: ERROR/BluetoothEventLoop.cpp(12008): onCreateDeviceResult: D-Bus error: org.bluez.Error.AlreadyExists (Already Exists)
  08-22 12:30:28.727: VERBOSE/BluetoothService.cpp(12008): discoverServicesNative
  08-22 12:30:28.727: VERBOSE/BluetoothService.cpp(12008): ... Object Path = /org/bluez/12635/hci0/dev_00_09_DD_50_88_54
  08-22 12:30:28.727: VERBOSE/BluetoothService.cpp(12008): ... Pattern = , strlen = 0
  08-22 12:30:29.138: VERBOSE/BluetoothEventLoop.cpp(12008): event_filter: Received signal org.bluez.Device:PropertyChanged from /org/bluez/12635/hci0/dev_00_09_DD_50_88_54
  08-22 12:30:29.138: DEBUG/BluetoothEventLoop(12008): Device property changed
  08-22 12:30:32.141: DEBUG/BluetoothA2DPStateReceiver(15827): BluetoothA2DPStateReceiver constructor call()
  08-22 12:30:32.141: DEBUG/BluetoothA2DPStateReceiver(15827): onReceive(): action = android.bluetooth.device.action.ACL_CONNECTED
  08-22 12:30:32.141: DEBUG/BluetoothA2DPStateReceiver(15827): ACTION_ACL_CONNECTED
  08-22 12:30:32.141: DEBUG/BluetoothA2DPSinkInfo(15827): checkBlackListCarkit() : isBlackListCarkit false
  08-22 12:30:32.161: DEBUG/BluetoothNotiBroadcastReceiver(15910): onReceive
  08-22 12:30:40.749: ERROR/Bluetooth(18030): Cannot connect
      java.io.IOException: Service discovery failed
      at android.bluetooth.BluetoothSocket$SdpHelper.doSdp(BluetoothSocket.java:475)
      at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:241)
      at com.company.BlueToothTestActivity.open(BlueToothTestActivity.java:48)
      at com.company.BlueToothTestActivity$1.run(BlueToothTestActivity.java:29)
  08-22 12:30:40.749: WARN/Bluetooth(18030): Unable to open connection !
  </code></pre>
  
  <hr>
  
  <p>Here is the code to reproduce the error (it's simplified version, it compiles and reproduce the error - at least on my hardware -)</p>
  
  <p><strong>Client</strong></p>
  
  <pre><code>import android.app.Activity;
  import android.bluetooth.BluetoothAdapter;
  import android.bluetooth.BluetoothDevice;
  import android.bluetooth.BluetoothSocket;
  import android.os.Bundle;
  import android.util.Log;
  import android.view.View;
  import android.widget.Button;
  import android.widget.LinearLayout;
  
  import java.io.IOException;
  import java.util.UUID;
  
  public class BlueToothTestActivity extends Activity {
  
  private String macAddress = "00:09:DD:50:88:54";  //hardcoded laptop macAddress
  private BluetoothAdapter mBluetoothAdapter;
  private BluetoothDevice bluetoothDevice;
  private BluetoothSocket socket;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);   
      Thread bluetoothClientThread = new Thread(){
          @Override
          public void run() {
              if(open()){
                  Log.i("Bluetooth","Connection is open !");
              }else{
                  Log.w("Bluetooth","Unable to open connection !");
              }
          }
      };
      bluetoothClientThread.start();
      initUI();
  }
  
  public boolean open() {
      mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
      bluetoothDevice = mBluetoothAdapter.getRemoteDevice(macAddress);
      String BT_UUID = "00001101-0000-1000-8000-00805F9B34FB";
      try {
          mBluetoothAdapter.cancelDiscovery();
          //socket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString(BT_UUID));
          socket = bluetoothDevice.createRfcommSocketToServiceRecord(UUID.fromString(BT_UUID));
          socket.connect(); //Block 12 sec here, then throw the exception.
          return true;
      } catch (IOException e) {
          try {
              socket.close();
          } catch (IOException closeException) { }
          Log.e("Bluetooth", "Cannot connect", e);
          return false;
      }
  }
  
  private void initUI(){
      LinearLayout linearLayout = new LinearLayout(this);
      Button finish = new Button(this);
      finish.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              if(socket!=null){
                  try {
                      socket.close();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
              BlueToothTestActivity.this.finish();
          }
      });
      finish.setText("Exit");
      linearLayout.addView(finish);
      setContentView(linearLayout);
  }
  }
  </code></pre>
  
  <p>The server is a simple <em>echo server</em> (based on Bluecove library, I took the code from here : <a href="http://www.miniware.net/mobile/articles/viewarticle.php?id=22" rel="nofollow noreferrer">http://www.miniware.net/mobile/articles/viewarticle.php?id=22</a>)</p>
  
  <p><strong>Server</strong></p>
  
  <pre><code>import java.io.*;
  import javax.bluetooth.*;
  import javax.microedition.io.*;
  
  // sample code from : http://www.miniware.net/mobile/articles/viewarticle.php?id=22   (Nikos Fotiou)
  public class EchoServer {
      public final UUID uuid = new UUID("0000110100001000800000805F9B34FB",false);
      public final String name = "EchoServer";                       //the name of the service
      public final String url  =  "btspp://localhost:" + uuid + ";name=" + name  + ";authenticate=false;encrypt=false;";
      LocalDevice local = null;
      StreamConnectionNotifier server = null;
      StreamConnection conn = null;
  
      public EchoServer() {
      try {
          System.out.println("Setting device to be discoverable...");
          local = LocalDevice.getLocalDevice();
          local.setDiscoverable(DiscoveryAgent.GIAC);
          System.out.println("Start service:"+url);
          server = (StreamConnectionNotifier)Connector.open(url);
          System.out.println("Waiting for incoming connection...");
          conn = server.acceptAndOpen();  // stop and wait here
          System.out.println("Client Connected..."); //never reach this line
          DataInputStream din   = new DataInputStream(conn.openInputStream());
          while(true){
              String cmd = "";
              char c;
              while (((c = din.readChar()) &gt; 0) &amp;&amp; (c!='\n') ){
                  cmd = cmd + c;
              }
              System.out.println("Received " + cmd);
          }
      } catch (Exception  e) {
          System.err.println("Exception Occured: " + e.toString());
          e.printStackTrace();
      }
  }
  
  public static void main (String args[]){
      EchoServer echoserver = new EchoServer();
  }
  
  }
  </code></pre>
  
  <p><strong>Server pom.xml</strong></p>
  
  <pre><code>&lt;dependencies&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;net.sf.bluecove&lt;/groupId&gt;
          &lt;artifactId&gt;bluecove&lt;/artifactId&gt;
          &lt;version&gt;2.1.1-SNAPSHOT&lt;/version&gt;
      &lt;/dependency&gt;
  &lt;/dependencies&gt;
  
  &lt;repositories&gt;
      &lt;repository&gt;
          &lt;id&gt;pyx4me-web-snapshot&lt;/id&gt;
          &lt;url&gt;http://www.pyx4me.com/maven2-snapshot&lt;/url&gt;
          &lt;snapshots&gt;
              &lt;enabled&gt;true&lt;/enabled&gt;
          &lt;/snapshots&gt;
          &lt;releases&gt;
              &lt;enabled&gt;false&lt;/enabled&gt;
          &lt;/releases&gt;
      &lt;/repository&gt;
  &lt;/repositories&gt;
  </code></pre>