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.
The team at Mindbowser was highly professional, patient, and collaborative throughout our engagement. They struck the right balance between offering guidance and taking direction, which made the development process smooth. Although our project wasn’t related to healthcare, we clearly benefited...
Founder, Texas Ranch Security
Mindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
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.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
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.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork