简体   繁体   English

ML Kit 条码扫描器在检测到第一个时不会停止

[英]ML Kit barcode Scanner don't stop when first is detected

I'm trying to get two values from cameraX and ML Kit using the barcode scanner (rawValue and format) but I can't stop the scan and insert data into room when the first one is detected.我正在尝试使用条形码扫描仪(rawValue 和格式)从 cameraX 和 ML Kit 获取两个值,但是当检测到第一个时,我无法停止扫描并将数据插入房间。 My code inserts in room as many elements as many barcodes are detected in the process (the same barcode many times)我的代码在房间中插入了与过程中检测到的条码一样多的元素(多次相同的条码)

This is my addOnSuccessListener in the processImageProxy function:这是我在 processImageProxy function 中的 addOnSuccessListener:

   scanner.process(inputImage).addOnSuccessListener { barcodeList ->
                processBarcode(barcodeList)
            }

And this is my actual method to keep data:这是我保存数据的实际方法:

    private fun processBarcode(barcodeList: List<Barcode>) {
        if (barcodeList.isNotEmpty()) {
            with (barcodeList.first()) {

                activityCameraScannerViewModel.rawValue = this.rawValue.toString()
                activityCameraScannerViewModel.format = this.format.toString()
                activityCameraScannerViewModel.setNewCard()

                val intent = Intent(applicationContext, MainActivity::class.java)
                intent.putExtra("rawValue", this.rawValue.toString())
                intent.putExtra("format", this.format.toString())
                startActivity(intent)
            }
        }
    }

The actual result of code is a lot of inserts (random number of them).代码的实际结果是很多插入(随机数)。 I would appreciate any help.我将不胜感激任何帮助。 If anybody need more code I will edit the question.如果有人需要更多代码,我将编辑问题。 Thanks.谢谢。

Simply resolution:简单解决:

Pass scanner as parameter of processBarcode function and call将扫描器作为 processBarcode function 的参数传递并调用

scanner.close()

Complete code:完整代码:

 private fun processBarcode(barcodeList: List<Barcode>, scanner: BarcodeScanner) {
        if (barcodeList.isNotEmpty()) {
            with (barcodeList.first()) {

                val rawValue = this.rawValue.toString()
                val format = this.format.toString()
                activityCameraScannerViewModel.rawValue = rawValue
                activityCameraScannerViewModel.format = format

                activityCameraScannerViewModel.setNewCard()
                val intent = Intent(applicationContext, MainActivity::class.java)
                startActivity(intent)
                scanner.close()
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM