Android zxing 二维码扫描和生成方法(简单版)

前言

二维码大家都见识过,这里就不废话了,直接来干货。

步骤

  • 导入依赖
    compile 'com.google.zxing:core:3.2.1'      //zxing核心依赖
    compile 'com.journeyapps:zxing-android-embedded:3.3.0'  //生成二维码依赖
  • 生成二维码
    这里封装一个ZxingUtils,主要功能就是生成二维码的Bitmap对象,调用工具类的方式就不多说了,就是一个点击事件生成就好
package com.example.zxingtest.utils;

import android.graphics.Bitmap;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeEncoder;

/**
 * Created by D'Russel on 2017/7/31.
 */

public class ZxingUtils {


   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;
    }

}
  • 实现扫描二维码功能

在布局文件activity_main.xml中添加一个按钮


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.zxingtest.activity.MainActivity">

    <TextView
        android:id="@+id/tv_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ImageView
        android:id="@+id/pic_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_test"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="生成二维码"/>

    <Button
        android:id="@+id/btn_test2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="扫描二维码"/>

LinearLayout>

在MainActivity中

package com.example.zxingtest.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zxingtest.R;
import com.example.zxingtest.utils.ZxingUtils;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by D'Russel on 2017/7/31.
 */


public class MainActivity extends AppCompatActivity{
    @BindView(R.id.tv_test)
    TextView tv_test;
    @BindView(R.id.pic_test)
    ImageView img_test;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }
     //生成二维码
    @OnClick(R.id.btn_test)
    public void onTest(View view){
        Bitmap bitmap = ZxingUtils.createBitmap("hahahaha");
        img_test.setImageBitmap(bitmap);


    }

    //扫描二维码
    @OnClick(R.id.btn_test2)
    public void onTest2(View view){
        new IntentIntegrator(this)
                .setOrientationLocked(false)
                .setCaptureActivity(ScanActivity.class) // 设置自定义的activity是ScanActivity
                .initiateScan(); // 初始化扫描
    }


    @Override
// 通过 onActivityResult的方法获取扫描回来的值
    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,"内容为空",Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this,"扫描成功",Toast.LENGTH_LONG).show();
                // ScanResult 为 获取到的字符串
                String ScanResult = intentResult.getContents();
                tv_test.setText(ScanResult);
            }
        } else {
            super.onActivityResult(requestCode,resultCode,data);
        }
    }

}

这里有一个作为扫描框的ScanActivity,先看布局文件activity_scan.xml,这里放置一个扫描框,二维码的扫描功能就是这个扫描框提供的


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.zxingtest.activity.ScanActivity">


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

RelativeLayout>

ScanActivity中

package com.example.zxingtest.activity;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.zxingtest.R;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by D'Russel on 2017/7/31.
 */


public class ScanActivity extends AppCompatActivity{


    @BindView(R.id.dbv) DecoratedBarcodeView mDBV;
    private CaptureManager captureManager;     //捕获管理器

    @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();
    }
}

这里解释一下 CaptureManager
CaptureManager中文名是捕获管理器,从名字上可以看出,这是扫描框中对捕获内容处理的管理器,那上面的代码就很好理解了,我们让它的生命周期同Activity的生命周期一样。

生成二维码:
Android zxing 二维码扫描和生成方法(简单版)_第1张图片
Android zxing 二维码扫描和生成方法(简单版)_第2张图片

扫描二维码:

Android zxing 二维码扫描和生成方法(简单版)_第3张图片

你可能感兴趣的:(android,android框架)