Zxing二维码生成和扫描
step1: D:\workspace\ZxingDemo\app\build.gradle
implementation 'com.journeyapps:zxing-android-embedded:4.2.0'
implementation 'com.google.code.gson:gson:2.8.0'
step2: D:\workspace\ZxingDemo\app\src\main\AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
step3: D:\workspace\ZxingDemo\app\src\main\res\layout\activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt_scan"
android:text="Scan"
android:layout_centerInParent="true"/>
</RelativeLayout>
step4: D:\workspace\ZxingDemo\app\src\main\res\layout\activity_qr_code.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/qrcode_root"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="@+id/ad_tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
<ImageView
android:id="@+id/ad_iv_qrcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/ad_tv_title"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</RelativeLayout>
step5: D:\workspace\ZxingDemo\app\src\main\java\com\example\zxingdemo\ScanBean.java
package com.example.zxingdemo;
public class ScanBean {
/**
* age : 26
* email : 249175190@qq.com
* isDeveloper : true
* name : Normal
*/
private int age;
private String email;
private boolean isDeveloper;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isIsDeveloper() {
return isDeveloper;
}
public void setIsDeveloper(boolean isDeveloper) {
this.isDeveloper = isDeveloper;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
step6: D:\workspace\ZxingDemo\app\src\main\java\com\example\zxingdemo\CommonUtils.java
package com.example.zxingdemo;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import com.google.gson.Gson;
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;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class CommonUtils {
public static int[] getScreenResolutions(Activity activity) {
int[] resolutions = new int[2];
DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
resolutions[0] = dm.widthPixels;
resolutions[1] = dm.heightPixels;
return resolutions;
}
public static int[] getGoneViewSize(View view) {
int size[] = new int[2];
int width = View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED);
int height = View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED);
view.measure(width, height);
size[0] = view.getMeasuredWidth();
size[1] = view.getMeasuredHeight();
return size;
}
public static Gson getGson() {
return new Gson();
}
// public static OkHttpClient getOkHttpClient() {
// return new OkHttpClient.Builder()
// .readTimeout(8000, TimeUnit.MILLISECONDS)
// .writeTimeout(8000, TimeUnit.MILLISECONDS)
// .sslSocketFactory(SSLCertificate.SSLSocketFactorygetSSLSocketFactory())
// .hostnameVerifier(new HostnameVerifier() {
// @Override
// public boolean verify(String s, SSLSession sslSession) {
// return true;
// }
// })
// .build();
// }
public static Bitmap createQRCodeBitmap(String content, int width, int height) {
return createQRCodeBitmap(content, width, height,
"UTF-8", "H", "2", Color.BLACK, Color.WHITE);
}
public static Bitmap createQRCodeBitmap(String content, int width, int height,
String character_set, String error_correction_level,
String margin, int color_black, int color_white) {
if (TextUtils.isEmpty(content)) {
return null;
}
if (width < 0 || height < 0) {
return null;
}
try {
Hashtable<EncodeHintType, String> hints = new Hashtable<>();
if (!TextUtils.isEmpty(character_set)) {
hints.put(EncodeHintType.CHARACTER_SET, character_set);
}
if (!TextUtils.isEmpty(error_correction_level)) {
hints.put(EncodeHintType.ERROR_CORRECTION, error_correction_level);
}
if (!TextUtils.isEmpty(margin)) {
hints.put(EncodeHintType.MARGIN, margin);
}
BitMatrix bitMatrix = new QRCodeWriter().encode(content, 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] = color_black;//黑色色块像素设置
} else {
pixels[y * width + x] = color_white;// 白色色块像素设置
}
}
}
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;
}
}
}
step7: D:\workspace\ZxingDemo\app\src\main\java\com\example\zxingdemo\MainActivity.java
package com.example.zxingdemo;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
public class MainActivity extends AppCompatActivity {
//Initialize variable
Button btScan;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Assign variable
btScan = findViewById(R.id.bt_scan);
btScan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Initialize intent integrator
IntentIntegrator intentIntegrator = new IntentIntegrator
(
MainActivity.this
);
//Set prompt text
intentIntegrator.setPrompt("For flash use volume up key");
//Set beep
intentIntegrator.setBeepEnabled(true);
//Locked orientation
intentIntegrator.setOrientationLocked(true);
//Set capture activity
//intentIntegrator.setCaptureActivity(Capture.class);
//Initiate scan
intentIntegrator.initiateScan();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Initialize intent result
IntentResult intentResult = IntentIntegrator.parseActivityResult(
requestCode, resultCode, data
);
//gson 解析
/**
{
"age":26,
"email":"249175190@qq.com",
"isDeveloper":true,
"name":"Normal"
}
*/
Gson gson = new Gson();
ScanBean mScanBean = gson.fromJson(intentResult.getContents(), ScanBean.class);
int age = mScanBean.getAge();
String email = mScanBean.getEmail();
String name = mScanBean.getName();
boolean developer = mScanBean.isIsDeveloper();
Log.e("TAG", age + "\t" + email + "\t" + name + "\t" + developer);
//Check condition
if (intentResult.getContents() != null) {
//When result content is not null
//Initialize alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this
);
//Set title
builder.setTitle("Result");
//Set message
builder.setMessage(intentResult.getContents());
Log.e("TAG", "" + intentResult.getContents());
//Set positive button
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//Dismiss dialog
dialogInterface.dismiss();
}
});
//Show alert dialog
builder.show();
} else {
//When result content is null
//Display toast
Toast.makeText(getApplicationContext()
, "OOPS... You did not scan anything", Toast.LENGTH_SHORT).show();
}
}
}
step8: D:\workspace\ZxingDemo\app\src\main\java\com\example\zxingdemo\QrCodeActivity.java
package com.example.zxingdemo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
public class QrCodeActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qr_code);
ImageView ad_iv_qrcode = findViewById(R.id.ad_iv_qrcode);
Gson gson = new Gson();
ScanBean mScanBean = new ScanBean();
mScanBean.setName("赵信");
mScanBean.setAge(18);
mScanBean.setEmail("2494075190@qq.com");
mScanBean.setIsDeveloper(true);
String res = gson.toJson(mScanBean);
Bitmap qrcode = CommonUtils.createQRCodeBitmap(res, 960, 960);
ad_iv_qrcode.setImageBitmap(qrcode);
}
}
run 运行成功 注意有两个activity,main是扫描 qrcode是生成,运行的时候记得再清单文件切换
end
本文介绍了如何使用Zxing库在Android应用中实现二维码的生成和扫描功能,包括配置build.gradle,修改AndroidManifest.xml,设计布局文件以及编写关键Java类如MainActivity和QrCodeActivity。运行成功后,注意应用程序包含两个Activity,分别用于扫描和生成二维码。


被折叠的 条评论
为什么被折叠?



