用 ZXing 库自定义二维码/条码扫描器很不错
https://github.com/journeyapps/zxing-android-embedded
您可以在那里查看示例应用项目并自行自定义(添加按钮、设置闪光灯开/关)。
还有另一个库,但它没有使用 ZXing。
https://github.com/googlesamples/android-vision
它已被弃用,现在是 ML Kit 的一部分,但仍然可以使用。
希望对你有所帮助。谢谢。
[更新]
请将此库导入您的项目。 (您可以从下面的链接中查看如何导入它。)
https://github.com/journeyapps/zxing-android-embedded#adding-aar-dependency-with-gradle
导入后,您可以更新条码扫描器活动的 layout.xml。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/topLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true">
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:id="@+id/barcode_scanner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" />
<Button
android:id="@+id/btn_flash"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:text="Flash"/>
</FrameLayout>
com.journeyapps.barcodescanner.DecoratedBarcodeView 是 BarcodeScanner 视图。而Button只是用来开/关闪光灯。
这是 BarcodeScanner 的活动。
public class ScanQRActivity extends BaseActivity {
private static final String TAG = "ScanQRActivity";
private DecoratedBarcodeView barcodeView;
private boolean isFlashOn;
/**
* Initializes the UI and creates the detector pipeline.
*/
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_scan_qr);
isFlashOn = false;
barcodeView = findViewById(R.id.barcode_scanner);
Collection<BarcodeFormat> formats = Arrays.asList(BarcodeFormat.CODE_39); // Set barcode type
barcodeView.getBarcodeView().setDecoderFactory(new DefaultDecoderFactory(formats));
barcodeView.initializeFromIntent(getIntent());
barcodeView.decodeContinuous(callback);
Button btnFlash = findViewById(R.id.btn_flash);
if (!hasFlash()) {
btnFlash.setVisibility(View.GONE);
}
btnFlash.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switchFlashlight();
}
});
}
private BarcodeCallback callback = new BarcodeCallback() {
@Override
public void barcodeResult(BarcodeResult result) {
Log.e(TAG, result.getText()); // QR/Barcode result
}
@Override
public void possibleResultPoints(List<ResultPoint> resultPoints) {
}
};
/**
* Check if the device's camera has a Flashlight.
*
* @return true if there is Flashlight, otherwise false.
*/
private boolean hasFlash() {
return getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
public void switchFlashlight() {
if (isFlashOn) {
isFlashOn = false;
barcodeView.setTorchOff();
} else {
isFlashOn = true;
barcodeView.setTorchOn();
}
}
@Override
protected void onResume() {
super.onResume();
barcodeView.resume();
}
@Override
protected void onPause() {
super.onPause();
barcodeView.pause();
}
}
扫描二维码/条码时,可以从 BarcodeCallback.barcodeResult 函数中获取结果。
希望对您有所帮助。
如果您有任何问题,请在此处发表评论。