I am now using the new BLE api in android developing.
Basic idea is using bluetooth scanning result to inflate the recyclerview(list);
I followed the BLE guide on google developer
Now I have two problem:
1. onBatchScanResults
listener is never triggered, butonScanResult
works well, is that because the scanner only sense 1 sensor nearby?
The following is the two core functions' code snippet.
private void scanBLE(boolean enable) {
final BluetoothLeScanner mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
if (enable) {
mScanning = true;
mBluetoothLeScanner.startScan(mScanCallback);
} else {
if (mScanning) {
mScanning = false;
mBluetoothLeScanner.stopScan(mScanCallback);
}
}
Log.i(TAG, "now the scanning state is" + mScanning);
}
// Device scan callback.
private ScanCallback mScanCallback =
new ScanCallback() {
public void onScanResult(int callbackType, android.bluetooth.le.ScanResult result) {
addBeaconTolist(result, beaconsList);
mAdapter.notifyDataSetChanged();
};
public void onScanFailed(int errorCode) {
Log.i(TAG, "error code is:" + errorCode);
};
public void onBatchScanResults(java.util.List<android.bluetooth.le.ScanResult> results) {
Log.i(TAG, "event linstener is called!!!!");
Log.i(TAG, "batch result are:" + results);
beaconsList.clear();
for (int i = 0; i < results.size(); i++) {
ScanResult result = results.get(i);
addBeaconTolist(result, beaconsList);
}
mAdapter.notifyDataSetChanged();
};
};
in MainFragment is like following:
beaconsList = new ArrayList<BeaconsInfo>();
mAdapter = new BeaconsAdapter(beaconsList);
mRecyclerView.setAdapter(mAdapter);
scannBLE(true);
Whether or not you get batch results or individual results depends on your scan settings.
In order to get batch results, you need to adjust the ScanSettings
. Check out the documentation for the ScanSettings.Builder
, and try using SCAN_MODE_LOW_POWER
, which batches up results. You can also try adjusting the batch interval with setReportDelay(long reportDelayMillis)
; You can see a blog post I wrote about the power benefits of these settings here.
It's not totally clear what you mean by "my BLE scanner is much slower compared with other applications", but it may be that the app's UI lags because you are not updating it on the UI thread. Try wrapping your calls to notifyDatasetChanged like this:
runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With