Search code examples
javabluetoothbluecove

How Can I disconnect a BT device in Java using bluecove?


I'm new to bluetooth communication using Java. Looking at the bluecove documentation I did the following to be able to communicate with a bluetooth device:

  1. Discover It
  2. Get the StreamConnection via Connector.open`
  3. Use the InputStream and the OutputStream to communicate

The only thing that i didn't find in the documentation is how to close the communication.

The code I implemented, guessing the disconnection strategy, is the following:

    public void Connect() throws IOException
    {
        final int service = 5;        
        String conString = "btspp://"+Dev.getBluetoothAddress()+":"+service;

        Connection = (StreamConnection) Connector.open(conString);        
        inStream = Connection.openInputStream();
        outStream = Connection.openOutputStream();
    }

    public void Disconnect() throws IOException
    {        
        Connection.close();
    }

Dev is the RemoteDevice I got from Discovery.

When the call to the Connect function comes after the Disconnect I always get the following exception:

javax.bluetooth.BluetoothConnectionException: Failed to connect; [10048] Only one usage of each socket address (protocol/network address/port) is normally permitted.

Can someone tell me how to close the connection?


Solution

  • I found the solution. The call to Connection.close() have to be done after the close of the streams obtained from the call to the function Connection.openInputStream() and Connection.openOutputStream()

    The disconnect function now is the following:

        public void Disconnect() throws IOException
        {        
            inStream.close();
            outStream.close();
            Connection.close();
            inStream = null;
            outStream = null;
            Connection = null;
        }