Reputation: 935
I've this code to begin to scan BLE devices:
Log.i("timeChar", "Begin");
customBluetoothManager.scanLeDevice(true);
Then scanLeDevice() are invoked, that manages the Bluetooth Adapter for start the BLE scan:
public void scanLeDevice(final boolean enable) {
mHandler = new Handler();
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, SCAN_PERIOD);
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
And now, the callback for each device that is found through the scanning:
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
String name = device.getName();
if (name != null && name.compareTo(bluetoothDeviceName) == 0) {
Log.i("timeChar", "Device found");
}
}
};
Each time that I'm going to scan my BLE device (that has a Peripheral role), it takes around 11 seconds to detect it...
05-31 17:32:39.139 27545-9668/app I/timeChar: Begin
05-31 17:32:50.149 27545-27545/app I/timeChar: Device found
Is there any way to reduce this time?
Upvotes: 4
Views: 2907
Reputation: 321
In order to do so you should take into account:
Defined interval set in the BLE Beacon. In order to save battery you can define the time interval between each packet sent by the BLE Beacon (from 100 ms to some seconds). Therefore first check what is the time interval of your Beacons.
The time set in Android OS to indicate you that a new packet has been received (callback function). As indicated by Marcin you can do so as easy as:
scanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY ).build();
Upvotes: 1
Reputation: 916
The BLE scan and device advertisement is done at intervals. If the interval between adverts is long, let s say a second, then android might miss it. In order to fix this from the app side:
//global ScanSettings settings;
ScanSettings.Builder settingBuilder = new ScanSettings.Builder();
settingBuilder.setScanMode(SCAN_MODE_LOW_LATENCY);
settings = settingBuilder.build();
which you later pass to the scan method
mBluetoothAdapter.getBluetoothLeScanner().startScan(null, settings, mLeScanCallback);
Upvotes: 3