Part 1: https://bit.ly/androidbluetoothtutorial
The Advertising part was covered in part 1, in this, Scanning is handled. As stated, there are two modes Bluetooth Connected mode(bilateral communication) and connectionless(unilateral communication). This article focuses on connectionless mode.
Basics
The same permissions apply — Bluetooth and location permissions have to be granted. To scan continuously, use a Foreground service alternatively to scan periodically use a Worker. Using a worker you can set the time intervals to carry out the scans.
Scanning
First, create a class that will handle the scanning of BLE devices. Then get the BluetoothAdapter and BluetoothLeScanner.
public void setBluetoothAdapter(BluetoothAdapter btAdapter) {
this.mBluetoothAdapter = btAdapter;
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
Build Scan Settings
Configure the scan settings to use
private ScanSettings buildScanSettings() {
ScanSettings.Builder builder = new ScanSettings.Builder();
builder.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER);// Low_Power mode conserves battery power.Change to SCAN_MODE_LOW_LATENCY for more aggressive scanning
return builder.build();
}
Build the Scan Filters
You can configure the scanner to only find devices advertising with a specific UUID to differentiate them from the others.
private List<ScanFilter> buildScanFilters() {
List<ScanFilter> scanFilters = new ArrayList<>();
ScanFilter.Builder builder = new ScanFilter.Builder();
/* Comment out the below line to see all BLE devices around you
the Service_UUID is the UUID in the advertisement packet*/
builder.setServiceUuid(Constants.Service_UUID);
scanFilters.add(builder.build());
return scanFilters;
}
Build the Callback
This will handle various events:
Success or failure of scanning
Will return the device or multiple devices found
private class SampleScanCallback extends ScanCallback {
@Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
//Handle when multiple devices are found
}
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
// Handle when a single device is found
}
@Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.d(TAG, "onScanFailed: " + errorCode);
//Handle when scan failed
}
}
Start Scanning
Now everything is set, you can start scanning for BLE devices near you.
public void startScanning() {
if (mScanCallback == null) {
Log.d(TAG, "Starting Scan");
// Start a new scan.
mScanCallback = new SampleScanCallback();
mBluetoothLeScanner.startScan(
buildScanFilters(),
buildScanSettings(),
mScanCallback
);
}
}