feat: 扫码迁移到 ZXingLite 并支持相册识别

This commit is contained in:
fengjingqi
2026-11-11 14:23:21 +08:00
parent 1fd760e80a
commit 5e8ea12f69
17 changed files with 544 additions and 39 deletions

View File

@@ -7,6 +7,13 @@
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.CAMERA" />
<!-- 扫码使用相机,但相机不是必需硬件,保证无相机设备也能安装并手动输入编码 -->
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-feature
android:name="android.hardware.camera.any"
android:required="false" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission
android:name="android.permission.READ_MEDIA_IMAGES"/>
@@ -151,6 +158,11 @@
android:name=".product.ProductInboundActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize" />
<activity
android:name=".product.ProductScanActivity"
android:exported="false"
android:screenOrientation="portrait"
android:theme="@style/ProductScanTheme" />
<activity
android:name=".login.LoginActivity"
android:theme="@style/AppTheme.FullScreen"

View File

@@ -32,7 +32,7 @@ import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;
import com.bumptech.glide.Glide;
import com.google.zxing.client.android.utils.ZXingUtils;
import com.king.zxing.util.CodeUtils;
import com.ckkj.griddlebiz.AppConfig;
import com.ckkj.griddlebiz.R;
import com.ckkj.griddlebiz.guide.GuideActivity;
@@ -181,8 +181,10 @@ public class ShareQrcodeDialog {
*/
private void authUrlToQrcode(String data) {
try {
Bitmap qrImage = ZXingUtils.createQRCodeImage(AppConfig.USER_SHARE_URL + data);
imgQrcode.setImageBitmap(qrImage);
Bitmap qrImage = CodeUtils.createQRCode(AppConfig.USER_SHARE_URL + data, 600);
if (qrImage != null) {
imgQrcode.setImageBitmap(qrImage);
}
} catch (Exception e) {
throw new RuntimeException(e);
}

View File

@@ -3,6 +3,7 @@ package com.ckkj.griddlebiz.product;
import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
@@ -13,10 +14,11 @@ import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import com.google.zxing.client.android.MNScanManager;
import com.google.zxing.client.android.other.MNScanCallback;
import com.king.camera.scan.CameraScan;
import com.ckkj.griddlebiz.R;
import com.ckkj.griddlebiz.base.BaseActivity;
import com.ckkj.griddlebiz.databinding.DialogProductInboundManualLayoutBinding;
@@ -39,6 +41,21 @@ public class ProductInboundActivity extends BaseActivity<ProductInboundLayoutBin
private static final int REQUEST_CAMERA_SCAN = 0x140;
/** 扫码页返回结果;扫码和相册识别都通过 {@link CameraScan#SCAN_RESULT} 回传。 */
private final ActivityResultLauncher<Intent> mScanLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() != RESULT_OK) {
return;
}
Intent data = result.getData();
String code = data == null ? null : data.getStringExtra(CameraScan.SCAN_RESULT);
if (TextUtils.isEmpty(code)) {
ToastUtil.showShort(mContext, R.string.product_scan_empty);
} else {
mPresenter.submitCode(code);
}
});
private Dialog mManualCodeDialog;
private DialogProductInboundManualLayoutBinding mManualBinding;
@@ -66,6 +83,11 @@ public class ProductInboundActivity extends BaseActivity<ProductInboundLayoutBin
}
private void requestScanPermission() {
// 相机在清单中声明为非必需硬件,无相机设备仍可安装和使用手动输入。
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
ToastUtil.showShort(mContext, R.string.product_camera_unavailable);
return;
}
if (hasRecordPermission(Manifest.permission.CAMERA)) {
startScan();
return;
@@ -78,32 +100,7 @@ public class ProductInboundActivity extends BaseActivity<ProductInboundLayoutBin
}
private void startScan() {
MNScanManager.startScan(this, new MNScanCallback() {
@Override
public void onActivityResult(int resultCode, Intent data) {
switch (resultCode) {
case MNScanManager.RESULT_SUCCESS:
String success = data == null ? ""
: data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS);
if (TextUtils.isEmpty(success)) {
ToastUtil.showShort(mContext, R.string.product_scan_empty);
} else {
mPresenter.submitCode(success);
}
break;
case MNScanManager.RESULT_FAIL:
String error = data == null ? ""
: data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_ERROR);
ToastUtil.showShort(mContext,
getString(R.string.product_scan_failed,
TextUtils.isEmpty(error) ? "" : error));
break;
case MNScanManager.RESULT_CANCLE:
default:
break;
}
}
});
mScanLauncher.launch(new Intent(this, ProductScanActivity.class));
}
@Override

