zxing - 将 Zxing 库与 Jetpack 组合使用
问题描述
我正在尝试使用 zxing 库实现 qr 扫描仪。为此,我在屏幕上添加了一个按钮,单击它,我将启动扫描仪,如下所示
Button(
onClick = {
val intentIntegrator = IntentIntegrator(context)
intentIntegrator.setPrompt(QrScanLabel)
intentIntegrator.setOrientationLocked(true)
intentIntegrator.initiateScan()
},
modifier = Modifier
.fillMaxWidth()
) {
Text(
text = QrScanLabel
)
}
但是,它启动了一个意图,该意图期望onActivityResult
方法能够取回结果。Jetpack compose 使用rememberLauncherForActivityResult
如下
val intentLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartIntentSenderForResult()
) {
if (it.resultCode != RESULT_OK) {
return@rememberLauncherForActivityResult
}
...
}
但是我们如何在这里将两者整合在一起呢?
解决方案
我使用相同的库制作了一个临时解决方案:Gradle 依赖项:
implementation('com.journeyapps:zxing-android-embedded:4.1.0') { transitive = false }
implementation 'com.google.zxing:core:3.4.0'
我的带有 jetpack compose 和相机捕捉的新屏幕,适用于我的应用程序:
@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 },
)
}
推荐阅读
- bash - 卷曲没有连接
- sql - 根据条件创建列 - sql
- python - 如何将 PyMOL 中的命令输出保存到 txt 文件?
- javascript - 如何在tiptap文本编辑器中将嵌套的vuex对象绑定到vuejs属性?
- javascript - 如何在 Javascript 中使用尾随 ISO 代码格式化货币?
- mongodb - 有什么方法可以在 mongo 中隐藏数据库管理员的收集数据?
- node.js - 当我尝试使用 nodejs 将文件上传到 S3 时出现 cors 问题
- javascript - 如何在innerHTML中调用函数和访问
- python - byte offset in reading binary data file with numpy
- python - 调试使用 Beautifulsoup 的网页抓取脚本