Bha*_*mar 7 zxing android-jetpack-compose
我正在尝试使用 zxing 库实现 qr 扫描仪。为此,我在屏幕上添加了一个按钮,单击它后,我将启动扫描仪,如下所示
Button(
onClick = {
val intentIntegrator = IntentIntegrator(context)
intentIntegrator.setPrompt(QrScanLabel)
intentIntegrator.setOrientationLocked(true)
intentIntegrator.initiateScan()
},
modifier = Modifier
.fillMaxWidth()
) {
Text(
text = QrScanLabel
)
}
Run Code Online (Sandbox Code Playgroud)
但是,它启动了一个意图,期望onActivityResult方法返回结果。Jetpack compose 使用rememberLauncherForActivityResult如下
val intentLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartIntentSenderForResult()
) {
if (it.resultCode != RESULT_OK) {
return@rememberLauncherForActivityResult
}
...
}
Run Code Online (Sandbox Code Playgroud)
但我们如何在这里将两者整合在一起呢?
Jos*_*e S 15
我使用相同的库制作了一个临时解决方案:Gradle 依赖项:
implementation('com.journeyapps:zxing-android-embedded:4.1.0') { transitive = false }
implementation 'com.google.zxing:core:3.4.0'
Run Code Online (Sandbox Code Playgroud)
我的新屏幕带有喷气背包构图和相机捕捉功能,适用于我的应用程序:
@Composable
fun AdminClubMembershipScanScreen(navController: NavHostController) {
val context = LocalContext.current
var scanFlag by remember {
mutableStateOf(false)
}
val compoundBarcodeView = remember {
CompoundBarcodeView(context).apply {
val capture = CaptureManager(context as Activity, this)
capture.initializeFromIntent(context.intent, null)
this.setStatusText("")
capture.decode()
this.decodeContinuous { result ->
if(scanFlag){
return@decodeContinuous
}
scanFlag = true
result.text?.let { barCodeOrQr->
//Do something and when you finish this something
//put scanFlag = false to scan another item
scanFlag = false
}
//If you don't put this scanFlag = false, it will never work again.
//you can put a delay over 2 seconds and then scanFlag = false to prevent multiple scanning
}
}
}
AndroidView(
modifier = Modifier,
factory = { compoundBarcodeView },
)
}
Run Code Online (Sandbox Code Playgroud)
gmk*_*k57 15
因为zxing-android-embedded:4.3.0有一个ScanContract, 可以直接从 Compose 中使用:
val scanLauncher = rememberLauncherForActivityResult(
contract = ScanContract(),
onResult = { result -> Log.i(TAG, "scanned code: ${result.contents}") }
)
Button(onClick = { scanLauncher.launch(ScanOptions()) }) {
Text(text = "Scan barcode")
}
Run Code Online (Sandbox Code Playgroud)
已接受答案的附录
这个答案深入探讨了 @Bharat Kumar 和 @Jose Pose S 在接受的答案中评论的问题。
我基本上只是在代码中实现了接受的答案,然后在定义之后添加了以下代码compundBarCodeView
DisposableEffect(key1 = "someKey" ){
compoundBarcodeView.resume()
onDispose {
compoundBarcodeView.pause()
}
}
Run Code Online (Sandbox Code Playgroud)
这可以确保扫描仪仅在位于前台时才处于活动状态,并减轻我们设备的负担。
长话短说
有时,即使您成功扫描二维码并离开扫描仪屏幕,条形码视图也会通过继续从后台扫描来“困扰”您。你通常不想要的。即使您使用布尔标志来防止扫描仪在焦点从扫描仪移开后执行任何操作,它仍然会给您的处理器带来负担并减慢您的用户界面,因为仍然有一个进程在后台不断解密高分辨率图像。
| 归档时间: |
|
| 查看次数: |
9146 次 |
| 最近记录: |