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:
parent
5861b1055c
commit
ce0c119416
1 changed files with 5 additions and 3 deletions
|
|
@ -49,6 +49,7 @@ class MainActivity : AppCompatActivity() {
|
|||
private var isScanning = false
|
||||
private var scanTimedOut = false
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val scanRunnable = Runnable { startScan() }
|
||||
|
||||
private var seq = 1
|
||||
private var hmacKey: ByteArray? = null
|
||||
|
|
@ -89,7 +90,7 @@ class MainActivity : AppCompatActivity() {
|
|||
bluetoothGatt = null
|
||||
relayCharacteristic = null
|
||||
seq = 1
|
||||
handler.postDelayed({ startScan() }, 2000)
|
||||
handler.postDelayed(scanRunnable, 2000)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -165,7 +166,7 @@ class MainActivity : AppCompatActivity() {
|
|||
relayCharacteristic = null
|
||||
seq = 1
|
||||
loadHmacKey()
|
||||
handler.postDelayed({ startScan() }, 500)
|
||||
handler.postDelayed(scanRunnable, 500)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -175,12 +176,13 @@ class MainActivity : AppCompatActivity() {
|
|||
if (hmacKey == null) {
|
||||
statusText.text = "Geen HMAC sleutel - open Instellingen"
|
||||
} else if (!isScanning && bluetoothGatt == null) {
|
||||
handler.postDelayed({ startScan() }, 300)
|
||||
handler.postDelayed(scanRunnable, 300)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
handler.removeCallbacks(scanRunnable)
|
||||
stopScan()
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue