I tried to connect using BluetoothSocket but get error read failed , socket might closed or timeout, read ret -1, am i missing something?
below is the code i use to test it in native module:
@ReactMethod
public void connectToDevice(String address, Callback callback) {
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
if (device == null) {
callback.invoke("Device not found");
return;
}
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
try {
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
socket.connect();
callback.invoke(null, "Connected");
} catch (IOException e) {
callback.invoke(e.getMessage());
}
}
in the react native:
const renderDevice = ({ item }: { item: Device }) => (
<TouchableOpacity onPress={() => {
BluetoothScannerModule.connectToDevice(item.address, (error: string | null, message: string) => {
if (error) {
console.log(error);
} else {
console.log(message);
}
});
}}>
<Text>{item.name ?? 'Unnamed device'}</Text>
<Text>{item.address}</Text>
<Text>Bond state: {item.bondState}</Text>
</TouchableOpacity>
);
<Modal visible={isModalVisible} transparent={true} onRequestClose={() => setIsModalVisible(false)}>
<View style={styles.modal}>
<FlatList data={devices} renderItem={renderDevice} />
<Button title='Close' onPress={() => setIsModalVisible(false)}/>
</View>
</Modal>
and I'm new to this, so is it possible without doing any pairing before using BluetoothSocket?