1.在buid.gradle(Module:app)中添加引用库
dependencies {
//引入ZXing库用于生成二维码(QRCode)
implementation 'com.google.zxing:core:3.3.0
}
其实ZXing库的体积比较庞大,但是由于个人水平有限,只能引用库进行使用,ZXing库是Google的开源库,这个开源库还是比较出名
2.建立QRCodeUtil工具类
由于代码的体积并不庞大,我就不分块讲解,直接在代码中解说,不懂单例模式的可以去我的一篇叫《Android 之 串口通信》的博客里面看,哪里有比较详细的介绍
public class QRCodeUtil {
//单例模式:懒汉模式
private static QRCodeUtil INSTANCE = null;
private QRCodeUtil(){
}
public static QRCodeUtil getInstance(){
if (INSTANCE == null){
INSTANCE = new QRCodeUtil();
}
return INSTANCE;
}
/**
*String transactionString //要生成二维码的字符串
*int QRCode_SIZE //二维码的大小[生成二维码是一个正方形的二维码,长宽同一]
*/
public Bitmap encodeTransactionString(String transactionString,int QRCode_SIZE){
boolean transactionString_Status = transactionString.isEmpty();
if(!transactionString_Status){
try {
Hashtable<EncodeHintType,String> hints = new Hashtable<>();
hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
BitMatrix bitMatrix = new QRCodeWriter().encode(transactionString, BarcodeFormat.QR_CODE,QRCode_SIZE,QRCode_SIZE,hints);
int[] pixels = new int[QRCode_SIZE * QRCode_SIZE];
for (int y=0;y<QRCode_SIZE;y++){
for (int x=0;x<QRCode_SIZE;x++){
if (bitMatrix.get(x,y)){
pixels[y*QRCode_SIZE+x] = 0xff000000;
}else {
pixels[y*QRCode_SIZE+x] = 0xffffffff;
}
}
}
Bitmap bitmap = Bitmap.createBitmap(QRCode_SIZE,QRCode_SIZE, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels,0,QRCode_SIZE,0,0,QRCode_SIZE,QRCode_SIZE);
return bitmap;
}catch (WriterException e){
e.printStackTrace();
return null;
}
}else {
return null;
}
}
}