众所周知,二维码的作用和价值在于提高了支付、营销、信息获取、身份认证和物流追踪等方面的效率和便利性,为用户和企业带来了更多的便利和机会,是一种快速、便捷的信息传递工具。
接下来我们使用java语言编写的android程序将会实现一个批量生成二维码的功能!
首先到GitHub库中将zing包下载并添加到你的项目中:https://github.com/zxing
为确保在我项目中所实现的功能和大家目标实现的功能一致,这里我先放上它的一个效果图:
它的主界面由上至下的构成是:4个editText编辑框,再左右2个editText编辑框,1个TextView文本框,1个生成按钮,1个查看相册的按钮。
布局代码如下:
<?xml version="1.0" encoding="utf-8"?>
<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"
android:background="#8BC34A">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="200dp">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:gravity="center"
android:textColor="@color/black"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="第一行:"/>
<EditText
android:id="@+id/companyName"
android:textColor="@color/black"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:gravity="center"
android:textColor="@color/black"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="批号1:"/>
<EditText
android:id="@+id/lot01"
android:textColor="@color/black"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:gravity="center"
android:textColor="@color/black"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="批号2:"/>
<EditText
android:id="@+id/lot02"
android:textColor="@color/black"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:gravity="center"
android:textColor="@color/black"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="批号3:"/>
<EditText
android:id="@+id/lot03"
android:textColor="@color/black"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_marginTop="35dp"
android:background="#2196F3"
android:gravity="center"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="100dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="180dp"
android:layout_height="match_parent">
<TextView
android:gravity="center"
android:text="开始批号"
android:layout_width="match_parent"
android:layout_height="20dp"/>
<EditText
android:inputType="number"
android:textColor="@color/black"
android:id="@+id/start"
android:background="#DA00BCD4"
android:layout_width="180dp"
android:layout_height="75dp"/>
</LinearLayout>
<View
android:layout_width="10dp"
android:layout_height="match_parent"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="180dp"
android:layout_height="match_parent">
<TextView
android:gravity="center"
android:text="结束批号"
android:layout_width="match_parent"
android:layout_height="20dp"/>
<EditText
android:inputType="number"
android:textColor="@color/black"
android:id="@+id/end"
android:background="#DA00BCD4"
android:layout_width="180dp"
android:layout_height="75dp"/>
</LinearLayout>
</LinearLayout>
<TextView
android:textColor="@color/black"
android:layout_marginTop="15dp"
android:id="@+id/fullNumber"
android:background="#4CAF50"
android:layout_width="match_parent"
android:layout_height="150dp"/>
<LinearLayout
android:layout_marginTop="15dp"
android:gravity="center"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="100dp">
<Button
android:background="#5200BCD4"
android:id="@+id/qrCodes"
android:layout_width="180dp"
android:layout_height="70dp"
android:text="生成QR"
android:textColor="@color/white"
/>
</LinearLayout>
<Button
android:text="查看相册"
android:background="#5200BCD4"
android:layout_marginTop="45dp"
android:id="@+id/goToPhoto"
android:layout_width="match_parent"
android:layout_height="60dp"/>
<TextView
android:id="@+id/progressText"
android:layout_marginLeft="190dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:textSize="18sp" />
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
android:progress="0"
style="@android:style/Widget.ProgressBar.Horizontal"
/>
</LinearLayout>
由于要批量生成二维码,我们可以先定义一个QRCodeGenerator类,当每次点击按钮的时候,我们就调用这个方法。代码如下:
package com.application.msgdata;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.provider.MediaStore;
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 com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
public class QRCodeGenerator {
private static int i;
public void setNum(int i) {
this.i=i;
}
public static void generateQRCode(Context context, String text) {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.MARGIN, 1);
int width = 500;
int height = 500;
QRCodeWriter writer = new QRCodeWriter();
try {
BitMatrix bitMatrix = writer.encode(text, BarcodeFormat.QR_CODE, width, height,hints);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
bitmap.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
}
}
saveImageToGallery(context, bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
private static void saveImageToGallery(Context context, Bitmap bitmap) {
// 保存图片到系统相册
String fileName = i+1+ ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try {
OutputStream outputStream = context.getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
最后,我们回到主界面MainActivity中,它的一个执行过程是:我们在1~4编辑框中输入名称等数据,再在蓝底编辑框中,左边输入起始批号,右边输入结尾批号,每个编辑框我都加入了一个监听,当我们输入了相关内容时,TextView框的内容也会随之而变动,只有当所有的编辑框都补全了时,生成QR按钮才有效,接下来,我们就可以点击相册,查看二维码是否创建成功啦!
MainActivity.java代码如下:
package com.application.msgdata;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private ProgressBar progressBar;
private TextView progressText;
private Handler handler=new Handler();
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
private final static int PICK_IMAGE_REQUEST=1;
private EditText compName,lot01,lot02,lot03,beginLot,endLot;
private String compNameStr,lot01Str,lot02Str,lot03Str,beginStr,endStr;
private TextView allNumbers;
private Button qr;
private Button goPhoto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressText = findViewById(R.id.progressText);
mSharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
compName=findViewById(R.id.companyName);
compName.setSingleLine(true);
compName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
compNameStr=s.toString();
setAllNumbersText();
}
@Override
public void afterTextChanged(Editable editable) {
}
});
lot01=findViewById(R.id.lot01);
lot01.setSingleLine(true);
lot01.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
lot01Str=s.toString();
setAllNumbersText();
}
@Override
public void afterTextChanged(Editable editable) {
}
});
lot02=findViewById(R.id.lot02);
lot02.setSingleLine(true);
lot02.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
lot02Str=s.toString();
setAllNumbersText();
}
@Override
public void afterTextChanged(Editable editable) {
}
});
lot03=findViewById(R.id.lot03);
lot03.setSingleLine(true);
lot03.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
lot03Str=s.toString();
setAllNumbersText();
}
@Override
public void afterTextChanged(Editable editable) {
}
});
beginLot=findViewById(R.id.start);
beginLot.setSingleLine(true);
beginLot.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
beginStr=s.toString();
setAllNumbersText();
}
@Override
public void afterTextChanged(Editable editable) {
}
});
endLot=findViewById(R.id.end);
endLot.setSingleLine(true);
endLot.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
endStr=s.toString();
setAllNumbersText();
}
@Override
public void afterTextChanged(Editable editable) {
}
});
allNumbers=findViewById(R.id.fullNumber);
progressBar=findViewById(R.id.progress_bar);
qr=findViewById(R.id.qrCodes);
qr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//检查是否输入完成
if (!(compNameStr.isEmpty()) && !(lot01Str.isEmpty()) && !(lot02Str.isEmpty()) && !(lot03Str.isEmpty()) && !(beginStr.isEmpty()) && !(endStr.isEmpty())) {
progressBar.setVisibility(View.VISIBLE);
printImages();
}else {
Toast.makeText(MainActivity.this, "请将数据填写完整!", Toast.LENGTH_SHORT).show();
}
}
});
goPhoto=findViewById(R.id.goToPhoto);
goPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
// 启动系统相册
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
});
}
private void printImages() {
// 打印图片
int begin = Integer.valueOf(beginStr).intValue();
int end = Integer.valueOf(endStr).intValue();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = begin;i<= end;i++){
int temp = 0;
String tempStr;
temp = temp+begin;
tempStr = compNameStr+":\n"+lot01Str+"-"+ temp +":"+lot02Str+":"+lot03Str+":"+endStr;
QRCodeGenerator.generateQRCode(MainActivity.this,tempStr);
QRCodeGenerator generator=new QRCodeGenerator();
generator.setNum(i);
try {
Thread.sleep(500); // 模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
int progress = i;
handler.post(new Runnable() {
@Override
public void run() {
progressBar.setProgress(progress);
progressBar.setMax((end-begin+1));
progressText.setText(progress + "/"+(end-begin+1));
}
});
}
runOnUiThread(new Runnable() {
@Override
public void run() {
progressText.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, "你共有"+(end-begin+1)+"个二维码已保存到相册", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
@Override
protected void onPause() {
super.onPause();
compNameStr=compName.getText().toString();
mEditor.putString("company",compNameStr);
lot01Str=lot01.getText().toString();
mEditor.putString("lot1",lot01Str);
lot02Str=lot02.getText().toString();
mEditor.putString("lot2",lot02Str);
lot03Str=lot03.getText().toString();
mEditor.putString("lot3",lot03Str);
beginStr=beginLot.getText().toString();
mEditor.putString("begin",beginStr);
endStr=endLot.getText().toString();
mEditor.putString("end",endStr);
mEditor.apply();
}
@Override
protected void onResume() {
super.onResume();
String company=mSharedPreferences.getString("company","");
compName.setText(company);
String lot1=mSharedPreferences.getString("lot1","");
lot01.setText(lot1);
String lot2=mSharedPreferences.getString("lot2","");
lot02.setText(lot2);
String lot3=mSharedPreferences.getString("lot3","");
lot03.setText(lot3);
String begin=mSharedPreferences.getString("begin","");
beginLot.setText(begin);
String end=mSharedPreferences.getString("end","");
endLot.setText(end);
}
public void setAllNumbersText() {
allNumbers.setText( compNameStr+":\n"+lot01Str+"-"+ beginStr +":"+lot02Str+":"+lot03Str+":"+endStr);
}
}
你在编写代码的过程中,也许会遇到阻碍,别灰心,下面评论区,我们可以一起探讨,共同进步!
项目源码我把它上传到Gitee里了,大家需要的话可以自行下载:
二维码的生成