본문 바로가기

프로그래밍/Android

[Android] 안드로이드 QR 스캐너 어플리케이션 예제

Kotlin 으로 QR 스캐너 예제를 만들어보자!

간단한 QR 스캐너 어플리케이션

example github

https://github.com/makepluscode/android-qr-scanner-app

 

GitHub - makepluscode/android-qr-scanner-app: QR code scanner with Kotlin

QR code scanner with Kotlin. Contribute to makepluscode/android-qr-scanner-app development by creating an account on GitHub.

github.com

build.gradle

build.gradle 파일에 compile option 을 추가한다.

    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }

QR 스캔 라이브러리를 사용하기 위해, build.grade 파일의 dependencies 항목에 zxing-android-embedded 라이브러리를 추가한다.

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

AndroidManifest.xml

어플리케이션에서 카메라를 원활히 사용하기 위해서 하드웨어 가속을 활성화 한다.

android:hardwareAccelerated="true"

activity_main.xml

  • 단순한 LinearLayout 으로 변경한다.
  • Button 을 추가하고, Click 이벤트가 발생하면 runQRcodeReader 를 callback 할 수 있게 설정한다.
  • 인식된 QR image 를 출력하기 위해 ImageView 를 추가한다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="QR 읽기"
        android:onClick="runQRcodeReader" />

    <ImageView
        android:id="@+id/scannedBitmap"
        android:layout_width="400dp"
        android:layout_height="200dp" />

</LinearLayout>

MainActivity.kt

  • Button Click 이벤트가 발생하면 runQRcodeReader 가 호출된다. runQRcodeReader 에서 zxing-android-embedded 라이브러리를 통해 QR reader 를 실행한다.
  • QR reader 실행 결과를 받기위해 onActivityResult 를 override 한다. 인식된 QR 이 있을 경우, Toast 를 통해 화면에 출력한다. 인식된 QR 이미지가 있을 경우, bitmap 이미지를 화면에 출력한다.
package com.example.qrscanner

import android.content.Intent
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.zxing.integration.android.IntentIntegrator

import android.view.View
import android.widget.Toast
import android.widget.ImageView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun runQRcodeReader(view: View) {
        val integrator = IntentIntegrator(this)
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
        integrator.setPrompt("QRÄڵ带 ½ºÄµÇØÁÖ¼¼¿ä!")
        integrator.setCameraId(0)
        integrator.setBeepEnabled(true)
        integrator.setBarcodeImageEnabled(true)
        integrator.initiateScan()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if(result != null) {
            if (result.contents != null) {
                Toast.makeText(
                    this, "Scanned : ${result.contents} format: ${result.formatName}",
                    Toast.LENGTH_LONG
                ).show()
            }
            if(result.barcodeImagePath != null) {
                val bitmap = BitmapFactory.decodeFile(result.barcodeImagePath)
                val imgView : ImageView = findViewById(R.id.scannedBitmap)
                imgView.setImageBitmap(bitmap)
            }
        }
        else {
            super.onActivityResult(requestCode, resultCode, data);
        }
        //super.onActivityResult()
    }
}

실행결과


참고자료

이 예제에서 사용한 zxing-android-embedded 라이브러리의 github 코드를 참고한다.

https://github.com/journeyapps/zxing-android-embedded

 

GitHub - journeyapps/zxing-android-embedded: Barcode scanner library for Android, based on the ZXing decoder

Barcode scanner library for Android, based on the ZXing decoder - GitHub - journeyapps/zxing-android-embedded: Barcode scanner library for Android, based on the ZXing decoder

github.com