Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.comsoft.code_app
- import android.content.pm.PackageManager
- import android.graphics.Bitmap
- import android.os.Build
- import androidx.appcompat.app.AppCompatActivity
- import android.os.Bundle
- import android.util.Log
- import android.widget.Toast
- import androidx.activity.result.contract.ActivityResultContracts
- import androidx.camera.core.CameraSelector
- import androidx.camera.core.ImageAnalysis
- import androidx.camera.core.ImageCapture
- import androidx.camera.core.ImageProxy
- import androidx.camera.core.Preview
- import androidx.camera.lifecycle.ProcessCameraProvider
- import androidx.camera.view.PreviewView
- import androidx.core.content.ContextCompat
- import androidx.lifecycle.LifecycleOwner
- import com.comsoft.code_app.databinding.ActivityScanBinding
- import com.google.common.util.concurrent.ListenableFuture
- import com.google.zxing.BinaryBitmap
- import com.google.zxing.LuminanceSource
- import com.google.zxing.RGBLuminanceSource
- import com.google.zxing.common.HybridBinarizer
- import com.google.zxing.qrcode.QRCodeReader
- import java.nio.ByteBuffer
- import java.util.concurrent.ExecutorService
- import java.util.concurrent.Executors
- typealias QRListener = (code: String) -> Unit
- class ScanActivity : AppCompatActivity() {
- private lateinit var viewBinding: ActivityScanBinding
- private var imageCapture: ImageCapture? = null
- private lateinit var cameraExecutor: ExecutorService
- private val activityResultLauncher =
- registerForActivityResult(
- ActivityResultContracts.RequestMultiplePermissions())
- { permissions ->
- // Handle Permission granted/rejected
- var permissionGranted = true
- permissions.entries.forEach {
- if (it.key in REQUIRED_PERMISSIONS && it.value == false)
- permissionGranted = false
- }
- if (!permissionGranted) {
- Toast.makeText(baseContext,
- "Permission request denied",
- Toast.LENGTH_SHORT).show()
- } else {
- startCamera()
- }
- }
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- viewBinding = ActivityScanBinding.inflate(layoutInflater)
- setContentView(viewBinding.root)
- // Request camera permissions
- if (allPermissionsGranted()) {
- startCamera()
- } else {
- requestPermissions()
- }
- cameraExecutor = Executors.newSingleThreadExecutor()
- }
- private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
- ContextCompat.checkSelfPermission(
- baseContext, it) == PackageManager.PERMISSION_GRANTED
- }
- private fun requestPermissions() {
- activityResultLauncher.launch(REQUIRED_PERMISSIONS)
- }
- private fun startCamera() {
- val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
- cameraProviderFuture.addListener({
- // Used to bind the lifecycle of cameras to the lifecycle owner
- val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
- // Preview
- val preview = Preview.Builder()
- .build()
- .also {
- it.setSurfaceProvider(viewBinding.viewFinder.surfaceProvider)
- }
- val imageAnalyzer = ImageAnalysis.Builder()
- .build()
- .also {
- it.setAnalyzer(cameraExecutor, QrAnalyzer { decoded_str ->
- runOnUiThread{
- viewBinding.decodedText.setText(decoded_str)
- }
- })
- }
- // Select back camera as a default
- val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
- try {
- // Unbind use cases before rebinding
- cameraProvider.unbindAll()
- // Bind use cases to camera
- cameraProvider.bindToLifecycle(
- this, cameraSelector, preview, imageAnalyzer)
- } catch(exc: Exception) {
- Log.e(TAG, "Use case binding failed", exc)
- }
- }, ContextCompat.getMainExecutor(this))
- }
- override fun onDestroy() {
- super.onDestroy()
- cameraExecutor.shutdown()
- }
- companion object {
- private const val TAG = "CameraXApp"
- private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS"
- private val REQUIRED_PERMISSIONS =
- mutableListOf (
- android.Manifest.permission.CAMERA,
- android.Manifest.permission.RECORD_AUDIO
- ).apply {
- if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
- add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
- }
- }.toTypedArray()
- }
- private class QrAnalyzer(private val listener: QRListener) : ImageAnalysis.Analyzer {
- fun BitmapToBinaryBitmap(src: Bitmap): BinaryBitmap {
- val intArray = IntArray(src.width * src.height)
- src.getPixels(intArray, 0, src.width, 0, 0, src.width, src.height)
- val source: LuminanceSource = RGBLuminanceSource(src.width, src.height, intArray)
- return BinaryBitmap(HybridBinarizer(source))
- }
- private fun ByteBuffer.toByteArray(): ByteArray {
- rewind() // Rewind the buffer to zero
- val data = ByteArray(remaining())
- get(data) // Copy the buffer into a byte array
- return data // Return the byte array
- }
- override fun analyze(image: ImageProxy) {
- //val buffer = image.planes[0].buffer
- val bitmap = image.toBitmap()
- //val data = buffer.toByteArray()
- var decoded_str = "Test string"
- val reader = QRCodeReader()
- try {
- decoded_str = reader.decode(BitmapToBinaryBitmap(bitmap)).text
- } catch(e: Exception) {
- }
- finally {
- listener(decoded_str)
- }
- image.close()
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement