11package it .iotinga .blelibrary ;
22
33import android .bluetooth .le .ScanCallback ;
4+ import android .bluetooth .le .ScanRecord ;
45import android .bluetooth .le .ScanResult ;
56import android .bluetooth .le .ScanSettings ;
7+ import android .os .ParcelUuid ;
68import android .util .Log ;
79
810import androidx .annotation .RequiresPermission ;
1214public class BleScanCallback extends ScanCallback {
1315 private static final String TAG = "BleScanCallback" ;
1416 private final EventEmitter eventEmitter ;
17+ private final List <ParcelUuid > filter ;
1518
16- BleScanCallback (EventEmitter eventEmitter ) {
19+ BleScanCallback (EventEmitter eventEmitter , List < ParcelUuid > filter ) {
1720 super ();
1821 this .eventEmitter = eventEmitter ;
22+ this .filter = filter ;
23+ }
24+
25+ private boolean resultPassesUuidFilter (ScanResult result ) {
26+ if (filter == null || filter .isEmpty ()) {
27+ return true ;
28+ }
29+
30+ ScanRecord record = result .getScanRecord ();
31+ if (record == null ) {
32+ return false ;
33+ }
34+
35+ for (ParcelUuid uuid : record .getServiceUuids ()) {
36+ for (ParcelUuid allowedUuid : filter ) {
37+ if (uuid .equals (allowedUuid )) {
38+ return true ;
39+ }
40+ }
41+ }
42+
43+ return false ;
1944 }
2045
2146 @ Override
2247 @ RequiresPermission (value = "android.permission.BLUETOOTH_CONNECT" )
2348 public void onScanResult (int callbackType , ScanResult result ) {
2449 Log .i (TAG , String .format ("got scan result: %s (callback type: %d)" , result , callbackType ));
2550
26- boolean available = callbackType == ScanSettings .CALLBACK_TYPE_FIRST_MATCH
27- || callbackType == ScanSettings .CALLBACK_TYPE_ALL_MATCHES ;
51+ if (resultPassesUuidFilter (result )) {
52+ boolean available = callbackType == ScanSettings .CALLBACK_TYPE_FIRST_MATCH
53+ || callbackType == ScanSettings .CALLBACK_TYPE_ALL_MATCHES ;
2854
29- RNEventScanResult event = new RNEventScanResult ();
30- event .add (result , available );
55+ RNEventScanResult event = new RNEventScanResult ();
56+ event .add (result , available );
3157
32- eventEmitter .emit (event );
58+ eventEmitter .emit (event );
59+ }
3360 }
3461
3562 @ Override
@@ -46,7 +73,9 @@ public void onBatchScanResults(List<ScanResult> results) {
4673
4774 RNEventScanResult event = new RNEventScanResult ();
4875 for (ScanResult result : results ) {
49- event .add (result , true );
76+ if (resultPassesUuidFilter (result )) {
77+ event .add (result , true );
78+ }
5079 }
5180
5281 eventEmitter .emit (event );
0 commit comments