Code scanner library for Android, based on ZXing

Overview

Code Scanner

Android Arsenal API Codacy Badge

Code scanner library for Android, based on ZXing

Features

  • Auto focus and flash light control
  • Portrait and landscape screen orientations
  • Back and front facing cameras
  • Customizable viewfinder
  • Kotlin friendly
  • Touch focus

Supported formats

1D product 1D industrial 2D
UPC-A Code 39 QR Code
UPC-E Code 93 Data Matrix
EAN-8 Code 128 Aztec
EAN-13 Codabar PDF 417
ITF MaxiCode
RSS-14
RSS-Expanded

Usage (sample)

Add dependency:

dependencies {
    implementation 'com.budiyev.android:code-scanner:2.1.0'
}

Add camera permission to AndroidManifest.xml (Don't forget about dynamic permissions on API >= 23):

<uses-permission android:name="android.permission.CAMERA"/>

Define a view in your layout file:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.budiyev.android.codescanner.CodeScannerView
        android:id="@+id/scanner_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:autoFocusButtonColor="@android:color/white"
        app:autoFocusButtonVisible="true"
        app:flashButtonColor="@android:color/white"
        app:flashButtonVisible="true"
        app:frameColor="@android:color/white"
        app:frameCornersSize="50dp"
        app:frameCornersRadius="0dp"
        app:frameAspectRatioWidth="1"
        app:frameAspectRatioHeight="1"
        app:frameSize="0.75"
        app:frameThickness="2dp"
        app:maskColor="#77000000"/>
</FrameLayout>

And add following code to your activity:

Kotlin

class MainActivity : AppCompatActivity() {
    private lateinit var codeScanner: CodeScanner

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val scannerView = findViewById<CodeScannerView>(R.id.scanner_view)
        
        codeScanner = CodeScanner(this, scannerView)
        
        // Parameters (default values)
        codeScanner.camera = CodeScanner.CAMERA_BACK // or CAMERA_FRONT or specific camera id
        codeScanner.formats = CodeScanner.ALL_FORMATS // list of type BarcodeFormat,
                                                      // ex. listOf(BarcodeFormat.QR_CODE)
        codeScanner.autoFocusMode = AutoFocusMode.SAFE // or CONTINUOUS
        codeScanner.scanMode = ScanMode.SINGLE // or CONTINUOUS or PREVIEW
        codeScanner.isAutoFocusEnabled = true // Whether to enable auto focus or not
        codeScanner.isFlashEnabled = false // Whether to enable flash or not
        
        // Callbacks
        codeScanner.decodeCallback = DecodeCallback {
            runOnUiThread {
                Toast.makeText(this, "Scan result: ${it.text}", Toast.LENGTH_LONG).show()
            }
        }
        codeScanner.errorCallback = ErrorCallback { // or ErrorCallback.SUPPRESS
            runOnUiThread {
                Toast.makeText(this, "Camera initialization error: ${it.message}",
                        Toast.LENGTH_LONG).show()
            }
        }
        
        scannerView.setOnClickListener {
            codeScanner.startPreview()
        }
    }

    override fun onResume() {
        super.onResume()
        codeScanner.startPreview()
    }

    override fun onPause() {
        codeScanner.releaseResources()
        super.onPause()
    }
}

Java

public class MainActivity extends AppCompatActivity {
    private CodeScanner mCodeScanner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CodeScannerView scannerView = findViewById(R.id.scanner_view);
        mCodeScanner = new CodeScanner(this, scannerView);
        mCodeScanner.setDecodeCallback(new DecodeCallback() {
            @Override
            public void onDecoded(@NonNull final Result result) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, result.getText(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        scannerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCodeScanner.startPreview();
            }
        });       
    }

    @Override
    protected void onResume() {
        super.onResume();
        mCodeScanner.startPreview();
    }

    @Override
    protected void onPause() {
        mCodeScanner.releaseResources();
        super.onPause();
    }
}

or fragment:

Kotlin

class MainFragment : Fragment() {
    private lateinit var codeScanner: CodeScanner

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, 
            savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_main, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val scannerView = view.findViewById<CodeScannerView>(R.id.scanner_view)
        val activity = requireActivity()
        codeScanner = CodeScanner(activity, scannerView)
        codeScanner.decodeCallback = DecodeCallback {
            activity.runOnUiThread {
                Toast.makeText(activity, it.text, Toast.LENGTH_LONG).show()
            }
        }
        scannerView.setOnClickListener {
            codeScanner.startPreview()
        }
    }

    override fun onResume() {
        super.onResume()
        codeScanner.startPreview()
    }

    override fun onPause() {
        codeScanner.releaseResources()
        super.onPause()
    }
}

Java

public class MainFragment extends Fragment {
    private CodeScanner mCodeScanner;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        final Activity activity = getActivity();
        View root = inflater.inflate(R.layout.fragment_main, container, false);
        CodeScannerView scannerView = root.findViewById(R.id.scanner_view);
        mCodeScanner = new CodeScanner(activity, scannerView);
        mCodeScanner.setDecodeCallback(new DecodeCallback() {
            @Override
            public void onDecoded(@NonNull final Result result) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, result.getText(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        scannerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCodeScanner.startPreview();
            }
        });        
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        mCodeScanner.startPreview();
    }

    @Override
    public void onPause() {
        mCodeScanner.releaseResources();
        super.onPause();
    }
}

Preview

Preview screenshot

Comments
  • Migrate from jcenter to maven central

    Migrate from jcenter to maven central

    With the shutdown of jcenter in may 2021 the artifact needs to be migrated to mavencentral. See https://jfrog.com/blog/into-the-sunset-bintray-jcenter-gocenter-and-chartcenter/ for details.

    opened by mpost 20
  • [Bug/Feature] Pixel 2 XL Not Scanning When QR Code is Exact Fit in ViewFinder

    [Bug/Feature] Pixel 2 XL Not Scanning When QR Code is Exact Fit in ViewFinder

    The issue I have seen on the Pixel 2 XL and I believe the Pixel 2 as well is that for some reason if the QR Code is an exact fit in the view finder frame, it does not scan. I have to move the phone back a bit a relatively considerable amount (QR Code smaller in camera ~8-10 inches) and then it scans properly.

    And in my testing (testing various devices, Samsung, LG, Pixel 1, Pixel 2) the Pixel 2/XL are the only phones to have this issue.

    Why is this a problem? Users will habitually try to fit the QR Code in the frame and not think to move it back because its counter intuitive

    Proposed Solution Add option to the code scanner to pass in the full width rect instead of the rect of the viewfinder (currently fixed at 0.75 of width and with my PR that is adjustable) to the decoder task so that it scans a larger area than the view finder and is able to scan the QR Code on devices that may have this issue

    Obviously this would be an option with perhaps the following api codeScanner.setScanFrameOverride(true|false) codeScanner.setScanFrameSize(0.1 <= frameSize <= 1.0)

    or even codeScanner.setFullWidthScan(true|false) which would tell the codeScanner to use the full width frame of the viewfinderview instead of frameRect(which it is doing right now)

    opened by hkmushtaq 11
  • Camera not initializing

    Camera not initializing

    In logcat: W/CameraBase: An error occurred while connecting to camera: 0

    mCodeScanner.setCamera(findCamera());
    mCodeScanner.startPreview();
    
    private int findCamera() {
        int numberOfCameras = Camera.getNumberOfCameras();
            int cameraId = 0;
            for (int i = 0; i < numberOfCameras; i++) {
                Camera.CameraInfo info = new Camera.CameraInfo();
                Camera.getCameraInfo(i, info);
                if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                    cameraId = i;
                    break;
                }
            }
            return cameraId;
    }
    
    opened by mojojojo42 9
  • Just copy pasted the code after adding dependencies and permissison

    Just copy pasted the code after adding dependencies and permissison

    Program type already present: com.google.zxing.client.android.camera.CameraConfigurationUtils Message{kind=ERROR, text=Program type already present: com.google.zxing.client.android.camera.CameraConfigurationUtils, sources=[Unknown source file], tool name=Optional.of(D8)}

    opened by shan1322 9
  • setParameters failed

    setParameters failed

    Hello! I have a few crashes in Crashlytics with this error:

    Fatal Exception: java.lang.RuntimeException: setParameters failed
           at android.hardware.Camera.native_setParameters(Camera.java)
           at android.hardware.Camera.setParameters(Camera.java:2045)
           at com.budiyev.android.codescanner.CodeScanner$InitializationThread.initialize(CodeScanner.java:891)
           at com.budiyev.android.codescanner.CodeScanner$InitializationThread.run(CodeScanner.java:812)
    

    As I understand we request the camera to be with the view's sizes, but the camera does not support such sizes: https://stackoverflow.com/a/33580027/2838676

    Devices: Xiaomi Redmi 4X, Samsung Galaxy A5(2017)

    opened by ProstoF 8
  • Camera Quality issues

    Camera Quality issues

    The camera quality is really bad, I will look check the code myself but I'm not comparing to the original camera application quality, it doesn't even compare with the Zxing camera intent demo, it's usable on my Pixel 2 XL but not with my other test phones. Please let me know if we can do something regarding this.

    opened by alinalihassan 8
  • speed up the recognition

    speed up the recognition

    Hello,

    thank you for this library. I am just wondering, if there is any way how can I speed up the recognition of QR code. I want to scan just QR codes and right after show different screen based on the scanned data (ScanMode.SINGLE). But the recognition takes quite long time. Although the conditions are good. There are no other codes in the camera view, good light conditions etc. It takes more then 15 seconds and I need to move the camera to by able to scan the code.

    This is my code:

    scannerView = mViews!!.scannerView
    mCodeScanner = CodeScanner(activity, scannerView!!)
    mCodeScanner?.let {
       mCodeScanner.setDecodeCallback(this)
       mCodeScanner.setErrorCallback(this)
       mCodeScanner.isAutoFocusEnabled = true
       mCodeScanner.setAutoFocusInterval(1000)
       mCodeScanner.setFormats(BarcodeFormat.QR_CODE)
       mCodeScanner.setScanMode(ScanMode.SINGLE)
    }
    

    I am using the 1.7.5 version. Thank you for any suggestions.

    opened by danielto 8
  • Feature: Rounded frame corners

    Feature: Rounded frame corners

    Hi. Thank you for your awesome library. I have to round the frame corners because of the app's design. I implemented it as another attribute of the CodeScannerView and draw it on the canvas in the ViewFinderView. If you have any questions about the implementation or you need me to change something, feel free to ask.

    I had some issues with the mask because canvas.clipPath() doesn't support anti-aliasing, which made the round corners pixelated, so I decided to create it from the top and bottom part. The implementation of corners rounding is based on this answer https://stackoverflow.com/a/28655800 , but I had to adjust it to my needs.

    opened by rduriancik 7
  • Scanner orientation

    Scanner orientation

    Hey Yuriy and fellow developers, i would want to ask how to change the scanner orientation using whether the ScannerViewor CodeScannerclass. Or rather can you help me to make the scanner be orientation independent (scan in both orientation states). so far it seems to be portrait fixed when scanning PDF417, QR Code is working in all orientation

    Cheers

    opened by innoflash 5
  • Front Camera Upside Down

    Front Camera Upside Down

    Hi

    A nice and "easy-to-implement" project. Just an issue that I came across on my Samsung S4 mini (KitKat). When using the front camera the preview is upside-down.

    Thanks

    opened by johan-schoeman 5
  • related to issue #30 #80 #127 problem  Application crashes when camer…

    related to issue #30 #80 #127 problem Application crashes when camer…

    related to issue #30 #80 #127 problem Application crashes when the camera is in an inconsistent state and fails to initialize. current error handler is not working in this case is simply crashes app.

    opened by SiddheshShetye 4
  • Camera too dark when embed CodeScannerView to Jetpack Compose

    Camera too dark when embed CodeScannerView to Jetpack Compose

    Hi @yuriy-budiyev i start use this library to scan many kind of qr and barcode, but when it come to Jetpack Compose, I have a trouble : the camera is too dark.

    I try to build from https://github.com/yuriy-budiyev/lib-demo-app everything looks good, so I assume is the problem is not related to the android device

    | From demo app | From Jetpack Compose App | | -------- | -------- | | 2022-12-22 15 12 09 | 2022-12-22 15 12 19 |

    Here is my code :

    @Composable
    private fun CameraView(
        qrCodeReturn: (String) -> Unit
    ) {
        Box(Modifier.fillMaxSize()) {
            AndroidView(
                modifier = Modifier,
                factory = {
                    CodeScannerView(it).apply {
                        val codeScanner = CodeScanner(it, this).apply {
                            isAutoFocusEnabled = true
                            isAutoFocusButtonVisible = false
                            scanMode = ScanMode.SINGLE
                            decodeCallback = DecodeCallback { result ->
                                qrCodeReturn.invoke(result.text)
                                releaseResources()
                            }
                            errorCallback = ErrorCallback {
                                releaseResources()
                            }
                        }
                        codeScanner.startPreview()
                    }
                },
            )
        }
    }
    
    

    TIA

    opened by rizmaulana 0
  • Scanner scans random even if no barcode under camera

    Scanner scans random even if no barcode under camera

    Hi, There is strange issue that if camera is open and still, scanner automatically capture some random numbers as barcodes and there is no actual barcode under camera. Can you please help why is it happening?

    opened by SaadBilal 3
  • Failed to resolve: com.budiyev.android:code-scanner:2.3.2

    Failed to resolve: com.budiyev.android:code-scanner:2.3.2

    Screenshot 2022-11-17 at 15 56 19

    When I reset/invalidate caches of android studio and rebuild the app, I found this error.

    here is my build.gradle

    
    buildscript {
        ext {
            kotlin_version = '1.6.21'
            code_scanner_version = "2.3.2"
        }
        repositories {
            google()
            mavenCentral()
        }
        dependencies {
            classpath "com.android.tools.build:gradle:7.2.0"
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        }
    
    }
    
    allprojects {
        repositories {
            google()
            mavenCentral()
            maven { url 'https://jitpack.io' }
        }
    }
    
    task clean(type: Delete) {
        delete rootProject.buildDir
    }
    
    
    opened by haqim007 3
  • How to set Zoom in Camera using Code Scanner ?

    How to set Zoom in Camera using Code Scanner ?

    I want to set Zoom in Camera but not able achieve this using Code Scanner, please suggest any solution.

    I'm currently using following version :

    implementation 'com.github.yuriy-budiyev:code-scanner:2.3.2'

    opened by vtangade 1
