Grace Jin
Grace Jin

Reputation: 11

Bluetooth LE scan can't find my device after first disconnection

I'm currently working on an android project. I have two activities working in series. They do roughly the same thing - scan for a device, connect, do some operations and disconnect. The first activity would do this process first, and after it disconnect, the second activity would perform the same process to the same device.

However, after successfully connecting and disconnecting the device in the first activity, the second activity's scan fails to find the previously connected device. It doesn't show up in the scanned results anymore. I verified that the device was successfully disconnected and was still broadcasting when the second device was scanning. I'm very confused what have caused this issue. Any help is greatly appreciated!

Here's the skeleton code of my first activity:

public class BluetoothActivity {

    private static final String SERVICE_UUID_STRING = "12340000-58fa-4b77-8f3b-72fd2cbaa335";
    private static final String CALIBRATE_CHAR_UUID_STRING = "1234efab-58fa-4b77-8f3b-72fd2cbaa335";
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeScanner mBluetoothLeScanner;
    private BluetoothGatt mBluetoothGatt;
    private boolean tag10connected = false;
    private Handler scanTimeoutHandler = new Handler();
    
    private Runnable scanTimeoutRunnable = new Runnable() {
        @SuppressLint("MissingPermission")
        @Override
        public void run() {
            stopScanning();
            toastMessage("Scan timed out without finding target device!");
            if (mBluetoothGatt != null) {
                mBluetoothGatt.disconnect();
                mBluetoothGatt.close();
                mBluetoothGatt = null;
            }
        }
    };

    @SuppressLint("MissingPermission")
    public void startScanning() {
        Log.e("BLE", "startScanning: mBluetoothAdapter.isEnabled() = " + mBluetoothAdapter.isEnabled());
        mBluetoothLeScanner.startScan(mScanCallback);
    }

    @SuppressLint("MissingPermission")
    private void stopScanning() {
        Log.e("BLE", "stopScanning: mBluetoothLeScanner = " + mBluetoothLeScanner);
        toastMessage("Scanning finished!");
        mBluetoothLeScanner.stopScan(mScanCallback);
        scanTimeoutHandler.removeCallbacks(scanTimeoutRunnable);
    }

    @SuppressLint("MissingPermission")
    private void connectToDevice(BluetoothDevice device) {
        mBluetoothGatt = device.connectGatt(this, false, mGattCallback, BluetoothDevice.TRANSPORT_LE);
    }

    @SuppressLint("MissingPermission")
    private void disconnectDevice() {
        if (mBluetoothGatt != null) {
            BluetoothDevice device = mBluetoothGatt.getDevice();
            Log.e("BLE", "Trying to disconnect: " + device.getName());
            mBluetoothGatt.disconnect();
            mBluetoothGatt.close();
            mBluetoothGatt = null;
        }
    }

    private ScanCallback mScanCallback = new ScanCallback() {
        @SuppressLint("MissingPermission")
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            BluetoothDevice device = result.getDevice();
            if (device.getName() != null && device.getName().equals("TOILET")) {
                tag10connected = true;
                stopScanning();
                connectToDevice(device);
            }
        }
    };

    private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @SuppressLint("MissingPermission")
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, final int newState) {
            if (newState == BluetoothGatt.STATE_CONNECTED) {
                Log.e("BLEConnection", "Connection Built!");
                toastMessage("Connected!");
                disconnectDevice();
            } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                Log.e("BLEConnection", "Disconnected!");
                toastMessage("Disconnected!");
            }
        }

        @SuppressLint("MissingPermission")
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Log.e("BLE", "onServicesDiscovered called with status: " + status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                BluetoothGattCharacteristic characteristic = gatt.getService(UUID.fromString(SERVICE_UUID_STRING))
                        .getCharacteristic(UUID.fromString(CALIBRATE_CHAR_UUID_STRING));
                characteristic.setValue(String.valueOf(0));
                gatt.writeCharacteristic(characteristic);
            }
        }

        @SuppressLint("MissingPermission")
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                disconnectDevice();
            }
        }
    };

    public void toastMessage(String data) {
        Toast.makeText(this, data, Toast.LENGTH_LONG).show();
    }
}

And here's the skeleton code for my second activity:

public class IMUCalibrationActivity {

    private static final String SERVICE_UUID_STRING = "45670000-58fa-4b77-8f3b-72fd2cbaa335";
    private static final String CALIBRATE_CHAR_UUID_STRING = "45671111-58fa-4b77-8f3b-72fd2cbaa335";
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeScanner mBluetoothLeScanner;
    private BluetoothGatt mBluetoothGatt;
    private Handler scanTimeoutHandler = new Handler();
    
