How to replace Handler() based code with lifecycle based code


I have been searching how to replace the Handler() based code I got from <https://developer.android.com/develop/connectivity/bluetooth/ble/find-ble-devices#kotlin> with a lifecycle based version, but all of the code I have found is all about views, there is not "view" here -- this is a "background" thing. I just want to start the BLE scan and then stop it after about 10 seconds if a device is not found. I am not sure how to do that,

The code fragment is this:

    private val handler = Handler()

    // ...

        try {
            if (!scanning) { // Stops scanning after a pre-defined scan period.
                handler.postDelayed({
                                    scanning = false
                                    bluetoothLeScanner.stopScan(leScanCallback)
                                }, SCAN_PERIOD)
                    scanning = true
                    bluetoothLeScanner.startScan(listOf(ScanFilter.Builder()
                                                        .setServiceData(ParcelUuid(ServiceUUID), 
                                                                        null, 
                                                                        null).build()),
                                                        ScanSettings.Builder()
                                                        .setNumOfMatches(ScanSettings.
                                                                         MATCH_NUM_ONE_ADVERTISEMENT)
                                                        .build(),
                                                        leScanCallback)
                } else {
                    scanning = false
                    bluetoothLeScanner.stopScan(leScanCallback)
                }
            }
            catch (e: SecurityException) {
                println(&quot;scanLeDevice: SecurityException caught: $e&quot;)
            }

All the handler is doing is waiting for the timeout period and then calling the stopScan() function to halt the scan if it is still running. The scan will stop on its own if a device is detected before the timeout. I am not sure how to do this with lifecycle. The documentation is not clear on how to do this sort of thing. It is full of blather and examples for doing clever things with the UI, which is not what I am doing here. All I really want to do is deal with the pesky warning about Handler() being depreciated by replacing it with code using more modern functions.+

0
Jul 26 at 12:15 PM
User AvatarRobert Heller
#android#kotlin#timeout#android-lifecycle

No answer found for this question yet.