Releases(v2.3.2)
Owner
Yuriy Budiyev
Yuriy Budiyev
Generate Qr Code using ZXING with a logo if needed

QrGeneratorWithLogo Generate Qr Code using ZXING with a logo if needed Download the Helper file and use it 1- add zxing lib into your project implem

null 0 Mar 14, 2022
Android library for creating QR-codes with logo, custom pixel/eyes shapes, background image. Powered by ZXing.

custom-qr-generator Android library for creating QR-codes with logo, custom pixel/eyes shapes, background image. Powerd by ZXing. Installation To get

Alexander Zhirkevich 34 Dec 17, 2022
a simple QRCode generation api for java built on top ZXING

QRGen: a simple QRCode generation api for java built on top ZXING Please consider sponsoring the work on QRGen Dependencies: ZXING: http://code.google

Ken Gullaksen 1.4k Dec 31, 2022
Barcode Scanner Libraries for Android

Project Archived July 1 2020 This project is no longer maintained. When I first started this project in late 2013 there were very few libraries to hel

Dushyanth 5.4k Jan 3, 2023
Qart is Android App that's based on CuteR project. App generate QR code that merge a picture. So the QR code looks more beautiful.

Qart is Android App that's based on CuteR project. App generate QR code that merge a picture. So the QR code looks more beautiful.

scola 1k Dec 16, 2022
Android app and Python library for turning mobile phone into a WebSocket-based, remotely controllable Barcode/QR code reader

Remote Barcode Reader suite Android app and Python library for turning mobile phone into a remotely controllable Barcode/QR code reader. It exposes a

Krystian Dużyński 3 Dec 6, 2022
QRAlarm - an Android alarm clock application lets the user turn off alarms by scanning the QR Code.

QRAlarm is an Android alarm clock application that does not only wake You up, but also makes You get up to disable the alarm by scanning the QR Code.

null 39 Jan 8, 2023
MyQRScanner - Simple app for reading QR Code

My QRCode Scanner Simple app for reading QR Code Technologies Jetpack Compose Ca

Joselaine Aparecida dos Santos 4 Feb 17, 2022
⭐️ Quick and easy QR Code scanning app created using Jetpack Compose. ☘️

QR-Code-Scanner Scan your QR codes easily and quickly. ⭐️ Google Play Store : Screenshots of the app : ?? Libraries Used in The Project : // Jetpa

Nisa Efendioğlu 12 Oct 8, 2022
A library to help implement barcode scanning

A library to help implement barcode scanning

Brightec 99 Nov 30, 2022
ZATAC Scanner is Android Kotlin-based QR code scanner and parser which de-crypt TLV qr codes and parse them into their values.

ZATAC Scanner is Android Kotlin-based QR code scanner and parser which de-crypt TLV qr codes and parse them into their values.

Enozom 12 Apr 23, 2022
D4rK QR & Bar Code Scanner Plus is a FOSS scanner app for every Android. 📷

?? QR & Bar Code Scanner Plus ?? ╔╦╦╦═╦╗╔═╦═╦══╦═╗ ║║║║╩╣╚╣═╣║║║║║╩╣ ╚══╩═╩═╩═╩═╩╩╩╩═╝ D4rK QR & Bar Code Scanner Plus is a FOSS scanner app for every

D4rK 8 Dec 19, 2022
Generate Qr Code using ZXING with a logo if needed

QrGeneratorWithLogo Generate Qr Code using ZXING with a logo if needed Download the Helper file and use it 1- add zxing lib into your project implem

null 0 Mar 14, 2022
ZXing ("Zebra Crossing") barcode scanning library for Java, Android

Project in Maintenance Mode Only The project is in maintenance mode, meaning, changes are driven by contributed patches. Only bug fixes and minor enha

ZXing Project 30.5k Dec 27, 2022
Android library for creating QR-codes with logo, custom pixel/eyes shapes, background image. Powered by ZXing.

custom-qr-generator Android library for creating QR-codes with logo, custom pixel/eyes shapes, background image. Powerd by ZXing. Installation To get

Alexander Zhirkevich 34 Dec 17, 2022
a simple QRCode generation api for java built on top ZXING

QRGen: a simple QRCode generation api for java built on top ZXING Please consider sponsoring the work on QRGen Dependencies: ZXING: http://code.google

Ken Gullaksen 1.4k Dec 31, 2022
ArchGuard Scanner for scan Git change history, scan source code by Chapi for Java, TypeScript, Kotlin, Go..、Java bytecode use for JVM languages, scan Jacoco test coverage.

Arch Scanner Requirements: JDK 12 Scanner: scan_git - Git commit history scan scan_jacoco - Jacoco scan scan_bytecode - for JVM languages known issues

ArchGuard 27 Jul 28, 2022
Barcode Scanner Libraries for Android

Project Archived July 1 2020 This project is no longer maintained. When I first started this project in late 2013 there were very few libraries to hel

Dushyanth 5.4k Jan 3, 2023
Barcode Scanner Libraries for Android

Project Archived July 1 2020 This project is no longer maintained. When I first started this project in late 2013 there were very few libraries to hel

Dushyanth 5.4k Jan 9, 2023
Yet another barcode scanner for Android

Binary Eye Yet another barcode scanner for Android. As if there weren't enough. This one is free, without any ads and open source. Works in portrait a

Markus Fisch 802 Dec 31, 2022