Basic use of Android QR code (3): QR code scanning Demo implementation

foreword

In the previous two articles, we described the generation, storage and sharing of QR codes. This time we will explain the scanning content of QR codes and realize a simple Android scanning function.

Series of articles:


Basic use of Android QR codes (1): Use Zxing to generate custom
QR codes

1. lib library description

Scanning the QR code also requires the introduction of the zxing library, but since the native zxing library generally supports custom features, I choose to introduce the auxiliary library here:

implementation 'com.king.zxing:zxing-lite:1.1.9-androidx'

The zxing-lite library is actually a simplified auxiliary library of Zxing, which optimizes the code scanning function and has built-in flashlight and other functions, which makes code integration easier.

Its GitHub address is as follows:
zxing-lite Github address

1. Layout realization

First of all, let's add a layout activity_q_r_scanner.xml, including a scan code box, and turn on the flash switch. The code is as follows:

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

Among them com.king.zxing.ViewfinderViewis the scan box, which has many attributes, such as setting prompt text labelText, etc. You can query and use attributes on zxing-lite's GitHub address.

Two, activity code

Add an activity corresponding to the layout—— QRScannerActivity.kt, first we need to judge the permission problem, as follows:

    /**
     * 权限检查
     */
    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()
                    }
                })
        }
    }

Then you need to configure the properties of the scan code box, the code is as follows:

    /**
     * 初始化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中对其的重新赋值
    }

In addition, we need to process in the life cycle of Activity, inherit OnCaptureCallbackthe interface at the same time, onCreate()initialize configuration and permission processing in , and process in ,, the code is as follows 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()
    }
    ...
}

Adding the above code, we can achieve the final result:

QR code scanning.png

In this way, we have implemented a QR code scanning function.

Summarize

zxing-lite is a streamlined library for implementing QR code-related content, which can easily realize the scanning function of QR codes.

Guess you like

Origin blog.csdn.net/cat_is_so_cute/article/details/121106160