Android QR code fast integration

QR code

It can be quickly integrated through the open source framework. zxing is a powerful QR code scanning library launched by Google, which supports multiple platforms. We only need Android core code, so we can rely on the God to extract the core package.

QR code scanning example

1. Rely on zxing

Add in the corresponding module build.gradle

// Add these two lines
implementation 'com.google.zxing:core:3.2.1'      //zxing core dependency
implementation 'com.journeyapps:zxing-android-embedded:3.3.0'  //Generate QR code dependency

2. QR code generation

ZxingUtil

public class ZxingUtil {
    /**
    * Generate QR code bitmap
    */
    public static Bitmap createBitmap(String str) {
        Bitmap bitmap = null;
        BitMatrix result = null;
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            result = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 400, 400);
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            bitmap = barcodeEncoder.createBitmap(result);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException iae) {
            return null;
        }
        return bitmap;
    }
}

3. QR code scanning

  1. In order to develop and use the ButterKnife framework easily

Add in build.gradle of corresponding module

//Add these two lines
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

The following errors may occur

all com.android.support libraries must use the exact same version specification

This is because the version of the third-party library referenced is lower (or inconsistent) than that in app build.gradle

It's too troublesome to change the version of the three-party library, so you can configure it directly in build.gradle of the corresponding module, and force the recommended version

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '25.3.0' // The recommended version of my studio is 25.3.0
            }
        }
    }
}


  1. Define your own scanning interface

ScanActivity
import android.app.Activity;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.KeyEvent;

import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import butterknife.BindView;
import butterknife.ButterKnife;
public class ScanActivity extends Activity {

    @BindView(R.id.dbv)
    DecoratedBarcodeView mDBV;

    private CaptureManager captureManager;     //Capture Manager

    @Override
    protected void onPause() {
        super.onPause();
        captureManager.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        captureManager.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        captureManager.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        captureManager.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return mDBV.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        ButterKnife.bind(this);
        captureManager = new CaptureManager(this, mDBV);
        captureManager.initializeFromIntent(getIntent(), savedInstanceState);
        captureManager.decode();
    }
}

Scan interface layout

activity_scan

<RelativeLayout 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:context="com.example.zxingtest.activity.ScanActivity">

    <com.journeyapps.barcodescanner.DecoratedBarcodeView
        android:id="@+id/dbv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:zxing_framing_rect_height="200dp"
        app:zxing_framing_rect_width="200dp"
        app:zxing_preview_scaling_strategy="fitXY"
        app:zxing_use_texture_view="true"></com.journeyapps.barcodescanner.DecoratedBarcodeView>

</RelativeLayout>

4. onActivityResult receives QR code scanning results

public class MainActivity extends Activity {
    public static final String TAG = "wangyannan";
    @BindView(R.id.iv_qrcode)
    ImageView mImageView;
    @BindView(R.id.tv_string)
    TextView mTvString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_create, R.id.btn_scan})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.btn_create:
                Bitmap bitmap = ZxingUtil.createBitmap("https://www.baidu.com");
                mImageView.setImageBitmap(bitmap);
                break;
            case R.id.btn_scan:
                Log.i(TAG, "click: btnscan");
                new IntentIntegrator(this)
                        .setOrientationLocked(false)
                        .setCaptureActivity(ScanActivity.class) // Set the custom activity as ScanActivity
                        .initiateScan(); // Initialize scan
                break;
        }

    }
    // Accept QR code scanning results through onActivityResult
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (intentResult != null) {
            if (intentResult.getContents() == null) {
                Toast.makeText(this, "Content is empty", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Scan success", Toast.LENGTH_LONG).show();
                // ScanResult is the obtained string
                String ScanResult = intentResult.getContents();
                mTvString.setText(ScanResult);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

}

Success:)

Tags: Android ButterKnife Gradle Google

Posted on Tue, 31 Mar 2020 06:07:39 -0400 by pandaweb