Reputation: 1976
i have tested in android 5 & android 6. in HTC One A9, Moto x play, Moto G4
In this full process in background device scanning is going on.
Upvotes: 4
Views: 9428
Reputation: 680
You need to ensure that you connect to your device no more than once. I found that without adding your own protection, you can inadvertently have multiple connections with one device (that is multiple BluetoothGatt objects in existence) simultaneously. You can communicate with the device via any of these BluetoothGatt objects, so you don't notice the problem at that point. But when you try to disconnect you (erroneously) leave connections open.
To remove this risk you need code roughly like this:
BluetoothGatt mBluetoothGatt;
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
if (device != null) {
Log.d(TAG, "LeScanCallback!!!! device " + device.getAddress());
boolean foundDevice = false;
if (device.getName() != null) {
Log.d(TAG, "LeScanCallback!!!! " + device.getName());
// Put your logic here!
if (device.getName().compareTo("YOUR_DEVICE") == 0) {
Log.d(TAG, "Found device by name");
foundDevice = true;
}
else {
Log.d(TAG,"Found " + device.getName());
}
}
if(mBluetoothGatt == null && foundDevice) {
mBluetoothGatt = device.connectGatt(getApplicationContext(), false, mGattCallback);
// Make sure to handle failure cases in your callback!
Log.d(TAG, "Stopping scan."); //Appropriate only if you want to find and connect just one device.
mBluetoothAdapter.stopLeScan(this);
}
}
}
};
Upvotes: 4
Reputation: 211
this problem can be connected with not calling stopScan() method. see comment from SoroushA Totally Disconnect a Bluetooth Low Energy Device
Upvotes: 3