Use named Runnable for scheduled BLE scans and cancel on pause

Replace anonymous lambdas in handler.postDelayed with a shared
scanRunnable so that handler.removeCallbacks(scanRunnable) in onPause
cancels any pending scan. Prevents duplicate or orphaned scan starts
during rapid activity transitions.

Reviewed in codereview.md (recommendation 2.2).
This commit is contained in:
eddy 2026-07-26 16:51:53 +02:00
commit ce0c119416

View file

@ -49,6 +49,7 @@ class MainActivity : AppCompatActivity() {
private var isScanning = false private var isScanning = false
private var scanTimedOut = false private var scanTimedOut = false
private val handler = Handler(Looper.getMainLooper()) private val handler = Handler(Looper.getMainLooper())
private val scanRunnable = Runnable { startScan() }
private var seq = 1 private var seq = 1
private var hmacKey: ByteArray? = null private var hmacKey: ByteArray? = null
@ -89,7 +90,7 @@ class MainActivity : AppCompatActivity() {
bluetoothGatt = null bluetoothGatt = null
relayCharacteristic = null relayCharacteristic = null
seq = 1 seq = 1
handler.postDelayed({ startScan() }, 2000) handler.postDelayed(scanRunnable, 2000)
} }
} }
@ -165,7 +166,7 @@ class MainActivity : AppCompatActivity() {
relayCharacteristic = null relayCharacteristic = null
seq = 1 seq = 1
loadHmacKey() loadHmacKey()
handler.postDelayed({ startScan() }, 500) handler.postDelayed(scanRunnable, 500)
} }
} }
@ -175,12 +176,13 @@ class MainActivity : AppCompatActivity() {
if (hmacKey == null) { if (hmacKey == null) {
statusText.text = "Geen HMAC sleutel - open Instellingen" statusText.text = "Geen HMAC sleutel - open Instellingen"
} else if (!isScanning && bluetoothGatt == null) { } else if (!isScanning && bluetoothGatt == null) {
handler.postDelayed({ startScan() }, 300) handler.postDelayed(scanRunnable, 300)
} }
} }
override fun onPause() { override fun onPause() {
super.onPause() super.onPause()
handler.removeCallbacks(scanRunnable)
stopScan() stopScan()
} }