一维码的扫描:Zxing4.3.0、华为ScanKit、MLKit
参考文档
Android 带回调的启动Activity 推荐使用registerForActivityResult
Android 集成zxing二维码扫描、自定义
Android之 Zxing二维码详解
zxing时反色的二维码
一、开源库的选择
主要有以下几种开源库可以选择,经过对比,Google的MLKit库,识别速度更快,更精准
ZXing
ZXing Android Embedded(ZXing Android端的嵌入)
ZXing
华为ScanKit
MLKit库
二、ZXing
1 添加依赖
注意,这里添加journeyapps的依赖就可以了,journeyapps内部依赖了com.google.zxing:core:3.4.1,会自动下载
implementation 'com.journeyapps:zxing-android-embedded:4.3.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
2 打开一维码扫描界面
private final ActivityResultLauncher<ScanOptions> barcodeLauncher = registerForActivityResult(new ScanContract(),
new ActivityResultCallback<ScanIntentResult>() {
@Override
public void onActivityResult(ScanIntentResult result) {
if (result.getContents() == null) {
Toast.makeText(UploadActivity.this, "扫码取消!", Toast.LENGTH_LONG).show();
} else {
if (etGps != null) {
etGps.setText(result.getContents());
}
Toast.makeText(UploadActivity.this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
}
});
private void scanQrcode() {
ScanOptions options = new ScanOptions();
options.setDesiredBarcodeFormats(ScanOptions.ONE_D_CODE_TYPES);//图形码的格式:商品码、一维码、二维码、数据矩阵、全部类型
options.setPrompt("请将条形码置于取景框内扫描");
options.setCameraId(0); //0 后置摄像头 1 前置摄像头
options.setBeepEnabled(true);//开启成功声音
options.setBarcodeImageEnabled(true);//是否保存图片,扫描成功会截取扫描框的图形保存到手机并在result中返回路径
//启动扫描二维码界面
barcodeLauncher.launch(options);
}
3 ZXing扫描二维码,横屏转竖屏
在AndroidManifest.xml中重新声明CaptureActivity,并将screenOrientation改为portrait,替换掉journeyapps中的声明
<activity android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:clearTaskOnLaunch="true"
android:screenOrientation="portrait"
android:stateNotNeeded="true"
android:theme="@style/zxing_CaptureTheme"
tools:replace="android:screenOrientation"
android:windowSoftInputMode="stateAlwaysHidden"/>
4 注意:ZXing4.3.0中以下这种写法已废弃
private void scanQrcode() {
IntentIntegrator integrator = new IntentIntegrator(this);
// 设置要扫描的条码类型,ONE_D_CODE_TYPES:一维码,QR_CODE_TYPES-二维码
integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
integrator.setPrompt("扫描条形码");
integrator.setCameraId(0); // 使用默认的相机
integrator.setBeepEnabled(true); // 扫到码后播放提示音
integrator.initiateScan();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Toast.makeText(this, "扫码取消!", Toast.LENGTH_LONG).show();
} else {
if (etGps != null) {
etGps.setText(result.getContents());
}
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}