Android에서 QR 코드 구현

Mar 01 2023
최근 QR 코드의 사용은 결제, 레스토랑 메뉴에서 체크인/체크아웃 메커니즘에 이르기까지 점점 더 널리 보급되어 여러 사무실이나 공공 장소 입구에서 사용되기 시작했습니다. 기본적으로 QR 코드는 데이터 자체를 나타내는 고유한 이미지로 소비자에게 데이터를 제공하는 프로세스를 용이하게 하며, 데이터는 소비자가 궁극적으로 어떤 조치를 취해야 하는지 결정할 수 있도록 관리됩니다.

최근 QR 코드의 사용은 결제, 레스토랑 메뉴에서 체크인/체크아웃 메커니즘에 이르기까지 점점 더 널리 보급되어 여러 사무실이나 공공 장소 입구에서 사용되기 시작했습니다.

기본적으로 QR 코드는 데이터 자체를 나타내는 고유한 이미지로 소비자에게 데이터를 제공하는 프로세스를 용이하게 하며, 데이터는 소비자가 궁극적으로 어떤 조치를 취해야 하는지 결정할 수 있도록 관리됩니다.

기본적으로 QRCode는 데이터를 고유한 이미지 형태로 표현한 것일 뿐입니다.

Android 개발에서는 두 가지 기능을 우리 측에서 독립적으로 구현할 수 있습니다.

발전기

QR 코드 생성을 위해 Google에서 이 라이브러리를 사용할 수 있습니다.

implementation 'com.google.zxing:core:3.2.1

private fun generatedQR(value: String): Bitmap? {
        val bitMatrix: BitMatrix
        try {
            bitMatrix = MultiFormatWriter().encode(
                    value,
                    BarcodeFormat.QR_CODE,
                    500, 500, null
            )

        } catch (e: IllegalArgumentException) {
            return null
        }

        val bitMatrixWidth = bitMatrix.width

        val bitMatrixHeight = bitMatrix.height

        val pixels = IntArray(bitMatrixWidth * bitMatrixHeight)

        for (y in 0 until bitMatrixHeight) {
            val offset = y * bitMatrixWidth

            for (x in 0 until bitMatrixWidth) {

                pixels[offset + x] = if (bitMatrix.get(x, y))
                    ContextCompat.getColor(this, R.color.black)
                else
                    ContextCompat.getColor(this, R.color.white)
            }
        }
        val bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_8888)

        bitmap.setPixels(pixels, 0, 500, 0, 0, bitMatrixWidth, bitMatrixHeight)
        return bitmap
    }

여기에서 우리는 데이터와 BarcodeFormat을 모두 인코딩합니다 bitMatrix.

val bitMatrix: BitMatrix
        try {
            bitMatrix = MultiFormatWriter().encode(
                    value,
                    BarcodeFormat.QR_CODE,
                    500, 500, null
            )

        } catch (e: IllegalArgumentException) {
            return null
        }

val bitmap = generatedQR(args)
imageView.setImageBitmap(bitmap)

스캐너의 경우 이 라이브러리를 사용해야 합니다.

implementation 'com.journeyapps:zxing-android-embedded:3.6.0'

val scanner = IntentIntegrator(this)
            scanner.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
            scanner.setBeepEnabled(true) //optional
            scanner.initiateScan()

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
            if (result != null) {
                if (result.contents == null) {
                    toast("Cancelled !")
                } else {
                    textView.text = "Your data from scanner is ${result.contents}" //do whatever you want with the data
                }
            } else {
                super.onActivityResult(requestCode, resultCode, data)
            }
        }
    }

그건 그렇고, 나는 약 4년 전에 한 프로젝트에 그 코드를 작성했습니다. 더 이상 사용되지 않는 클래스/함수 사용이 있을 수 있으며 이에 대한 새로운 접근 방식이 있을 수 있습니다. 그 중 하나는 jetpack의 ML 키트를 사용하는 것입니다.

위에서 설명한 코드의 전체 코드는 다음과 같습니다.

—