Я создаю приложение для Android, которое может подключать два устройства BT и осуществлять связь через SPP. Чтобы создать такое приложение, я следую простой логике.
Я получил два MAC-адреса устройства BT, поэтому в цикле for я подключаю устройства BT, как показано ниже:
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);
}
}
Используя приведенный выше код, я могу подключить два устройства BT. Но проблема в том, что когда я закрываю активность, я отключаю их, но в это время отключается только одно устройство. Я вызываю отключение на «OnDestroy» фрагмента:
@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) {
}
}
Мне нужна помощь, чтобы выяснить, почему при отключении отключается только одно устройство? Нужно ли закрывать два сокета, потому что при подключении открыл 2 сокета на два устройства? Если да, то как я могу закрыть два сокета?
Заранее спасибо