Connect to Bluetooth device

suggest change

After you have a BluetoothDevice, talk to it through the socket input and output streams.

1) Create the socket. createRfcommSocketToServiceRecord takes a service UUID, not a device id. The listening device must advertise the same UUID. 00001101-0000-1000-8000-00805F9B34FB is the Serial Port Profile UUID.

private BluetoothSocket _socket;
private final UUID serviceUuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

public void initializeSocket(BluetoothDevice device) {
   try {
       _socket = device.createRfcommSocketToServiceRecord(serviceUuid);
   } catch (IOException e) {
       // Error
   }
}

2) Connect the socket:

try {
    _socket.connect();
} catch (IOException connEx) {
    try {
        _socket.close();
    } catch (IOException closeException) {
        //Error
    }
}

if (_socket != null && _socket.isConnected()) {
    //Socket is connected, now we can obtain our IO streams
}

3) Obtain the socket input and output streams

private InputStream _inStream;
private OutputStream _outStream;
//....
try {
    _inStream = _socket.getInputStream();
    _outStream =  _socket.getOutputStream();
} catch (IOException e) {
   //Error
}

Input stream - Used as incoming data channel (receive data from connected device)

Output stream - Used as outgoing data channel (send data to connected device)

After finishing 3rd step, we can receive and send data between both devices using previously initialized streams:

4) Receive data by reading the input stream. read returns -1 at the end of the stream. Run this loop on a background thread.

byte[] buffer = new byte[1024];
int bytesCount;

while (true) {
    try {
        bytesCount = _inStream.read(buffer);
        if (bytesCount < 0) {
            break;
        }
        if (bytesCount > 0) {
            // Parse the first bytesCount bytes. The rest of the buffer is stale.
        }
    } catch (IOException e) {
        break;
    }
}

5) Send data by writing to the output stream:

public void write(byte[] bytes) {
    try {
        _outStream.write(bytes);
    } catch (IOException e) {
        //Error
    }
}

Connect, read, and write on a dedicated thread. connect() and read() block. Close the socket and both streams when communication finishes. Closing the socket also closes the streams.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents