Android-Scanner-Compat-Library icon indicating copy to clipboard operation
Android-Scanner-Compat-Library copied to clipboard

Leaked scan callback when app be killed by task manager

Open doanpt opened this issue 2 years ago • 0 comments

Hi, I'm using your lib to build an android app, In my app, I start scanScan when application lifecycle is onStart and stopScan when application lifecycle is onStop as below.

override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) =
    when (event) {
        Lifecycle.Event.ON_START -> {
            Timber.d("onStateChanged onStart")
            dependencies.bleLockModule.onStart()
        }
        Lifecycle.Event.ON_STOP -> {
            Timber.d("onStateChanged onStop")
            dependencies.bleLockModule.onStop()
        }
        else -> {
            Timber.d("onStateChanged $event")
        }
    }
override fun startScan(scanAggressively: Boolean) {
    if (scanCallback == null) {
        val callback = BleScanCallBack(scope, _resultsFlow)
        scanCallback = callback
        runCatching {
            scanner.startScan(emptyList(), buildScanSettings(scanAggressively), callback)
            restartScanning()
            Timber.d("BLE scan started")
        }.onFailure {
            Timber.e("Start scan failed: $it")
            callback.onScanFailed(BleError.ScanErrorCode.Unknown.value)
        }
    }
}

override fun stopScan() {
    scanCallback?.let {
        scanner.stopScan(it)
        Timber.d("BLE scan stop scanning")
        scanCallback = null
    } ?: Timber.d("Ignore stop scan due to callback null")
}

I found it working fine, but when app killed by task manager(recents tab), I see that I leaked the scan callback due to onStop not being called. after I tried to close/-reopen my app more that 32 times, android os throw error: "Unable to register GATT client, MAX client reached: 32" so cloud you please share me the best practice to call stopScan when app is being killed by task manager

doanpt avatar Jun 10 '23 02:06 doanpt