7
2

More than 1 year has passed since last update.

KotlinでZXingを用いてQRコードリーダーを作る方法

Last updated at Posted at 2022-11-08

はじめに

Android端末でQRコードリーダーを作る際には、ZXingというライブラリを使うことが多いみたいです。

しかしこのZXingのドキュメントは全てJavaで書かれており、Kotlinで実装したものがなかったため、備忘録としてKotlinでの実装を残しておきます。

実装

まずライブラリを追加します。

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

次に権限周りの設定を行います。

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

         // ここでライブラリのAndroidManifestを更新する
         <activity
            // ここでカメラ起動時に横画面になる設定を上書き
            android:screenOrientation="fullSensor"
            tools:replace="screenOrientation"
            android:name="com.journeyapps.barcodescanner.CaptureActivity">
        </activity>

注意
2つ目のactivityタグは新しく新規作成するようにしましょう。
ここでactivityタグを書くことで、カメラ起動時に横画面になるという初期設定を上書きできます。

最後にActivity内でQRコードリーダーを起動します。
ベタガキしてるので各自で整えてください🙏

MainActivity
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // ScanContractの結果を受け取る
        val barcodeLauncher = registerForActivityResult(
            ScanContract()
        ) { result ->
            if (result.contents == null) {
                // ここでQRコードを読み取れなかった場合の処理を書く
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG)
                    .show()
            } else {
                // ここでQRコードを読み取れた場合の処理を書く
                // ここではトーストに結果を表示するだけ
                Toast.makeText(this, "Scanned: " + result.contents, Toast.LENGTH_LONG)
                    .show()
            }
        }

        // QRコードリーダーの立ち上げ
        fun onButtonClick() {
            // 縦画面に固定
            val options = ScanOptions().setOrientationLocked(false)
            barcodeLauncher.launch(options)
        }

        super.onCreate(savedInstanceState)
        setContent {
            QRCodeReaderTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    // ボタンタップで起動
                    TextButton(onClick = { onButtonClick() }) {
                        Text(text = "QRCodeReaderを起動する")
                    }
                }
            }
        }
    }
}

できたもの

ドキュメント一覧

https://github.com/journeyapps/zxing-android-embedded
https://developer.android.com/studio/build/manifest-merge
https://developer.android.com/training/basics/intents/result?hl=ja

最後まで読んでいただきありがとうございました。
よければtwitterのフォローよろしくお願いします。

7
2
1

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
7
2