    private Runnable scanTimeoutRunnable = new Runnable() {
        @SuppressLint("MissingPermission")
        @Override
        public void run() {
            stopScanning();
            toastMessage("Scan timed out without finding target device!");
            if (mBluetoothGatt != null) {
                mBluetoothGatt.disconnect();
                mBluetoothGatt.close();
                mBluetoothGatt = null;
            }
        }
    };

    @SuppressLint("MissingPermission")
    public void startScanning() {
        Log.e("BLE", "startScanning: mBluetoothAdapter.isEnabled() = " + mBluetoothAdapter.isEnabled());
        toastMessage("Scanning...");
        mBluetoothLeScanner.startScan(mScanCallback);
        scanTimeoutHandler.postDelayed(scanTimeoutRunnable, 10000); // 10 seconds timeout
    }

    @SuppressLint("MissingPermission")
    private void stopScanning() {
        Log.e("BLE", "stopScanning: mBluetoothLeScanner = " + mBluetoothLeScanner);
        toastMessage("Scanning finished!");
        mBluetoothLeScanner.stopScan(mScanCallback);
        scanTimeoutHandler.removeCallbacks(scanTimeoutRunnable);
    }

    @SuppressLint("MissingPermission")
    private void connectToDevice(BluetoothDevice device) {
        mBluetoothGatt = device.connectGatt(this, false, mGattCallback, BluetoothDevice.TRANSPORT_LE);
    }

    @SuppressLint("MissingPermission")
    private void disconnectDevice() {
        if (mBluetoothGatt != null) {
            mBluetoothGatt.disconnect();
            mBluetoothGatt.close();
            mBluetoothGatt = null;
            Intent nextStep = new Intent(IMUCalibrationActivity.this, TimeSyncActivity.class);
            startActivity(nextStep);
            finish();
        }
    }

    private ScanCallback mScanCallback = new ScanCallback() {
        @SuppressLint("MissingPermission")
        public void onScanResult(int callbackType, ScanResult result) {
            BluetoothDevice device = result.getDevice();
            if (device.getName() != null && device.getName().equals("TOILET")) {
                stopScanning();
                connectToDevice(device);
            }
        }
    };

    private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @SuppressLint("MissingPermission")
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, final int newState) {
            runOnUiThread(() -> {
                if (newState == BluetoothGatt.STATE_CONNECTED) {
                    Log.e("BLEConnection", "Connection Built!");
                    toastMessage("Connected!");
                    mBluetoothGatt.discoverServices();
                } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                    Log.e("BLEConnection", "Disconnected!");
                    toastMessage("Disconnected!");
                }
            });
        }

        @SuppressLint("MissingPermission")
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Log.e("BLE", "onServicesDiscovered called with status: " + status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                BluetoothGattCharacteristic characteristic = gatt.getService(UUID.fromString(SERVICE_UUID_STRING))
                        .getCharacteristic(UUID.fromString(CALIBRATE_CHAR_UUID_STRING));
                characteristic.setValue(timestampGenerator());
                gatt.writeCharacteristic(characteristic);
                Log.e("TimeWorker", "Writing to characteristic: " + gatt.writeCharacteristic(characteristic));
            }
        }

        @SuppressLint("MissingPermission")
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                BluetoothGattCharacteristic calibrationCharacteristic = gatt.getService(UUID.fromString(SERVICE_UUID_STRING))
                        .getCharacteristic(UUID.fromString(CALIBRATE_CHAR_UUID_STRING));
                gatt.readCharacteristic(calibrationCharacteristic);
            }
        }

        @SuppressLint("MissingPermission")
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            Log.e("BLE", "characteristic read: " + characteristic.toString());
            if (status == BluetoothGatt.GATT_SUCCESS) {
                final byte[] data = characteristic.getValue();
                float value = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).getFloat();
                Log.e("Got value after calibration", String.valueOf(value));
                disconnectDevice();
            }
        }
    };
}

Initially, I thought the device might be bonded and that's why it doesn't show up in the scanned device anymore. So I printed the bonded device from BluetoothAdapter.getBondedDevices(), but there's no bonded device stored at all.

I also tried to flushPendingScanResults before starting scanning in the second activity. But it doesn't work either. The device still doesn't show up.

I checked if other applications are able to scan for this device. So I switched to nRFConnect to scan for this device, and the device showed up. Interestingly, when I switched back to this app after scanning using nRFConnect, the device was able to show up in the scan. I'm really confused about what is going, and what I should do to fix this issue. If you have any suggestions, please let me know! Thank you very much!

Upvotes: 1

Views: 105

Answers (0)

Related Questions