How to scan QRCode in android

前端 未结 7 2262
说谎
说谎 2020-12-25 14:04

I found a tutorial on how to scan a barcode. But in my application I have to scan a QR code. How can I a scan QR code in Android?

相关标签:
7条回答
  • 2020-12-25 15:05

    One way is using the AppCompatActivity and ZXingScannerView.ResultHandler interface.

    import android.annotation.SuppressLint;
    import android.content.Context;
    import android.content.Intent;
    import android.hardware.Camera;
    import android.hardware.camera2.CameraAccessException;
    import android.hardware.camera2.CameraCharacteristics;
    import android.hardware.camera2.CameraManager;
    import android.os.Build;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.RelativeLayout;;
    
    import com.android.volley.VolleyError;
    import com.example.team.merchant.functional.Request;
    import com.example.team.merchant.functional.ResponseListener;
    import com.google.zxing.Result;
    
    import me.dm7.barcodescanner.zxing.ZXingScannerView;
    
    /**
     * Created by Prakhar on 5/16/2016.
     */
    public class MerchantScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
        private ZXingScannerView mScannerView;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            RelativeLayout relativeLayout = new RelativeLayout(this);
    
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(60, 60);
            params.setMargins(0, 50, 50, 0);
            params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
    
    
            Button switchCamera = new Button(this); //declare a button in layout for camera change option
            switchCamera.setLayoutParams(params);
            switchCamera.setBackgroundResource(R.drawable.switch_camera);
            relativeLayout.addView(switchCamera);
            final int i = getFrontCameraId();
            if (i == -1) {
                switchCamera.setVisibility(View.GONE);
            }
    
    
            mScannerView = new ZXingScannerView(this);   // Programmatically initialize the scanner view
            relativeLayout.addView(mScannerView);
    
            setContentView(relativeLayout);
            final int[] id = {0};
            switchCamera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mScannerView.stopCamera();
                    if (id[0] % 2 == 0) {
                        mScannerView.startCamera(i);
                    } else {
                        mScannerView.startCamera();
                    }
                    id[0]++;
                }
            });
    
            mScannerView.setResultHandler(this);// Register ourselves as a handler for scan results.
    
            mScannerView.startCamera();         // Start camera
    
    
        }
    
        @SuppressLint("NewApi")
        int getFrontCameraId() {
            if (Build.VERSION.SDK_INT < 22) {
                Camera.CameraInfo ci = new Camera.CameraInfo();
                for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
                    Camera.getCameraInfo(i, ci);
                    if (ci.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) return i;
                }
            } else {
                try {
                    CameraManager cManager = (CameraManager) getApplicationContext()
                            .getSystemService(Context.CAMERA_SERVICE);
                    String[] cameraId = cManager.getCameraIdList();
                    for (int j = 0; j < cameraId.length; j++) {
                        CameraCharacteristics characteristics = cManager.getCameraCharacteristics(cameraId[j]);
                        int cOrientation = characteristics.get(CameraCharacteristics.LENS_FACING);
                        if (cOrientation == CameraCharacteristics.LENS_FACING_FRONT)
                            return Integer.parseInt(cameraId[j]);
                    }
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }
            return -1; // No front-facing camera found
        }
    
        @Override
        public void onPause() {
            super.onPause();
            mScannerView.stopCamera();           // Stop camera on pause
        }
    
        @Override
        public void handleResult(Result rawResult) {
           // rawResult.getText()
           // handle your result here
           // handle exceptions here
        }
    }
    

    Other can be used in fragments accordingly.

    import android.Manifest;
    import android.os.Build;
    import android.os.Bundle;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v4.content.ContextCompat;
    import android.support.v7.app.AlertDialog;
    
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import com.google.zxing.ResultPoint;
    import com.journeyapps.barcodescanner.BarcodeCallback;
    import com.journeyapps.barcodescanner.BarcodeResult;
    import com.journeyapps.barcodescanner.CompoundBarcodeView;
    
    
    /**
     * Created by Prakhar on 3/8/2016.
     */
    public class PayWithQrCodeScannerFragment extends Fragment {
    
        private static final int PERMISSION_REQUEST_CAMERA = 23;
        public static CompoundBarcodeView barcodeScannerView;
        public static BarcodeCallback callback;
    
    
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.paywithqrcodescannerfragment, container, false);
    
            barcodeScannerView = (CompoundBarcodeView) view.findViewById(R.id.zxing_barcode_scanner);
    
    
            callback = new BarcodeCallback() {
                @Override
                public void barcodeResult(BarcodeResult result) {
                        // handle result and exceptions here
                }
            return view;
        }
    
        /**
         * Check if the device's camera has a Flashlight.
         *
         * @return true if there is Flashlight, otherwise false.
         */
        private boolean hasFlash() {
            return getActivity().getApplicationContext().getPackageManager()
                    .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
        }
    
    
        @Override
        public void onResume() {
            super.onResume();
            if (android.os.Build.VERSION.SDK_INT < 23) {
                barcodeScannerView.resume();
            }
        }
    
    
        @Override
        public void onPause() {
            super.onPause();
            if (android.os.Build.VERSION.SDK_INT < 23) {
                barcodeScannerView.pause();
            }
        }
    
    }
    

    Use below written in layout XML file to placeholder the scanner

    <com.journeyapps.barcodescanner.CompoundBarcodeView
                android:id="@+id/zxing_barcode_scanner"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:zxing_preview_scaling_strategy="centerCrop"
                app:zxing_use_texture_view="false" />
    

    Build.gradle

    compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
    compile 'com.google.zxing:core:3.2.1'
    
    0 讨论(0)
提交回复
热议问题