Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Bluetooth Low Energy sometimes locking up

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?

like image 343
Darren Avatar asked Oct 16 '14 11:10

Darren


People also ask

Why does Bluetooth low energy requires location?

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.

Is BLE always on?

Because BLE is designed to save power, the device is typically dormant until action is required.

What is Bluetooth low energy connection?

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.


1 Answers

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.

like image 155
Gyebro Avatar answered Oct 12 '22 23:10

Gyebro