4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Jetpack Composeでバーコードリーダー起動

Last updated at Posted at 2023-04-17

はじめに

こちらの記事は今回使用した ZXing はドキュメントのコードが Java であるため、自身でKotlinに置き換えて実装した際のことについての備忘録です。

ライブラリの導入(JetpackCompose,ZXing)

JetpackComposeの導入

下記のサイトを参考に導入しました。

ZXingの導入

build.gradleに以下を記述しました。

build.gradle(app)
dependencies {
    implementation 'com.journeyapps:zxing-android-embedded:4.3.0'
}
settings.gradle
repositories {
    mavenCentral()
}

権限の設定

AndroidManifest.xml<Application> タグ内に次の属性を追加してアプリケーション全体のハードウェアアクセラレーションを有効にします。

AndroidManifest.xml
<application
        android:hardwareAccelerated="true">
...
</application>

QRコードリーダー作成

今回はボタンをクリックしたらQRコードリーダーが起動するようにしました。
QRコードを読み取るとQRコードリーダーが閉じられ,データの取得に応じてerrorかsuccessを返すようにしています。

SampleReader.kt
package com.example.sampleqr.view

import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanOptions

@Composable
fun SampleReaderScreen() {
    Surface {
        Column() {
            openQRCodeReaderButton()
        }
    }
}

@Composable
fun openQRCodeReaderButton() {
    val barcodeLauncher = rememberLauncherForActivityResult(
        contract = ScanContract()
    ) { result ->
        if (result.contents == null) {
            println("error")
        } else {
            println("success")
        }
    }
    Button(onClick = { barcodeLauncher.launch(ScanOptions()) }) {
        Text(text = "QRコード読み取り")
    }
}

完成図

まとめ

1. ライブラリ(JetpackCompose,ZXing)の導入
2. 権限の設定
3. ktファイルに必要な要素を追加

参考文献

クイック スタート | Jetpack Compose - Android Developers: https://developer.android.com/jetpack/compose/setup?hl=ja
ZXing公式ドキュメント: https://github.com/journeyapps/zxing-android-embedded
KotlinでZXingを用いてQRコードリーダーを作る方法: https://qiita.com/takasshii/items/5749a50e18fb524b72e6

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?