Nowadays, Everyone is using Applications like Phonepe, GooglePay, Paytm for payment as they are providing a convenient and faster way of payment just by scanning the QR Code.
One of my clients has also asked me to implement QR code scanning for the payment in his application. According to me Look and feel of the application is also important. So let’s customize the camera view for QR code scanning. And implement Camera API to scan the QR code.
Before we move to coding I am sharing one preview image.
Add dependency of Google vision in build.gradle(:app)
implementation 'com.google.android.gms:play-services-vision:20.1.0
RectangleOverLayView.java is used to draw a rectangle on canvas.
public class RectangleOverLayView extends LinearLayout {
private Bitmap bitmap;
public RectangleOverLayView(Context context) {
super(context);
}
public RectangleOverLayView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RectangleOverLayView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public RectangleOverLayView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (bitmap == null) {
createWindowFrame();
}
canvas.drawBitmap(bitmap, 0, 0, null);
}
protected void createWindowFrame() {
setWillNotDraw(false);
setLayerType(LAYER_TYPE_HARDWARE, null);
bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas osCanvas = new Canvas(bitmap);
RectF outerRectangle = new RectF(0, 0, getWidth(), getHeight());
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(getResources().getColor(R.color.scannerBg));
osCanvas.drawRect(outerRectangle, paint);
paint.setColor(Color.TRANSPARENT);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
float x1 = getWidth() / 5;
float x2 = getWidth() - x1;
float heightDiff = x2 - x1;
float y1 = (getHeight() / 2) - (heightDiff / 2);
float y2 = (getHeight() / 2) + (heightDiff / 2);
RectF rect = new RectF(x1, y1, x2, y2);
osCanvas.drawRoundRect(rect, 100, 100, paint);
RectF rectBorder = new RectF(x1 + 10, y1 + 10, x2 - 10, y2 - 10);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(20);
paint.setColor(Color.WHITE);
osCanvas.drawRoundRect(rectBorder, 90, 90, paint);
}
@Override
public boolean isInEditMode() {
return true;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
bitmap = null;
}
}
Camera_preview.Xml
Camera View with the Rectangle in the center is done. So let’s start with the Camera source to scan the QR code. This camera source is a part of the android-vision(https://github.com/googlesamples/android-vision). This one is the easiest and best way of scanning without any other third party.
First, add camera permission in AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
CameraPreview.Java
public class CameraPreview extends Fragment implements SurfaceHolder.Callback, Detector.Processor { private CameraSource cameraSource; private BarcodeDetector barcodeDetector; private SurfaceView surfaceCamera; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); return inflater.inflate(R.layout.camera_preview, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); surfaceCamera = view.findViewById(R.id.surfaceCamera); } @Override public void surfaceCreated(SurfaceHolder holder) { //Ask for runtime camera permission before call startCameraSurface startCameraSurface(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceDestroyed(SurfaceHolder holder) { } @Override public void release() { } @Override public void receiveDetections(Detector.Detections detections) { SparseArray barcode = detections.getDetectedItems(); if ( barcode.size()>0){ Log.e("CameraPreview"," QR Code : "+barcode.valueAt(0).displayValue); } } private void setBarCodeListeners() { barcodeDetector = new BarcodeDetector.Builder(getActivity()) .setBarcodeFormats(Barcode.ALL_FORMATS) .build(); DisplayMetrics displayMetrics = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); cameraSource = new CameraSource.Builder(getActivity(), barcodeDetector) .setRequestedPreviewSize(displayMetrics.heightPixels, displayMetrics.widthPixels) .setAutoFocusEnabled(true) .build(); surfaceCamera.getHolder().addCallback(this); barcodeDetector.setProcessor(this); } private void startCameraSurface() { barcodeDetector.setProcessor(this); if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } try { cameraSource.start(surfaceCamera.getHolder()); } catch (IOException e) { e.printStackTrace(); } } private void stopSurface(){ cameraSource.stop(); } @Override public void onPause() { super.onPause(); stopSurface(); barcodeDetector.release(); } @Override public void onStart() { super.onStart(); setBarCodeListeners(); } }
There are many third-party libraries available on Git for Qr code Scanning. But the best practice to scan the QR code is google vision APIs. Using these APIs you can achieve many features like face tracker, eye tracker, etc.
Hopefully, this helps you to develop the scanning QR code functionality in an easy way.
What’s on your mind? Tell us a little bit about yourself and your question, and we will be in touch with you within 12 hours
Free eBook on Telemedicine Platform Development: All About Telemedicine
Download Free eBook Now!