I am creating an Android APP which could connect the two BT device and do the communication over SPP. To create such application I am following the simple logic.
I got the two mac addressed of the BT Device, so in a for loop I am connecting the BT Devices as below:
private void connect() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
String[] strDevice = deviceAddress.split(",");
BluetoothDevice device = null;
String currentConnection;
String deviceName = "";
try {
disconnect();
Thread.sleep(500);
for (String item: strDevice) {
Log.d(TAG,"item is: " + item + " size is: " + strDevice.length);
currentConnection = item;
device = bluetoothAdapter.getRemoteDevice(item);
deviceName = device.getName() != null ? device.getName() : device.getAddress();
status("connecting..." + item);
connected = Connected.Pending;
socket = new SerialSocket();
service.connect(this, "Connected to " + deviceName);
socket.connect(getContext(), service, device);
Thread.sleep(500);
}
} catch (Exception e) {
onSerialConnectError(e);
}
}
Using above code, I am able to connect the two BT devices. But the problem is when I close the activity I disconnect them but at that time only one device disconnects. I am calling the disconnect on "OnDestroy" of the fragment:
@Override
public void onDestroy() {
if (connected != Connected.False) {
disconnect();
}
getActivity().stopService(new Intent(getActivity(), SerialService.class));
super.onDestroy();
}
void disconnect() {
listener = null; // ignore remaining data and errors
connected = false; // run loop will reset connected
if(socket != null) {
try {
socket.close();
} catch (Exception ignored) {
}
socket = null;
}
try {
context.unregisterReceiver(disconnectBroadcastReceiver);
} catch (Exception ignored) {
}
}
I need a help to find out why on disconnect, only one device is disconnecting? Do I need to close two sockets because during connection it opened 2 sockets for two devices? If yes, how can I close two sockets?
Thanks in Advance
Here's the solution:
The issue was described above that on socket disconnect only one of the BT device was disconnecting. To resolve the situation, what I did is, I saved the socket in a concurrent list whenever it's created and connected.
So when the disconnect happens, I disconnected all the sockets from the list which are connected. This way it disconnects all the BT device.
Thanks.