2

I pass HeadphoneConnectThread the bluetooth device i.e. SONY WH-1000XM3 that I get from: Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();.

The HeadphoneConnectThread class attempts to establish a connection with the Bluetooth headphones.

The connection part is working fine i.e. the paired headphones are connected and data can be streamed to it.

To disconnect, I call close() which updates the state of the BluetoothSocket (see below) however, headphones are not disconnected.

socket.isConnected()=false, headphone.getBondState()=12

Bond state 12:

https://developer.android.com/reference/android/bluetooth/BluetoothDevice#BOND_BONDED


public class HeadphoneConnectThread extends Thread {

public static final UUID uuid = UUID.fromString("96cc203e-5068-46ad-b32d-e316f5e069ba");

private final BluetoothDevice headphone;
private BluetoothSocket socket;

public HeadphoneConnectThread(BluetoothDevice headphone) {
    BluetoothSocket tmp = null;
    this.headphone = headphone;

    try {
        tmp = headphone.createRfcommSocketToServiceRecord(uuid);
    } catch (IOException e) {
        Log.e(TAG, "Socket's create() method failed", e);
    }
    socket = tmp;
}

public void run() {
    try {
        Log.d(TAG, "Connecting to " +  headphone.getName() + ", address=" + headphone.getAddress());
        if (!socket.isConnected()) {
            socket.connect();
            Log.d(TAG, "Connected");
        } else {
            Log.d(TAG, "Headphone already connected");
        }

        Thread.sleep(3000);

        if (socket.isConnected()) {
            disconnectHeadphone();
        }
    } catch (IOException e) {
        ...
    }
}


public void disconnectHeadphone() {
    try {
        Log.d(TAG,"Disconnecting " +  headphone.getName() + ", address=" + headphone.getAddress());
        socket.getOutputStream().close();
        socket.getInputStream().close();
        socket.close();
        Log.d(TAG, "Disconnected, socket.isConnected()=" + socket.isConnected() +
                ", headphone.getBondState()=" + headphone.getBondState());
        socket = null;
    } catch (IOException e) {
        Log.e(TAG, "Error occurred while disconnecting", e);
    }
}
aamir
  • 76
  • 1
  • 4

1 Answers1

1

From the docs you've linked:

Being bonded (paired) with a remote device does not necessarily mean the device is currently connected. It just means that the pending procedure was completed at some earlier time, and the link key is still stored locally, ready to use on the next connection.

So if your code outputs socket.isConnected = false and bondedState=12, it just means it's paired and disconnected.

There is no error in your code.

Fede
  • 321
  • 1
  • 9