Skip to content

Commit 3c92517

Browse files
committed
android: refine nfc handler logic to prevent thread leaking
Signed-off-by: Shengqi Chen <[email protected]>
1 parent fd9be81 commit 3c92517

File tree

2 files changed

+11
-11
lines changed

2 files changed

+11
-11
lines changed

CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@
197197
* Refactor with new `dart:js_interop` APIs to fix build with WASM (#223)
198198
* Support `readBlock` / `writeBlock` on Mifare tags on iOS (#205 by @rushank-shah)
199199
* More robust logic on Android
200-
* ensure NFC Handler is always alive (#219 by @Akshya107)
200+
* ensure NFC Handler is always alive (#219)
201201
* prevent an NPE due to wrong API typing (#220)
202202
* add comment on `poll` related to Samsung API bug (#190, #200)
203203
* Add more detailed error message in iOS APIs

android/src/main/kotlin/im/nfc/flutter_nfc_kit/FlutterNfcKitPlugin.kt

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,13 @@ class FlutterNfcKitPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
7171
return transceiveMethod.invoke(this, data) as ByteArray
7272
}
7373

74+
private fun ensureNfcHandler() {
75+
if (!::nfcHandlerThread.isInitialized || !nfcHandlerThread.isAlive) {
76+
nfcHandlerThread = HandlerThread("FlutterNfcKit-NfcHandlerThread").apply { start() }
77+
nfcHandler = Handler(nfcHandlerThread.looper)
78+
}
79+
}
80+
7481
private fun runOnNfcThread(result: Result, desc: String, fn: () -> Unit) {
7582
val handledFn = Runnable {
7683
try {
@@ -89,13 +96,8 @@ class FlutterNfcKitPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
8996
}
9097
}
9198
}
92-
val looperThread = nfcHandler.looper?.thread
93-
if (looperThread == null || !looperThread.isAlive) {
94-
val thread = HandlerThread("FlutterNfcKit").apply { start() }
95-
nfcHandler = Handler(thread.looper)
96-
}
97-
val posted = nfcHandler.post(handledFn)
98-
if (!posted) {
99+
ensureNfcHandler()
100+
if (!nfcHandler.post(handledFn)) {
99101
result.error("500", "Failed to post job to NFC Handler thread.", null)
100102
}
101103
}
@@ -249,9 +251,7 @@ class FlutterNfcKitPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
249251
}
250252

251253
override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
252-
nfcHandlerThread = HandlerThread("NfcHandlerThread")
253-
nfcHandlerThread.start()
254-
nfcHandler = Handler(nfcHandlerThread.looper)
254+
ensureNfcHandler()
255255

256256
methodChannel = MethodChannel(flutterPluginBinding.binaryMessenger, "flutter_nfc_kit/method")
257257
methodChannel.setMethodCallHandler(this)

0 commit comments

Comments
 (0)