I have an app complete and ready to ship that connects to a custom bluetooth peripheral we have had made. However I have just found an issue with the app that I can't pin down.
I am running all my Bluetooth operations in a Service
and sometimes when I want the bluetooth operations to end, I end up with 1 peripheral still connected but i've lost all pointers to it. And every now and then the whole bluetooth stack seems to lock up and requires the phone to be rebooted.
I think the issues are arising when trying to clean out any connected devices after I stop scanning. I have this cleanup method
private void clearAllDevices() {
Log.e(TAG, "Clear all devices");
for (int i = 0; i < _connectedPeripherals.size(); i++) {
Log.e(TAG, "int i:" + i + " _connectedPeripherals size:" + _connectedPeripherals.size());
BluetoothGatt gatt = (BluetoothGatt) _connectedPeripherals.get(i);
gatt.disconnect();
}
}
However I think sometimes a peripheral is half way through connecting at the same time as disconnecting from everything that has a connection.
Is there a better way to clean out all connected devices or devices that are in the process of being connected?
Caution: BLE scanning typically needs location permissions as BLE scanning identifies objects that could be used for geolocation. Turning off location services will turn off Bluetooth scanning. From Android 12, apps that declare neverForLocation can gain Bluetooth scanning results even when location services are off.
Because BLE is designed to save power, the device is typically dormant until action is required.
What is Bluetooth Low Energy? Bluetooth Low Energy is a wireless, low-power personal area network that operates in the 2.4 GHz ISM band. Its goal is to connect devices over a relatively short range. BLE was created with IoT applications in mind, which has particular implications for its design.
bluetoothGatt.disconnect()
is not enough alone. You should also call bluetoothGatt.close()
.
Once your app has finished using a BLE device, it should call
close()
so the system can release resources appropriately.
See: API Guides > Bluetooth Low Energy
You may check the result of bluetoothGatt.disconnect()
via BluetoothGattCallback.onConnectionStateChange
callback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With