安卓 Zxing扫码

发布时间 2023-11-17 18:46:13作者: 湘summer

1. 添加依赖:

api 'com.google.zxing:core:3.3.3'
implementation 'com.king.zxing:zxing-lite:1.1.2-androidx'

 

2. 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/surfaceView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <com.king.zxing.ViewfinderView
        android:id="@+id/viewfinderView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:labelTextColor="#ffffff"
        app:labelTextLocation="bottom"
        app:laserColor="#e06c51"
        app:frameColor="#e06c51"
        app:cornerColor="#e06c51"
        app:maskColor="#7f7f7f"
        app:laserStyle="line"
        app:gridHeight="0dp"/>

    <RelativeLayout
        android:id="@+id/ll"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#000000"
        tools:ignore="MissingConstraints">

        <ImageView
            android:id="@+id/iv_scan_back"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_gravity="center_vertical"
            android:paddingRight="14dp"
            android:src="@drawable/ic_back_dark_selector" />

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:ellipsize="middle"
            android:gravity="center"
            android:singleLine="true"
            android:text="@string/qrcode_scan_title"
            android:textColor="#ffffff"
            android:textSize="18dp" />

    </RelativeLayout>
    <TextView
        android:id="@+id/ivFlash"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginTop="560dp"
        android:visibility="gone"
        android:textColor="?android:attr/textColorPrimary"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 

3.扫码页面的类:QRCaptureActivity.java

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Rect;
import android.hardware.Camera;
import android.media.Image;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;

import com.eshare.businessclient.FindDeviceActivity;
import com.eshare.businessclient.QRCodeActivity;
import com.king.zxing.CaptureActivity;
import com.king.zxing.DecodeFormatManager;
import com.king.zxing.OnCaptureCallback;
import com.king.zxing.camera.CameraConfigurationUtils;
import com.king.zxing.camera.open.CameraFacing;
import com.king.zxing.camera.open.OpenCamera;
import com.king.zxing.camera.open.OpenCameraInterface;
import com.viewsonic.vcastsender.R;

import java.io.IOException;

public class QRCaptureActivity extends CaptureActivity implements SurfaceHolder.Callback, OnCaptureCallback {
    private TextView ivFlash;
    private RelativeLayout ll;
    private ImageView ivScanBack;
    private SurfaceView surfaceView;
    int mSceenWidth;
    int mSceenHeight;

    public static void setMargins(View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_qrcapture;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("LXP","onCreate...");
        ll = findViewById(R.id.ll);
        setMargins(ll, 0, 50, 0, 0);
        TextView tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setTextColor(Color.WHITE);
        ivFlash = findViewById(R.id.ivFlash);
        if (!hasTorch()) {
            ivFlash.setVisibility(View.GONE);
        }

        ivScanBack = findViewById(R.id.iv_scan_back);
        ivScanBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        // 2.设置相机预览
        surfaceView = findViewById(R.id.surfaceView);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);

        //3.获取CaptureHelper,里面有扫码相关的配置设置
        getCaptureHelper().playBeep(false)//播放音效
                .vibrate(true)//震动
                .decodeFormats(DecodeFormatManager.QR_CODE_FORMATS)//设置只识别二维码会提升速度
                .supportVerticalCode(false)//支持扫垂直条码,建议有此需求时才使用。
                .continuousScan(false);//是否连扫
    }

    /**
     * 开启或关闭闪光灯(手电筒)
     *
     * @param on {@code true}表示开启,{@code false}表示关闭
     */
    public void setTorch(boolean on) {
        Camera camera = getCameraManager().getOpenCamera().getCamera();
        Camera.Parameters parameters = camera.getParameters();
        CameraConfigurationUtils.setTorch(parameters, on);
        camera.setParameters(parameters);
    }

    /**
     * 检测是否支持闪光灯(手电筒)
     *
     * @return
     */
    public boolean hasTorch() {
        return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    }


    /**
     * 扫码结果回调
     *
     * @param result 扫码结果
     * @return
     */
    @Override
    public boolean onResultCallback(String result) {
        Log.d("LXP","onResultCallback ----- result:"+result);
        //获取到扫码结果HmsScan,判断结果是否有效
        if (result != null && !TextUtils.isEmpty(result)) {
            //成功
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt("result_type", 1);
            bundle.putString("result_string", result);
            resultIntent.putExtras(bundle);
            setResult(RESULT_OK, resultIntent);
            finish();
        } else {
            //失败
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt("result_type", 2);
            bundle.putString("result_string", "");
            resultIntent.putExtras(bundle);
            setResult(RESULT_OK, resultIntent);
            finish();
        }
        return super.onResultCallback(result);
    }


    private void clickFlash(View v) {
        boolean isSelected = v.isSelected();
        setTorch(!isSelected);
        v.setSelected(!isSelected);
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivFlash:
                clickFlash(v);
                break;
        }
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
    }
}

4. 回调

1.点击按钮扫码
case R.id.tv_pincode_scan:
                if(PermissionUtils.requestCamera1Permissions(this)){
                    toQRCaptureActivity();
                }

2.跳转扫码页面
private void toQRCaptureActivity() {
        Log.d("LXP","scan qrcode");
        Intent intent1 = new Intent();
        intent1.putExtra(KEY_TITLE, this.getString(R.string.find_device));
        intent1.setClass(this.getApplicationContext(), QRCaptureActivity.class);
        startActivityForResult(intent1, REQUEST_CODE_SCAN);
    }
    
    
    
3.数据回调

  @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        Log.d("LXP","onActivityResult-----requestCode:"+requestCode+" resultCode:"+resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == -1) {
            String qrResult = data.getStringExtra("result_string");
            Log.d("LXP","qrResult:"+qrResult);
            if (!TextUtils.isEmpty(qrResult)) {
                qrResult = FileUtils.toURLDecoder(qrResult);
                parsingScanCodeData(qrResult);
            }
        }
    }