安卓生成二维码demo

举个栗子。

  1. 需要用到zxing这个库。
    下载core-3.4.0.jar这个东西,修改Android.mk,将core-3.4.0.jar写到LOCAL_STATIC_JAVA_LIBRARIESLOCAL_PREBUILT_STATIC_JAVA_LIBRARIES,用于编译。

  2. 添加二维码工具类QRCodeUtils.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    package com.test.menu.util;

    import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Matrix;
    import android.support.annotation.Nullable;
    import android.text.TextUtils;

    import com.google.zxing.BarcodeFormat;
    import com.google.zxing.EncodeHintType;
    import com.google.zxing.WriterException;
    import com.google.zxing.common.BitMatrix;
    import com.google.zxing.qrcode.QRCodeWriter;

    import java.util.Hashtable;

    public class QRCodeUtils {

    private static final String TAG = "QRCodeUtil";

    public static Bitmap createQRImage(String url, final int width, final int height) {
    try {

    if (url == null || "".equals(url) || url.length() < 1) {
    return null;
    }
    Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    hints.put(EncodeHintType.MARGIN, "1");

    BitMatrix bitMatrix = new QRCodeWriter().encode(url,
    BarcodeFormat.QR_CODE, width, height, hints);
    int[] pixels = new int[width * height];


    for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
    if (bitMatrix.get(x, y)) {
    pixels[y * width + x] = 0xff000000;
    } else {
    pixels[y * width + x] = 0xffffffff;
    }
    }
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height,
    Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return bitmap;
    } catch (WriterException e) {
    e.printStackTrace();
    }
    return null;
    }
    }

  3. 制作菜单

  4. 把二维码图片设置到菜单
    二维码图片的内容是往createQRImage传入的字符串。

    1
    2
    String allString = "helloworld";
    mImageView.setImageBitmap(QRCodeUtils.createQRImage(allString, 128, 128));