序文
前回の2回の記事でQRコードの生成・保存・共有について説明しましたが、今回はQRコードの読み取り内容を説明し、Androidの簡単な読み取り機能を実現します。
一連の記事:
Android QR コードの基本的な使い方(1): Zxing を使用してカスタム
QR コードを生成する
1. lib ライブラリの説明
QR コードをスキャンするには zxing ライブラリも導入する必要がありますが、ネイティブの zxing ライブラリは一般にカスタム機能をサポートしているため、ここでは補助ライブラリを導入することにしました。
implementation 'com.king.zxing:zxing-lite:1.1.9-androidx'
zxing-lite ライブラリは、実際には Zxing の単純化された補助ライブラリであり、コード スキャン機能を最適化し、懐中電灯やその他の機能を組み込み、コードの統合も容易にします。
その GitHub アドレスは次のとおりです。
zxing-lite Github アドレス
1. レイアウトの実現
まず、activity_q_r_scanner.xml
スキャン コード ボックスを含むレイアウトを追加し、フラッシュ スイッチをオンにします。コードは次のとおりです。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<SurfaceView
android:id="@+id/sv_preview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.king.zxing.ViewfinderView
android:id="@+id/vfv"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:cornerColor="@color/color_4E5BCD"
app:cornerRectHeight="54dp"
app:cornerRectWidth="4dp"
app:frameColor="@color/color_4E5BCD"
app:frameHeight="242dp"
app:frameWidth="242dp"
app:labelText="请扫描智慧码"
app:labelTextColor="@color/color_ffffff"
app:labelTextLocation="bottom"
app:labelTextPadding="18dp"
app:labelTextSize="16sp"
app:laserColor="@color/color_4E5BCD"
app:maskColor="@color/color_80000000"
app:scannerLineHeight="4dp" />
<TextView
android:id="@+id/tv_torch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:drawableTop="@drawable/selector_torch"
android:drawablePadding="12dp"
android:gravity="center"
android:text="打开照明"
android:textColor="@color/color_ffffff"
android:textSize="26sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:ignore="HardCodedText" />
</androidx.constraintlayout.widget.ConstraintLayout>
その中にはcom.king.zxing.ViewfinderView
、プロンプト テキストの設定など、多くの属性を持つスキャン ボックスがありますlabelText
。zxing-lite の GitHub アドレスで属性をクエリして使用できます。
二、活動コード
レイアウトに対応するアクティビティを追加します—— QRScannerActivity.kt
、まず、次のようにパーミッションの問題を判断する必要があります。
/**
* 权限检查
*/
private fun checkPermission() {
if (!checkPermissions(arrayOf(Manifest.permission.CAMERA))) {
//弹起授权弹窗
baseRequestPermissions(
arrayOf(Manifest.permission.CAMERA),
object : PermissionCallback() {
override fun onPermissionGranted(permissions: Array<String?>?) {}
override fun onPermissionDenied(permissions: Array<String?>?) {
Toast.makeText(mActivity,"权限被拒绝",Toast.LENGTH_SHORT).show()
finish()
}
})
}
}
次に、スキャン コード ボックスのプロパティを構成する必要があります。コードは次のとおりです。
/**
* 初始化QRScanner配置
*/
private fun initQRConfig(){
captureHelper = CaptureHelper(this, viewBinding.svPreview, viewBinding.vfv, null)
captureHelper.setOnCaptureCallback(this)
captureHelper.decodeFormats(DecodeFormatManager.QR_CODE_FORMATS)
.supportAutoZoom(true) // 自动缩放
.fullScreenScan(true) // 全屏扫码识别
.supportLuminanceInvert(true) // 是否支持识别反色码,黑白颜色反转,开启提高识别效率
.continuousScan(true) // 开启连续扫描
.autoRestartPreviewAndDecode(false) // 连续扫描开启情况下,取消自动继续扫描,自己处理完后调用restartPreviewAndDecode()
.playBeep(true) // 播放beep声音
.supportZoom(true) // 支持双指缩放
.frontLightMode(FrontLightMode.OFF) // 默认关闭闪光灯
.setOnCaptureCallback(this) // 设置回调
.onCreate()
val cameraManager: CameraManager = captureHelper.cameraManager
cameraManager.setOnTorchListener { torch: Boolean ->
viewBinding.tvTorch.isSelected = torch
viewBinding.tvTorch.text = if (torch) "关闭照明" else "打开照明"
}
viewBinding.tvTorch.setOnClickListener(View.OnClickListener {
cameraManager.setTorch(
!viewBinding.tvTorch.isSelected
)
})
viewBinding.tvTorch.post(Runnable { this.updateScanFrameLocation() })
}
/**
* 更新扫描框位置
*/
private fun updateScanFrameLocation() {
//(327+184)/2-184
viewBinding.vfv.setPadding(0, 0, 0, Utils.dp2px(this, 71))
viewBinding.vfv.scannerStart = 0 // 动态改变padding时,需要设置该值为0,以触发在onDraw中对其的重新赋值
}
また、Activityのライフサイクルで処理を行う必要があり、OnCaptureCallback
同時にインターフェースを継承し、onCreate()
設定の初期化と権限の処理を で行い、処理を で行います。コードは次のとおりですonResume()
。onPause()
onDestory()
@Route(path = ConstUtil.QRCodeActivityPath)
class QRScannerActivity : BaseActivity(),OnCaptureCallback {
private lateinit var viewBinding: ActivityQRScannerBinding
private lateinit var captureHelper: CaptureHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewBinding = ActivityQRScannerBinding.inflate(layoutInflater)
setContentView(viewBinding.root)
initQRConfig()
checkPermission()
}
override fun onResultCallback(result: String?): Boolean {
//todo 处理结果
Toast.makeText(mActivity,result,Toast.LENGTH_SHORT).show()
return true
}
override fun onResume() {
//注意在生命周期的captureHelper设置,否则可能出现无法扫描的问题
captureHelper.onResume()
super.onResume()
}
override fun onPause() {
captureHelper.onPause()
super.onPause()
}
override fun onDestroy() {
captureHelper.onDestroy()
super.onDestroy()
}
...
}
上記のコードを追加すると、最終結果が得られます。
このように、QRコードの読み取り機能を実装しました。
要約する
zxing-lite は、QR コード関連のコンテンツを実装するための合理化されたライブラリであり、QR コードのスキャン機能を簡単に実現できます。