본문 바로가기
안드로이드 코틀린

[Kotlin][Android] ZXing 라이브러리 사용하여 QR 코드 생성 및 Intent 로 공유하기

by teamnova 2025. 2. 26.
728x90

 

 

안녕하세요 오늘은 안드로이드 코틀린에서 원하는 링크로 이동할 수 있는 QR 코드 생성하고

외부 어플로 공유할 수 있도록 intent 로 전달하는 예제를 만들어보도록 하겠습니다

 

이제는 일상생활 어디에서나 QR 코드를 쉽게 접할 수 있습니다. 카페나 음식점에서 메뉴를 보거나 결제할 때, 지하철/버스 정류장에서 실시간 도착 정보를 확인할 때, 공유 킥보드 및 자전거를 대여할 때, 항공권 및 기차표 전자 티켓 발급할 때 등 이외에도 정말 많은 곳에서 QR 코드가 쓰이고 있습니다. 따라서 어떻게 구현할 수 있을지 알고 있다면 유용하게 사용할 수 있을 것 같습니다.

 

안드로이드 코틀린에서는 ZXing 라이브러리를 사용해 QR 코드를 생성할 수 있습니다

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            InvitationScreen()
        }
    }
}



@Composable
fun InvitationScreen() {
    val invitationLink = "https://팀노바스틱코드초대.com/invitation/1234" // QR 코드를 통해 연결할 사이트 주소 입력
    val qrBitmap = generateQRCode(invitationLink)
    val context = LocalContext.current  //Context 가져오기

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
    
        // card 모양
        Card(
            modifier = Modifier
                .fillMaxWidth(0.9f)
                .padding(16.dp),
            shape = RoundedCornerShape(16.dp),
            elevation = CardDefaults.cardElevation(8.dp)
        ) {
            Column(
                modifier = Modifier.padding(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(text = "아래 QR 코드를 인식해주세요", fontSize = 24.sp)

                Spacer(modifier = Modifier.height(16.dp))

                // QR 코드 표시
                qrBitmap?.let {
                    Image(
                        bitmap = it.asImageBitmap(),
                        contentDescription = "QR Code",
                        modifier = Modifier.size(150.dp)
                    )
                }

                Spacer(modifier = Modifier.height(16.dp))

                // 링크 공유 버튼
                Button(onClick = { context.shareInvitation(invitationLink) }) {
                    Text(text = "공유하기")
                }
            }
        }
    }
}

// QR 코드 생성 함수
fun generateQRCode(content: String): Bitmap? {
    return try {
        val size = 500
        val bitMatrix: BitMatrix = MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, size, size)
        val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)

        for (x in 0 until size) {
            for (y in 0 until size) {
                bitmap.setPixel(x, y, if (bitMatrix[x, y]) android.graphics.Color.BLACK else android.graphics.Color.WHITE)
            }
        }
        bitmap
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

// QR 코드 공유 함수
fun Context.shareInvitation(link: String) {
    val sendIntent = Intent().apply {
        action = Intent.ACTION_SEND
        putExtra(Intent.EXTRA_TEXT, "QR 코드 링크입니다: $link")
        type = "text/plain"
    }
    startActivity(Intent.createChooser(sendIntent, "링크 공유하기"))
}

 

 

 

 

1. InvitationScreen() 함수 

invitationLink 변수에는 QR 코드를 스캔하면 이동할 수 있는 사이트의 주소를 담습니다. 예제에는 한국어로 나와있으나 영어로 작성되어야 합니다. 이어서 QR 코드가 담길 카드의 UI 를 만들어주고 "공유하기" 버튼을 만들어줍니다 

 

 

2. generateQRCode 함수 

여기서는 입력된 문자열 (invitationLink) 을 QR 코드로 변환하고 Bitmap 이미지로 생성하는 기능을 합니다. 만약 QR 코드 생성 중 오류가 발생하면 null 을 반환하고 예외 메시지를 출력합니다 

// QR 코드 생성 함수
fun generateQRCode(content: String): Bitmap? {
    return try {
        val size = 500
        val bitMatrix: BitMatrix = MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, size, size)
        val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)

        for (x in 0 until size) {
            for (y in 0 until size) {
                bitmap.setPixel(x, y, if (bitMatrix[x, y]) android.graphics.Color.BLACK else android.graphics.Color.WHITE)
            }
        }
        bitmap
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

 

 

 

3. Context.shareInvitation 함수 

이 함수는 intent 를 사용해서 QR 코드 링크를 공유하는 기능을 합니다. Intent.ACTION_SEND 를 설정함으로써 링크 데이터를 다른 앱으로 전달할 수 있도록 액션을 설정해줍니다. Intent.createChooser(sendIntent, "링크 공유하기") 로 앱 선택 창을 표시해, 사용자가 직접 공유할 앱을 선택할 수 있도록 합니다.  

// QR 코드 공유 함수
fun Context.shareInvitation(link: String) {
    val sendIntent = Intent().apply {
        action = Intent.ACTION_SEND
        putExtra(Intent.EXTRA_TEXT, "QR 코드 링크입니다: $link")
        type = "text/plain"
    }
    startActivity(Intent.createChooser(sendIntent, "링크 공유하기"))
}

 

 

 

시연 영상입니다. 

 

 

이제 원하는 링크로 이동할 수 있는 QR 코드 생성 기능과 공유 기능을 구현해보았습니다. 이 기능을 활용하면 웹사이트 링크 뿐만 아니라, 특정 앱의 기능을 실행하는 딥링크(Deep Link), 특정 데이터를 담은 QR 코드도 쉽게 만들 수 있습니다. 

 

다음에는 QR 코드 스캔 기능까지 추가하는 기능을 만들어보도록 하겠습니다. 감사합니다