Я создал пример приложения, использующего Google MLKit для сканирования штрих-кода с помощью API CameraX. Я умею сканировать штрих-код. Но сканирование происходит очень быстро, и когда необходимо сканировать несколько штрих-кодов (например, если в одной и той же позиции находится несколько штрих-кодов), сканер сканирует один штрих-код несколько раз, а затем переходит к следующему штрих-коду.
Я пытаюсь сделать так, чтобы мой макет содержал предварительный просмотр и TextView, где отсканированный штрих-код обновляется до TextView. Обновление TextView происходит настолько быстро, что я не вижу значения отсканированного штрих-кода. Есть ли способ сделать паузу на несколько секунд, а затем начать сканирование, или же, если один и тот же штрих-код сканируется несколько раз, можем ли мы попробовать пропустить обновление TextView с этим значением?
Я поделюсь своим кодом ниже:
private fun bindCameraUseCases() {
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener({
val cameraProvider = cameraProviderFuture.get()
// setting up the preview use case
val previewUseCase = Preview.Builder()
.build()
.also {
it.setSurfaceProvider(previewView.surfaceProvider)
}
val options = BarcodeScannerOptions.Builder()
.enableAllPotentialBarcodes()
.build()
val scanner = BarcodeScanning.getClient(options)
// setting up the analysis use case
val analysisUseCase = ImageAnalysis.Builder()
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build()
val cameraExecutor = Executors.newSingleThreadExecutor()
analysisUseCase.setAnalyzer(
Executors.newSingleThreadExecutor()
) { imageProxy ->
processImageProxy(scanner, imageProxy)
}
// configure to use the back camera
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
try {
cameraProvider.bindToLifecycle(
this,
cameraSelector,
previewUseCase,
analysisUseCase)
} catch (illegalStateException: IllegalStateException) {
// If the use case has already been bound to another lifecycle or method is not called on main thread.
Log.e("MainActivity", illegalStateException.message.orEmpty())
} catch (illegalArgumentException: IllegalArgumentException) {
// If the provided camera selector is unable to resolve a camera to be used for the given use cases.
Log.e("MainActivity", illegalArgumentException.message.orEmpty())
}
}, ContextCompat.getMainExecutor(this))
}
Обработка изображения и значение обновляются до TextView в приведенном ниже методе:
@SuppressLint("UnsafeOptInUsageError")
private fun processImageProxy(
barcodeScanner: BarcodeScanner,
imageProxy: ImageProxy
) {
imageProxy.image?.let { image ->
val inputImage =
InputImage.fromMediaImage(
image,
imageProxy.imageInfo.rotationDegrees
)
barcodeScanner.process(inputImage)
.addOnSuccessListener { barcodeList ->
val barcode = barcodeList.getOrNull(0)
// `rawValue` is the decoded value of the barcode
**if (lastScannedBarcodeValue != barcode?.rawValue) {
barcode?.rawValue?.let { value ->
barCodeResult.text = value
}
}**
}
.addOnFailureListener {
// This failure will happen if the barcode scanning model
// fails to download from Google Play Services
Log.e("MainActivity", it.message.orEmpty())
}.addOnCompleteListener {
// When the image is from CameraX analysis use case, must
// call image.close() on received images when finished
// using them. Otherwise, new images may not be received
// or the camera may stall.
imageProxy.image?.close()
imageProxy.close()
}
}
}
Я обновляюсь до TextView в блоке addSuccess()....
// Camera API
implementation("androidx.camera:camera-camera2:1.2.1")
implementation("androidx.camera:camera-lifecycle:1.2.1")
implementation("androidx.camera:camera-view:1.2.1")
// MLKit
implementation("com.google.mlkit:barcode-scanning:17.1.0")
Подробнее здесь: https://stackoverflow.com/questions/764 ... ng-camerax
Сканер штрих-кода Google MLKit с использованием CameraX ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение