赞
踩
1.在你的build.gradle文件中添加Mobile Vision库的依赖:
- dependencies {
- implementation 'com.google.android.gms:play-services-vision:20.1.0'
- }
2.创建一个新的Activity来处理扫描过程。
- import android.Manifest;
- import android.content.pm.PackageManager;
- import android.os.Bundle;
- import androidx.core.app.ActivityCompat;
- import androidx.core.content.ContextCompat;
- import androidx.appcompat.app.AppCompatActivity;
- import com.google.android.gms.vision.barcode.BarcodeReader;
- import com.google.android.gms.vision.CameraSource;
- import com.google.android.gms.vision.barcode.Barcode;
- import android.util.SparseArray;
- import com.google.android.gms.vision.Detector;
- import android.view.SurfaceHolder;
- import android.view.SurfaceView;
-
- public class QRCodeScannerActivity extends AppCompatActivity {
-
- private SurfaceView cameraPreview;
- private CameraSource cameraSource;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_qrcode_scanner);
-
- cameraPreview = findViewById(R.id.camera_preview);
-
- BarcodeReader barcodeReader = new BarcodeReader.Builder(this).build();
- cameraSource = new CameraSource.Builder(this, barcodeReader)
- .setFacing(CameraSource.CAMERA_FACING_BACK)
- .setRequestedPreviewSize(1600, 1024)
- .setAutoFocusEnabled(true)
- .build();
- cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
- @Override
- public void surfaceCreated(SurfaceHolder holder) {
- if (ContextCompat.checkSelfPermission(QRCodeScannerActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
- try {
- cameraSource.start(cameraPreview.getHolder());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- @Override
- public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
- }
-
- @Override
- public void surfaceDestroyed(SurfaceHolder holder) {
- cameraSource.stop();
- }
- });
-
- barcodeReader.setProcessor(new Detector.Processor<Barcode>() {
- @Override
- public void release() {
- }
-
- @Override
- public void receiveDetections(Detector.Detections<Barcode> detections) {
- final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
- if (qrCodes.size() != 0) {
- Barcode barcode = qrCodes.valueAt(0);
- String scannedQRCode = barcode.displayValue;
- // Handle the scanned code as needed
- }
- }
- });
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- cameraSource.release();
- }
- }
3.确保你的AndroidManifest.xml文件中添加了相应的权限
<uses-permission android:name="android.permission.CAMERA" />
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。