5

my application scans BLE devices in background. I don't understand what determines the choice between these two methods: advantage / disadvantage. (I tested both and it works)

public int startScan (List<ScanFilter> filters, 
            ScanSettings settings, 
            PendingIntent callbackIntent)

public void startScan (List<ScanFilter> filters, 
                ScanSettings settings, 
                ScanCallback callback)`

thank you for help

Sebastien
  • 133
  • 1
  • 8

1 Answers1

5

Android 8+ allows you to deliver Bluetooth scan results with two different messaging transports: Callback and Intent.

Callback

This makes a call to a method you define with the scan results.

Pros:

  • Simpler setup in code
  • Lighter weight (less CPU usage) due to no need to serialize scan result data structures. This is especially important if you expect a heavy volume of detections.
  • Works on older Android versions, not just 8+

Cons:

  • Background scans are generally limited to 10 minutes at a time unless you start a Foreground Service to keep your app running in the background.
  • Cannot re-launch your app in the background on detection

Intent

This delivers the scan results to a BroadcastReceiver using Android’s Intent messaging structure

Pros:

  • Delivers results in the background indefinitely without a Foreground Service
  • Can re-launch your app on detection

Cons:

  • Higher power usage, especially with heavy scan results
  • More complex code setup
  • Does not work before Android 8
  • Scans to detect pattern match loss will be missed if Android Doze mode has kicked in
  • Processing scan results at regular intervals (if needed) still requires timers and perhaps a Foreground Service, negating many of the Pros
davidgyoung
  • 63,876
  • 14
  • 121
  • 204
  • Thank you for your answer. Could you please clarify one thing: when scanning using PendingIntent, should we stop scanning by calling stopScan(sameIntent) when the device of interest is found? – Waldmann Nov 22 '21 at 18:49
  • Yes, if you do not need more results you should stop scanning to save battery. – davidgyoung Nov 22 '21 at 21:00