View File

@@ -0,0 +1,300 @@
package com.ckkj.griddlebiz.product;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import com.ckkj.griddlebiz.R;
import com.ckkj.griddlebiz.utils.show.ToastUtil;
import com.google.zxing.Result;
import com.king.camera.scan.AnalyzeResult;
import com.king.camera.scan.CameraScan;
import com.king.camera.scan.analyze.Analyzer;
import com.king.zxing.BarcodeCameraScanActivity;
import com.king.zxing.DecodeConfig;
import com.king.zxing.analyze.MultiFormatAnalyzer;
import com.king.zxing.util.CodeUtils;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 商品入库扫码页:相机实时扫码,也可从相册选择图片识别。
* <p>
* 相册使用 AndroidX Photo Picker,不需要读取存储权限;返回结果统一放在
* {@link CameraScan#SCAN_RESULT} 中。
*/
public class ProductScanActivity extends BarcodeCameraScanActivity {
private final Handler mMainHandler = new Handler(Looper.getMainLooper());
private final ExecutorService mDecodeExecutor = Executors.newSingleThreadExecutor();
private TextView mTvGallery;
private boolean mDecoding;
private boolean mResultReturned;
private final ActivityResultLauncher<PickVisualMediaRequest> mPickImageLauncher =
registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), this::onImagePicked);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
applyEdgeToEdge();
findViewById(R.id.ivScanBack).setOnClickListener(v -> finish());
mTvGallery = findViewById(R.id.tvGallery);
mTvGallery.setOnClickListener(v -> openPhotoPicker());
}
private void applyEdgeToEdge() {
Window window = getWindow();
WindowCompat.setDecorFitsSystemWindows(window, false);
window.setStatusBarColor(Color.TRANSPARENT);
window.setNavigationBarColor(Color.BLACK);
WindowCompat.getInsetsController(window, window.getDecorView())
.setAppearanceLightStatusBars(false);
View root = findViewById(R.id.scanRoot);
View topBar = findViewById(R.id.scanTopBar);
View bottomBar = findViewById(R.id.scanBottomBar);
final int topPadding = topBar.getPaddingTop();
final int bottomPadding = bottomBar.getPaddingBottom();
ViewCompat.setOnApplyWindowInsetsListener(root, (v, insets) -> {
Insets bars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
topBar.setPadding(topBar.getPaddingLeft(), topPadding + bars.top,
topBar.getPaddingRight(), topBar.getPaddingBottom());
bottomBar.setPadding(bottomBar.getPaddingLeft(), bottomBar.getPaddingTop(),
bottomBar.getPaddingRight(), bottomPadding + bars.bottom);
return insets;
});
ViewCompat.requestApplyInsets(root);
}
@Override
public int getLayoutId() {
return R.layout.product_scan_layout;
}
@Override
public Analyzer<Result> createAnalyzer() {
// 默认支持 QR_CODE / UPC_A / EAN_13 / CODE_128,覆盖设备外箱常见条码。
return new MultiFormatAnalyzer(new DecodeConfig().setFullAreaScan(true));
}
@Override
public void initCameraScan(@NonNull CameraScan<Result> cameraScan) {
super.initCameraScan(cameraScan);
cameraScan.setPlayBeep(true)
.setVibrate(true)
.setAnalyzeImage(true);
}
@Override
public void onScanResultCallback(@NonNull AnalyzeResult<Result> result) {
Result value = result.getResult();
if (value == null || TextUtils.isEmpty(value.getText())) {
return;
}
CameraScan<Result> cameraScan = getCameraScan();
if (cameraScan != null) {
cameraScan.setAnalyzeImage(false);
}
returnResult(value.getText());
}
private void openPhotoPicker() {
if (mDecoding) {
return;
}
CameraScan<Result> cameraScan = getCameraScan();
if (cameraScan != null) {
// 系统相册打开期间暂停识别,避免相机结果提前返回。
cameraScan.setAnalyzeImage(false);
}
mPickImageLauncher.launch(new PickVisualMediaRequest.Builder()
.setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
.build());
}
private void onImagePicked(@Nullable Uri uri) {
if (uri == null) {
// 用户取消选择,恢复相机识别。
resumeScan();
return;
}
setDecoding(true);
mDecodeExecutor.execute(() -> {
String text = decodeImage(uri);
mMainHandler.post(() -> {
setDecoding(false);
if (TextUtils.isEmpty(text)) {
ToastUtil.showShort(this, R.string.product_scan_gallery_failed);
resumeScan();
} else {
returnResult(text);
}
});
});
}
@Nullable
private String decodeImage(Uri uri) {
Bitmap bitmap = null;
try {
bitmap = loadSampledBitmap(uri);
if (bitmap == null) {
return null;
}
bitmap = applyExifRotation(uri, bitmap);
String text = CodeUtils.parseCode(bitmap);
if (!TextUtils.isEmpty(text)) {
return text;
}
// 相册图片可能本身带旋转角度,逐个方向重试。
for (int degrees = 90; degrees < 360; degrees += 90) {
Bitmap rotated = rotate(bitmap, degrees);
if (rotated == null) {
continue;
}
text = CodeUtils.parseCode(rotated);
if (rotated != bitmap) {
rotated.recycle();
}
if (!TextUtils.isEmpty(text)) {
return text;
}
}
return null;
} catch (Exception e) {
return null;
} finally {
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle();
}
}
}
@Nullable
private Bitmap loadSampledBitmap(Uri uri) throws Exception {
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
try (InputStream in = getContentResolver().openInputStream(uri)) {
if (in == null) {
return null;
}
BitmapFactory.decodeStream(in, null, bounds);
}
int sampleSize = 1;
int maxSize = Math.max(bounds.outWidth, bounds.outHeight);
if (maxSize <= 0) {
return null;
}
while (maxSize / sampleSize > 1600) {
sampleSize *= 2;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sampleSize;
try (InputStream in = getContentResolver().openInputStream(uri)) {
if (in == null) {
return null;
}
return BitmapFactory.decodeStream(in, null, options);
}
}
private Bitmap applyExifRotation(Uri uri, Bitmap bitmap) {
try (InputStream in = getContentResolver().openInputStream(uri)) {
if (in == null) {
return bitmap;
}
ExifInterface exif = new ExifInterface(in);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
int degrees;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degrees = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degrees = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degrees = 270;
break;
default:
return bitmap;
}
Bitmap rotated = rotate(bitmap, degrees);
return rotated == null ? bitmap : rotated;
} catch (Exception e) {
return bitmap;
}
}
@Nullable
private Bitmap rotate(Bitmap bitmap, int degrees) {
if (degrees % 360 == 0) {
return bitmap;
}
try {
Matrix matrix = new Matrix();
matrix.postRotate(degrees);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
matrix, true);
} catch (Exception e) {
return null;
}
}
private void setDecoding(boolean decoding) {
mDecoding = decoding;
mTvGallery.setEnabled(!decoding);
mTvGallery.setText(decoding ? R.string.product_scan_decoding : R.string.product_scan_gallery);
}
private void resumeScan() {
CameraScan<Result> cameraScan = getCameraScan();
if (cameraScan != null) {
cameraScan.setAnalyzeImage(true);
}
}
private void returnResult(String text) {
if (mResultReturned) {
return;
}
mResultReturned = true;
Intent data = new Intent();
data.putExtra(CameraScan.SCAN_RESULT, text);
setResult(RESULT_OK, data);
finish();
}
@Override
protected void onDestroy() {
mDecodeExecutor.shutdownNow();
mMainHandler.removeCallbacksAndMessages(null);
super.onDestroy();
}
}

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z" />
</vector>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#66FFFFFF"
android:pathData="M7,2v11h3v9l7,-12h-4l4,-8z" />
</vector>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M7,2v11h3v9l7,-12h-4l4,-8z" />
</vector>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M21,19V5c0,-1.1 -0.9,-2 -2,-2H5c-1.1,0 -2,0.9 -2,2v14c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2zM8.5,13.5l2.5,3.01L14.5,12l4.5,6H5l3.5,-4.5z" />
</vector>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="270"
android:endColor="#B3000000"
android:startColor="#00000000" />
</shape>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_product_scan_flash_on" android:state_selected="true" />
<item android:drawable="@drawable/ic_product_scan_flash_off" />
</selector>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#33FFFFFF" />
<corners android:radius="22dp" />
</shape>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="270"
android:endColor="#00000000"
android:startColor="#99000000" />
</shape>

