Juan CA
Juan CA

Reputation: 176

Android BLE scan and show of result

I'm developing an android app that needs to connect to a Bluetooth-low-energy device. In order of achieving that goal, and following the Android Dev page, I have included the correct permissions in the manifest file. In the mainActivity I'm trying to scan for BLE devices and printing the result on the screen. The code looks like this:

     final BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
     bluetoothLeScanner.startScan(callback);
     // Before 5 seconds, stop the scan and show results.
     new Handler().postDelayed(new Runnable() {
         @Override
         public void run() {
             bluetoothLeScanner.stopScan(callback);
             callback.onBatchScanResults(results);
             callback.onScanFailed(2);
             callback.onScanResult(3,result);
             listOfResults.setText(results.toString());
         }
     },5000);

Upvotes: 1

Views: 2977

Answers (2)

Robby Lebotha
Robby Lebotha

Reputation: 1255

Have you added location permissions in manifest and also check if location permission is granted at runtime? If you havent done this, your results will always be null.

Upvotes: 0

andy
andy

Reputation: 26

The way I did it was to implement scanCallback() object and overriding the onScanResult() or onBatchScanResults() as needed.

    private ScanCallback callback= new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);

            // handles scan result
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);

            // handles batch scan results
            for (ScanResult result : results) {

                // you can iterate through each result like so
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            // handles error
        }
    };

You then pass callback inside of stopScan() and startScan()

bluetoothLeScanner.startScan(callback);
bluetoothLeScanner.stopScan(callback);

Also consider using result.getDevice() so you can retrieve the specific data of the device you need instead of a large chunk of information. For example, result.getDevice().getAddress() if you want the address only.

Upvotes: 1

Related Questions