Fix MainActivity: receiver flag, handler cleanup, onPause, boolean state

This commit is contained in:
eddy 2026-07-26 12:53:18 +02:00
commit 4954c91d77

View file

@ -44,11 +44,13 @@ class MainActivity : AppCompatActivity() {
private const val HMAC_PKT_SIZE = 37
private const val HMAC_LEN = 32
private const val REQUEST_SETTINGS = 1
private const val SCAN_TIMEOUT_MS = 10000L
}
private var bluetoothGatt: BluetoothGatt? = null
private var relayCharacteristic: BluetoothGattCharacteristic? = null
private var isScanning = false
private var scanTimedOut = false
private val handler = Handler(Looper.getMainLooper())
private var seq = 1
@ -168,7 +170,7 @@ class MainActivity : AppCompatActivity() {
}
setupRelayButton()
registerReceiver(bondReceiver, IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED))
registerReceiver(bondReceiver, IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED), Context.RECEIVER_NOT_EXPORTED)
}
@Deprecated("Deprecated in Java")
@ -189,6 +191,11 @@ class MainActivity : AppCompatActivity() {
}
}
override fun onPause() {
super.onPause()
stopScan()
}
private fun loadHmacKey() {
val prefs = getSharedPreferences(SettingsActivity.PREFS_NAME, Context.MODE_PRIVATE)
val hexKey = prefs.getString(SettingsActivity.PREF_KEY, null)
@ -267,14 +274,18 @@ class MainActivity : AppCompatActivity() {
}
isScanning = true
scanTimedOut = false
statusText.text = "Scanning..."
Log.d(TAG, "Starting BLE scan for $DEVICE_NAME")
adapter.bluetoothLeScanner.startScan(scanCallback)
handler.postDelayed({
if (isScanning) stopScan()
}, 10000)
if (isScanning) {
scanTimedOut = true
stopScan()
}
}, SCAN_TIMEOUT_MS)
}
@SuppressLint("MissingPermission")
@ -283,7 +294,7 @@ class MainActivity : AppCompatActivity() {
isScanning = false
val adapter = BluetoothAdapter.getDefaultAdapter()
adapter?.bluetoothLeScanner?.stopScan(scanCallback)
if (statusText.text == "Scanning...") {
if (scanTimedOut) {
statusText.text = "Device not found"
}
}
@ -332,11 +343,11 @@ class MainActivity : AppCompatActivity() {
ActivityCompat.requestPermissions(this, getRequiredPermissions(), 1)
}
@SuppressLint("UnspecifiedRegisterReceiverFlag")
override fun onDestroy() {
super.onDestroy()
handler.removeCallbacksAndMessages(null)
stopScan()
bluetoothGatt?.close()
unregisterReceiver(bondReceiver)
try { unregisterReceiver(bondReceiver) } catch (e: Exception) {}
}
}