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!

New contributor

Grace Jin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật