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.
A forward-thinking developer with skills like designing, building integrating, testing, and supporting android mobile applications. Also known for writing efficient, maintainable and reusable code.
Get the latest updates by sharing your email.
Flexible Engagement Model | Secure & Scalable Apps | First Time Right Process
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
We had very close go live timeline and MindBowser team got us live a month before.
They were a very responsive team! Extremely easy to communicate and work with!
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Mindbowser was very helpful with explaining the development process and started quickly on the project.
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Mindbowser is professional, efficient and thorough.
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.
They're very tech-savvy, yet humble.
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.
We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!