Reputation: 176
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);
bluetoothApater
is the BlueoothAdapter needed to perform the operation as it's told in the android page, bluetoothLeScanner
is the object needed to perform LE scan operations, callback
is a Scan call back object, results
is a List < ScanResult > result
is a ScanResult,listOfResults
is text view.Upvotes: 1
Views: 2977
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
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