View File

@@ -0,0 +1,107 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scanRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black">
<androidx.camera.view.PreviewView
android:id="@+id/previewView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:importantForAccessibility="no" />
<com.king.view.viewfinderview.ViewfinderView
android:id="@+id/viewfinderView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<View
android:layout_width="match_parent"
android:layout_height="140dp"
android:background="@drawable/product_scan_top_scrim" />
<View
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="bottom"
android:background="@drawable/product_scan_bottom_scrim" />
<LinearLayout
android:id="@+id/scanTopBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingStart="8dp"
android:paddingTop="6dp"
android:paddingEnd="8dp"
android:paddingBottom="6dp">
<ImageView
android:id="@+id/ivScanBack"
android:layout_width="44dp"
android:layout_height="44dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/product_inbound_back"
android:padding="10dp"
android:src="@drawable/ic_product_scan_back" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_weight="1"
android:text="@string/product_scan_title"
android:textColor="@android:color/white"
android:textSize="17sp"
android:textStyle="bold" />
<ImageView
android:id="@+id/ivFlashlight"
android:layout_width="44dp"
android:layout_height="44dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/product_scan_flashlight"
android:padding="10dp"
android:src="@drawable/product_scan_flash_selector" />
</LinearLayout>
<LinearLayout
android:id="@+id/scanBottomBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingStart="24dp"
android:paddingTop="16dp"
android:paddingEnd="24dp"
android:paddingBottom="32dp">
<TextView
android:id="@+id/tvGallery"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:background="@drawable/product_scan_gallery_bg"
android:drawableStart="@drawable/ic_product_scan_gallery"
android:drawablePadding="8dp"
android:gravity="center"
android:minWidth="164dp"
android:paddingStart="20dp"
android:paddingEnd="20dp"
android:text="@string/product_scan_gallery"
android:textColor="@android:color/white"
android:textSize="15sp" />
<TextView
android:id="@+id/tvScanTip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:text="@string/product_scan_tip"
android:textColor="#B3FFFFFF"
android:textSize="13sp" />
</LinearLayout>
</FrameLayout>

