Android二维码扫描+反转色

前言
本次文章主要讲解二维码扫描识别功能,并支持反转色扫描,并赋予源码,话不多说,直接开整。

一、依赖集成

在build.gradle添加:

maven { url "https://jitpack.io" }

APP层添加:

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

以上集成了zxing-lite库,zxing-lite库是Zxing的辅助库,对于扫码功能进行了优化,其中包含反转色扫描以及闪光灯等功能。

二、布局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"
    tools:ignore="MissingDefaultResource">


    <SurfaceView
        android:id="@+id/sv_surface_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <com.king.zxing.ViewfinderView
        android:id="@+id/vfv_zxing"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:cornerColor="#4E5BCD"
        app:cornerRectHeight="54dp"
        app:cornerRectWidth="4dp"
        app:frameColor="#4E5BCD"
        app:frameHeight="242dp"
        app:frameWidth="242dp"
        app:labelText="@string/qr_code_tip"
        app:labelTextColor="#ffffff"
        app:labelTextLocation="bottom"
        app:labelTextPadding="18dp"
        app:labelTextSize="@dimen/dimen_13"
        app:laserColor="#4E5BCD"
        app:maskColor="#80000000"
        app:scannerLineHeight="4dp" />
    <TextView
        android:id="@+id/tv_torch_flash"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:drawablePadding="12dp"
        android:gravity="center"
        android:text="@string/turn_flashlight"
        android:textColor="#ffffff"
        android:textSize="@dimen/dimen_20"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:ignore="HardCodedText" />

</androidx.constraintlayout.widget.ConstraintLayout>

三、创建QRScannerActivity工具类

public class QRScannerActivity extends BaseActivity implements OnCaptureCallback {

    private CaptureHelper captureHelper = null;
    private SurfaceView svSurfaceView = null;
    private ViewfinderView vfvZxing = null;
    private TextView tvTorch = null;
    private int scannerCode=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DeviceTools.setFullScreen(this);
        DeviceTools.setLightStatusBar(this,true);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        initView();
    }

    public void initView(){
        svSurfaceView = findViewById(R.id.sv_surface_View );
        vfvZxing= findViewById(R.id.vfv_zxing);
        tvTorch = findViewById(R.id.tv_torch);
        //特定页面,特定处理头部显示
        scannerCode=getIntent().getIntExtra("scannCode",0);
        initQRConfig();
    }

    /**
     * 初始化QRScanner配置
     */
    private void initQRConfig() {
        captureHelper = new CaptureHelper(this, svSurfaceView, vfvZxing, null);
        captureHelper.setOnCaptureCallback(this);
        captureHelper.decodeFormats(DecodeFormatManager.QR_CODE_FORMATS)
                .supportAutoZoom(true) // 自动缩放
                .fullScreenScan(true) // 全屏扫码识别
                .supportLuminanceInvert(true) // 是否支持识别反色码,黑白颜色反转,开启提高识别效率
                .continuousScan(true) // 开启连续扫描
                .supportVerticalCode(true) // 支持扫垂直的条码
                .autoRestartPreviewAndDecode(false) // 连续扫描开启情况下,取消自动继续扫描,自己处理完后调用restartPreviewAndDecode()
                .playBeep(true) // 播放beep声音
                .supportZoom(true) // 支持双指缩放
                .frontLightMode(FrontLightMode.OFF) // 默认关闭闪光灯
                .setOnCaptureCallback(this) // 设置回调
                .onCreate();
        CameraManager cameraManager = captureHelper.getCameraManager();
        cameraManager.setOnTorchListener(new CameraManager.OnTorchListener() {
            @Override
            public void onTorchChanged(boolean torch) {
                tvTorch.setSelected(torch);
                tvTorch.setText(torch ? "关闭手电筒" : "打开手电筒");

            }
        });

        tvTorch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cameraManager.setTorch(
                        !tvTorch.isSelected()
                );
            }
        });

        tvTorch.post(new Runnable() {
            @Override
            public void run() {
                updateScanFrameLocation();
            }
        });

    }

    /**
     * 更新扫描框位置
     */
    private void updateScanFrameLocation() {
        //(327+184)/2-184
        vfvZxing.setPadding(0, 0, 0, dp2px(this, 71));
        vfvZxing.scannerStart = 0;// 动态改变padding时,需要设置该值为0,以触发在onDraw中对其的重新赋值
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 开始扫描
        //注意在生命周期的captureHelper设置,否则可能出现无法扫描的问题
        captureHelper.onResume();
    }


    public int dp2px(Context context, float dp) {
        return (int) (dp * context.getResources().getDisplayMetrics().density + 0.5f);
    }


    @Override
    protected void onStop() {
        super.onStop();
        // 停止扫描
        captureHelper.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 销毁
        captureHelper.onDestroy();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_q_r_scanner;
    }


    @Override
    public boolean onResultCallback(String result) {
		if(result!=null&&!TextUtils.isEmpty(result)){
            if(scannerCode== IntentCode.INTENT_SCANN_SN_BIND){
                Intent mIntent=getIntent();
                mIntent.putExtra("scannStr",result);
                setResult(Activity.RESULT_OK,mIntent);
                finish();
            }
      }
        return true;
    }
}

四、在MainActivity使用此功能

二维码扫一扫功能实现

Intent mIntent = new Intent(DeviceTypeListActivity.this, QRScannerActivity.class);
mIntent.putExtra("scannCode", IntentCode.INTENT_SCANN_SN_BIND);
startActivityForResult(mIntent, INTENT_OPEN_SCANN);

接收二维码扫描结果

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == INTENT_OPEN_SCANN) {
            if (resultCode == Activity.RESULT_OK) {
                String scannStr = data.getStringExtra("scannStr");
            }
        }
    }

那么以上二维码扫描已完成!

意见反馈

如有问题请及时联系我,及时修复问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Android程序Su

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值