I am working on implementing an Android app that connects to BLE devices but the lack of proper documentation is killing me. Nothing seems to be working the same way twice if I run the app once it might work but the next time stops somewhere(no idea where) but I kinda came to a conclusion that I might have not been using disconnect()
and close()
in the right order.
After let's say an error I call disconnect() first:
public void disconnect() {
mScanning = true;
mConnected = false;
startedConnect = false;
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
scanLeDevice(true);
return;
}
mBluetoothGatt.disconnect();
scanLeDevice(true);
}
then I call close():
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
Is this the correct way of doing it or wrong? Please be aware that I am calling scanLeDevice(true);
right after disconnecting but then close()
is called which I think is just "finishing" everything and stops the scanning right?
When you create a BluetoothGatt
object by calling connectGatt
on a BluetoothDevice
, you claim one of the 32 (in current Android version) available slots in the Bluetooth stack.
On this object you can now call connect
and disconnect
to change the state of the "goal" if Android should try to keep a connection to the device or not. Until you call disconnect
, Android will (forever) try to connect to the device and automatically reconnect to the device if the connection drops for any reason. Calling connect
again after disconnect
will make it try to connect again.
Note: setting autoConnect
to false
in the initial connectGatt
call will set an initial timeout for the first implicit connect attempt (usually 30 seconds), and if the device connects and the connection later drops, it won't automatically try to reconnect.
So the BluetoothGatt
object can be in the "disconnected" state but still take up one of the 32 slots in the Bluetooth Stack. When you call close
, you release all the resources for the BluetoothGatt
object and return the slot to the Bluetooth stack. A close therefore implicitly also means disconnect. To potentially workaround some buggy Android devices, you could call disconnect
on the BluetoothGatt
object before close
. Note that once you have called close
, you can't call any other methods on that BluetoothGatt
object.
Note: turning off Bluetooth means destroying all BluetoothGatt
objects automatically.
Back to your question, I don't really understand what your BLE scanning has to do with
connect/disconnect/close. Scanning is totally separate from connections and BluetoothGatt
objects and there are no issues with being connected and performing a scan at the same time. To stop the scan, call stopScan
on the BluetoothLeScanner
.