Quick start of the two-dimensional code framework zxing of the Android framework

Use of Zxing

Import dependencies:

compile 'cn.yipianfengye.android:zxing-library:2.2'

request for access:

<!--震动权限-->
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!--照相机权限-->
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" /> <!-- 使用照相机权限 -->
    <uses-feature android:name="android.hardware.camera.autofocus" /> <!-- 自动聚焦权限 -->

If it is Android 6.0 or above, apply for permission dynamically

String[] permissions=new String[]{
    
    Manifest.permission.
                WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
    
    
            requestPermissions(permissions,PERMS_REQUEST_CODE);
        }

The first step is to initialize:

ZXingLibrary.initDisplayOpinion(this);

Simple scan via intent:

 //设置进行扫描二维码
Intent intent = new Intent();
intent.setClass(MainActivity.this, CaptureActivity.class);
startActivityForResult(intent,REQUEST);

Or use a mobile phone picture to scan

//进行跳转到图片
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_IMAGE);

Simple scan results are processed:

if(requestCode == 1){
    
    
    //进行简单扫描
    //获取数据
    if(data != null){
    
    
        Bundle bundle = data.getExtras();
        //判断bundle中存储的数据是否代表解析成功
        if(bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS){
    
    
            //获取解析结果
            String result = bundle.getString(CodeUtils.RESULT_STRING);
            Toast.makeText(MainActivity.this,"解析结果"+result,Toast.LENGTH_SHORT).show();
        }else{
    
    
            Toast.makeText(MainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
        }
    }

}

The result of QR code processing of images in the gallery:

public static String deCodeQR(Bitmap bitmap) {
    
    
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int[] pixels = new int[width * height];
    bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
    RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
    BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
    Result result = null;
    QRCodeReader reader = new QRCodeReader();
    try {
    
    
        result = reader.decode(binaryBitmap);
    } catch (NotFoundException e) {
    
    
        e.printStackTrace();
    } catch (ChecksumException e) {
    
    
        e.printStackTrace();
    } catch (FormatException e) {
    
    
        e.printStackTrace();
    }
    if(result == null || result.equals("")){
    
    
        return "解析结果失败";
    }
    return result.getText();
}

To obtain scan data:

if(requestCode == 2){
    
    
    //进行图片扫描
    if(data != null){
    
    
        //获取Uri
        Uri uri = data.getData();
        ContentResolver contentResolver = getContentResolver();
        try {
    
    
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri);//获取对应的Bitmap图片
            //解析bitmap二维码图片
            String s = deCodeQR(bitmap);
            Toast.makeText(this,s,Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

    }
}

Set a custom layout to scan QR codes:

The two layout files are as follows:

1. Add colors under the colors file of values ​​to determine the color of the four borders of the QR code

#0effc22.
2. Add a scan_image.png image under the drawable file, which is the horizontal line scanned by the QR code

3. Create a new Activity (called SecondActivity in the demo) to integrate FragmentActivity and configure it in the manifest file.

  1. Modify the new Activity layout file, which is the background layout of the QR code

  2. Technical point: start the FrameLayout whose id is fl_my_container is the scan component we need to replace, that is to say we

The scan Fragment we defined will be replaced by the FrameLayout with the id fl_my_container.

The button above is an additional control we added, where you can add any control, various UI effects, etc.

  1. Create the my_camera.xml layout file, this is the interface for scanning the QR code

To customize the QR code scanning page, modify it in this layout, here I added a ToolBar and a Button button

Used to quit scanning.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_second"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/second_button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="20dp"
        android:text="取消二维码扫描" />
    <FrameLayout
        android:id="@+id/fl_my_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <SurfaceView
        android:id="@+id/preview_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <com.uuzuche.lib_zxing.view.ViewfinderView
        android:id="@+id/viewfinder_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:inner_corner_length="30dp"
        app:inner_corner_width="5dp"
        app:inner_height="200dp"
        app:inner_margintop="150dp"
        app:inner_scan_iscircle="false"
        app:inner_scan_speed="10"
        app:inner_width="200dp" />
</FrameLayout>

SecondActivity file (instead of CaptureActivity.java)

package com.it.zxing;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;

public class SecondActivity extends AppCompatActivity {
    
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment);

        CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
    
    
            @Override
            public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
    
    
                Intent resultIntent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
                bundle.putString(CodeUtils.RESULT_STRING, result);
                resultIntent.putExtras(bundle);
                SecondActivity.this.setResult(RESULT_OK, resultIntent);
                SecondActivity.this.finish();
            }

            @Override
            public void onAnalyzeFailed() {
    
    
                Intent resultIntent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
                bundle.putString(CodeUtils.RESULT_STRING, "");
                resultIntent.putExtras(bundle);
                SecondActivity.this.setResult(RESULT_OK, resultIntent);
                SecondActivity.this.finish();
            }
        };

        //在Activity中执行Fragment的初始化操作
        //执行扫面Fragment的初始化操作
        CaptureFragment captureFragment = new CaptureFragment();
        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.my_camera);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();
        //进行展示
    }
}

Generate a QR code image (without logo)

button1.setOnClickListener(new View.OnClickListener() {
    
    
    @Override
    public void onClick(View v) {
    
    

        String textContent = editText.getText().toString();
        if (TextUtils.isEmpty(textContent)) {
    
    
            Toast.makeText(ThreeActivity.this, "您的输入为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        editText.setText("");
        mBitmap = CodeUtils.createImage(textContent, 400, 400, null);
        imageView.setImageBitmap(mBitmap);
    }
});

Guess you like

Origin blog.csdn.net/weixin_45927121/article/details/120686174