I am connecting an Android device to iOS using BluetoothLeScanner on the Android side. All this works great for the first time.
The fact is that after connecting to one of the detected iOS devices, I stop scanning (stopScan (scanCallback)) to save energy.
If the previously connected device is disconnected for some reason, I start scanning again ... but it seems that after the “reboot” scan no longer works, it does not detect any devices ... not sure why, but I 'm force restart the application.
Any ideas how to fix this?
I also use ScanFilter to filter devices by UUID and use ScanSettings.SCAN_MODE_BALANCED for scan mode.
Here is the code:
private void startScanner() {
BluetoothManager bluetoothManager = (BluetoothManager) activity.getSystemService(activity.BLUETOOTH_SERVICE);
BluetoothAdapter adapter = bluetoothManager.getAdapter();
scanner = adapter.getBluetoothLeScanner();
ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build();
scanner.startScan(scanFilters(), settings, scanCallback);
System.out.println("Scanner started");
}
private List<ScanFilter> scanFilters() {
ScanFilter filter = new ScanFilter.Builder().setServiceUuid(THE_BT_UUID).build();
List<ScanFilter> list = new ArrayList<ScanFilter>(1);
list.add(filter);
return list;
}
private final ScanCallback scanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice device = result.getDevice();
if (device != null) {
callback.foundRemoteDevice(BluetoothCentral.this, device);
}
}
}
public void connectToDevice(BluetoothDevice device) {
if (gatt == null) {
gatt = device.connectGatt(activity, false, gattCallback);
scanner.stopScan(scanCallback);
}
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
System.out.println("onConnectionStateChange; status: " + status + ", state: " + newState);
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
System.out.println("STATE_CONNECTED");
if (!startedServiceDiscovery) {
gatt.discoverServices();
startedServiceDiscovery = true;
}
break;
case BluetoothProfile.STATE_DISCONNECTED:
callback.didDisconnectFromDevice(BluetoothCentral.this, gatt.getDevice());
gatt = null;
startScanner();
break;
default:
System.out.println("STATE_OTHER");
}
}
}
, connectGatt , BluetoothProfile.STATE_DISCONNECTED.