View File

@@ -11,10 +11,15 @@
<string name="product_manual_code_close">Close</string>
<string name="product_manual_code_empty">Please enter the QR code number</string>
<string name="product_manual_code_submitted">Code submitted: %1$s</string>
<string name="product_scan_unavailable">Scanner is not connected yet</string>
<string name="product_camera_permission_title">Camera Permission</string>
<string name="product_camera_permission_content">Product Inbound uses the camera to scan the device outer box barcode. If you decline, you can still enter the SN code manually.</string>
<string name="product_camera_permission_denied">Camera permission was not granted. You can enter the SN code manually.</string>
<string name="product_scan_failed">Scan failed: %1$s</string>
<string name="product_camera_unavailable">No camera is available on this device. Please enter the SN code manually.</string>
<string name="product_scan_empty">No barcode was detected. Please try again.</string>
<string name="product_scan_title">Scan to Inbound</string>
<string name="product_scan_gallery">Choose from Gallery</string>
<string name="product_scan_decoding">Decoding image…</string>
<string name="product_scan_tip">Align the barcode within the frame to scan</string>
<string name="product_scan_gallery_failed">No barcode was found in the image.</string>
<string name="product_scan_flashlight">Flashlight</string>
</resources>

View File

@@ -11,10 +11,15 @@
<string name="product_manual_code_close">关闭</string>
<string name="product_manual_code_empty">请输入二维码编号</string>
<string name="product_manual_code_submitted">已提交编码:%1$s</string>
<string name="product_scan_unavailable">扫码能力待接入</string>
<string name="product_camera_permission_title">相机权限使用说明</string>
<string name="product_camera_permission_content">商品入库需要使用相机扫描设备外箱条码。拒绝或取消授权不影响手动输入 SN 码。</string>
<string name="product_camera_permission_denied">未获得相机权限,可手动输入 SN 码</string>
<string name="product_scan_failed">扫码失败:%1$s</string>
<string name="product_camera_unavailable">当前设备没有可用相机,请手动输入 SN 码</string>
<string name="product_scan_empty">未识别到条码,请重试</string>
<string name="product_scan_title">扫码入库</string>
<string name="product_scan_gallery">从相册选择</string>
<string name="product_scan_decoding">正在识别图片…</string>
<string name="product_scan_tip">将条码放入框内,即可自动识别</string>
<string name="product_scan_gallery_failed">未从图片中识别到条码</string>
<string name="product_scan_flashlight">手电筒</string>
</resources>

View File

@@ -10,4 +10,14 @@
<item name="android:backgroundDimAmount">0.6</item>
<item name="android:windowCloseOnTouchOutside">true</item>
</style>
<!-- 扫码页:相机预览铺满全屏,状态栏透明。 -->
<style name="ProductScanTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@android:color/black</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:navigationBarColor">@android:color/black</item>
<item name="android:windowLightStatusBar">false</item>
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
</style>
</resources>