スマホで簡易にQRコードリーダーを動かしたいとき、ZXingというのがあります。それを含むパッケージに、https://github.com/journeyapps/zxing-android-embedded というのがあります。この秋に、それがRegisterActivityResult対応し、Integratorとか機能をDeprecateしました。
それを取り込むのにひと手間あったので、ここへ記録。
1.zxing-android-embedded は、Javaコードしか提供していません。Kotlinほしい。Android StudioでそのSampleをコンバートすりゃいいのですが。ネットで調べた限り、まだ誰も載せていないので、以下にKotlinでのスケルトン載せておきます。これだけ。非常にSimple。
2.以前動いていたコードが、もう動かない、原因を調べたところ、ManifestでActivity属性で、android:noHistory="true" という変更をしたのが邪魔していた。なんでか、理解していない。誰か教えてくれ。
import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanOptions
...
val barcodeLauncher = registerForActivityResult(ScanContract()) { result ->
if (result.contents != null) {
読み取ったQRコードテキストの処理
} else {
失敗処理
}
val options = ScanOptions()
options.setOrientationLocked(false)
barcodeLauncher.launch(options)
あとはbuild.gradleに、以下。
implementation 'com.journeyapps:zxing-android-embedded:4.3.0'
また、Manifestに、以下を追加。
<activity
android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="fullSensor"
tools:replace="screenOrientation" />