Com google zxing android

Распознавание Barcode Android

В данной статье мы будем использовать ZXing (Zebra Crossing), чтобы расшифровать штрихкод в нашем Android приложении.

Используя ZXing, нам не нужно думать о том, что у пользователя нет сканера barcode, так как классы, предоставляемые библиотекой позаботятся об этом. Интегрируя ZXing в наше приложение мы можем предоставить пользователю более простую возможность сканировать шрихкоды, также это позволит нам сфокусироваться на разработке основной части приложения.

Создание нового проекта

Шаг 1

В Eclipse создайте новый Android проект. Введите имя приложения, проекта и название пакета.

Шаг 2

Откройте основной шаблон. Eclipse должен был создать стандартный шаблон. Внутри него замените существующий контент на кнопку

После кнопки добавим два текстовых поля, которые будут отображать результаты отсканированной информации.

Добавьте к кнопке текст. Откройте файл res/values/strings

Чтобы просканировать пользователь должен будет нажать на кнопку. Когда приложение получает результат распознавания, оно отобразит его в текстовых полях.

Интегрируем ZXing

Шаг 1

ZXing — библиотека с открытым исходным кодом, предоставляющая возможность распознавания штрихкодов на Android. Некоторые пользователи уже имеют установленное приложение ZXing, поэтому достаточно передать ему код и дождаться результатов. В данном приложении мы рассмотрим способ, вызывающий соответствующую функцию другого приложения. Если данное приложение отсутствует у пользователя, то будет выведено предложение скачать его.

В Eclipse добавим новый пакет в Ваш проект. Для этого кликнем правой кнопкой мыши по папке src и выберем «New»->«Package», а затем введем com.google.zxing.integration.android в качестве имени пакета.

Шаг 2

Eclipse предлагает несколько способов импортирования существующего кода в проект. В данной статье самым простым методом будет создание двух классов, содержащий код из ZXing. Кликните правой кнопкой мыши по Вашему проекту, выберете «New»->«Class» и введите «IntentIntegrator» в качестве названия класса. Остальные параметры Вы можете не изменять. Как только Вы создали класс, проделайте тоже самое, но назовите класс «IntentResult».

Скопируйте код из обоих классов библиотеки, а затем вставьте его в созданные классы.

Теперь Вы можете подключить файлы в основной класс

Вернемся на минутку и также подключим следующие файлы. Обратите внимание, что Eclipse мог уже их подключить за Вас

Изучите содержание двух классов. Изучив их Вы обнаружите, что они не считывают код. Эти два класса являются просто интерфейсами, предоставляющими доступ к функционалу сканирования.

Сканируем

Шаг 1

Давайте реализуем сканирование, когда пользователь нажимает на нашу кнопку. В главном файле приложения существует метод onCreate, который должен выглядеть примерно так

Перед данной функцией создайте следующие переменные, которые будут хранить нашу кнопку и два текстовых поля, созданных в шаблоне

Читайте также:  Получит ли huawei nova 5t android 11

После существующего кода в onCreate добавьте строки, которые будут инициализировать переменные

Теперь, добавим обработчик нажатия

Расширим класс, чтобы объявить интерфейс OnClickListener

Шаг 2

Теперь, мы можем реагировать на нажатие кнопки началом процесса сканирования. Добавим метод onClick

Проверяем, была ли нажата именно кнопка сканирования

Внутри блока с условием создадим экземпляр класса IntentIntegrator, который мы импортировали

Сейчас, давайте вызовем процедуру, которая начнет сканирование

В данный момент должно начаться распознавание, но только, если у пользователя установлено необходимое приложение. Если его нет, то будет предложено начать загрузку. Результат сканирования будет возвращен приложению.

Обработка результатов сканирования

Шаг 1

Сканер будет запущен, когда нажата кнопка. Затем будет возвращен результат сканирования в метод onActivityResult. Добавим его в наш код

Внутри функции постараемся обработать результат

Шаг 2

Как и любые другие данные, полученные от другого приложения, было бы не плохо проверить, что результат не пуст. Продолжим мы только, если у нас есть правильный результат

Если мы не получили результат сканирования (например, пользователь отменил сканирование), то мы просто выведем сообщение

Вернемся в блок с условием, давайте разберемся с тем, что нам вернула библиотека. Объект Intent Result имеет метод, обеспечивающий получение результата сканирования. Получим результат сканирования, как строку

Также, получим вид barcode

Шаг 3

Теперь, наше приложение имеет всю необходимую для отображения информацию. В нашей статье мы просто отобразим ее пользователю.

Запустите наше приложение на реальном устройстве вместо эмулятора, чтобы увидеть, как работает функционал распознавания штрихкодов. Попробуйте просканировать штрихкод с какой-нибудь книги или любого другого товара.

Результаты сканирования

Источник

Com google zxing android

Project in Maintenance Mode Only

The project is in maintenance mode, meaning, changes are driven by contributed patches. Only bug fixes and minor enhancements will be considered. The Barcode Scanner app can no longer be published, so it’s unlikely any changes will be accepted for it. There is otherwise no active development or roadmap for this project. It is «DIY».

Get Started Developing

ZXing («zebra crossing») is an open-source, multi-format 1D/2D barcode image processing library implemented in Java, with ports to other languages.

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
UPC/EAN Extension 2/5 ITF MaxiCode
RSS-14
RSS-Expanded
Module Description
core The core image decoding library, and test code
javase JavaSE-specific client code
android Android client Barcode Scanner
android-integration Supports integration with Barcode Scanner via Intent
android-core Android-related code shared among android , other Android apps
zxingorg The source behind zxing.org
zxing.appspot.com The source behind web-based barcode generator at zxing.appspot.com

Available in previous releases

Module Description
cpp C++ port
iphone iPhone client
objc Objective C port
actionscript Partial ActionScript port
jruby JRuby wrapper

ZXing-based third-party open source projects

Module Description
QZXing port to Qt framework
glassechidna/zxing-cpp port to C++ (forked from the deprecated official C++ port)
nu-book/zxing-cpp recent port to C++
zxing_cpp.rb bindings for Ruby (not just JRuby), powered by zxing-cpp
jsqrcode port to JavaScript
python-zxing bindings for Python
ZXing .NET port to .NET and C#, and related Windows platform
php-qrcode-detector-decoder port to PHP
ZXing Delphi Port to native Delphi object pascal, targeted at Firemonkey compatible devices (IOS/Android/Win/OSX) and VCL.
ZXingObjC Port to Objective-C
php-zxing PHP wrapper to Zxing Java library
zxing-js/library TypeScript port of ZXing library
pyzxing Python wrapper to ZXing library

Other related third-party open source projects

Module Description
Barcode4J Generator library in Java
ZBar Reader library in C99
OkapiBarcode

Post to the discussion forum or tag a question with zxing on StackOverflow.

QR code is trademarked by Denso Wave, inc. Thanks to Haase & Martin OHG for contributing the logo.

Optimized with

About

ZXing («Zebra Crossing») barcode scanning library for Java, Android

Источник

Com google zxing android

ZXing Android Embedded

Barcode scanning library for Android, using ZXing for decoding.

The project is loosely based on the ZXing Android Barcode Scanner application, but is not affiliated with the official ZXing project.

  1. Can be used via Intents (little code required).
  2. Can be embedded in an Activity, for advanced customization of UI and logic.
  3. Scanning can be performed in landscape or portrait mode.
  4. Camera is managed in a background thread, for fast startup time.

A sample application is available in Releases.

By default, Android SDK 24+ is required because of zxing:core 3.4.x. SDK 19+ is supported with additional configuration, see Older SDK versions.

Adding aar dependency with Gradle

Add the following to your build.gradle file:

Older SDK versions

By default, only SDK 24+ will work, even though the library specifies 19 as the minimum version.

For SDK versions 19+, one of the changes changes below are required. Some older SDK versions below 19 may work, but this is not tested or supported.

Option 1. Downgrade zxing:core to 3.3.0

Option 2: Desugaring (Advanced)

This option does not require changing library versions, but may complicate the build process.

This requires Android Gradle Plugin version 4.0.0 or later.

Example for SDK 21+:

SDK 19+ additionally requires multiDex. In addition to these gradle config changes, the Application class must also be changed. See for details: Configure your app for multidex.

Hardware acceleration is required since TextureView is used.

Make sure it is enabled in your manifest file:

Usage with ScanContract

Note: startActivityForResult is deprecated, so this example uses registerForActivityResult instead. See for details: https://developer.android.com/training/basics/intents/result

startActivityForResult can still be used via IntentIntegrator , but that is not recommended anymore.

See BarcodeOptions for more options.

Generate Barcode example

While this is not the primary purpose of this library, it does include basic support for generating some barcode types:

Changing the orientation

To change the orientation, specify the orientation in your AndroidManifest.xml and let the ManifestMerger to update the Activity’s definition.

Customization and advanced options

For more advanced options, look at the Sample Application, and browse the source code of the library.

This is considered advanced usage, and is not well-documented or supported.

The camera permission is required for barcode scanning to function. It is automatically included as part of the library. On Android 6 it is requested at runtime when the barcode scanner is first opened.

When using BarcodeView directly (instead of via IntentIntegrator / CaptureActivity), you have to request the permission manually before calling BarcodeView#resume() , otherwise the camera will fail to open.

To deploy the artifacts the your local Maven repository:

You can then use your local version by specifying in your build.gradle file:

JourneyApps — Creating business solutions with mobile apps. Fast.

Источник

Didn’t find class «com.google.zxing.BarcodeFormat» #452

Comments

jaag12 commented Jan 16, 2019 •

When starting the detection, it throws me the following error: Did not find class «com.google.zxing.BarcodeFormat»

java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/zxing/BarcodeFormat; at com.google.zxing.client.android.DecodeFormatManager. (DecodeFormatManager.java:37) at com.journeyapps.barcodescanner.DecoratedBarcodeView.initializeFromIntent(DecoratedBarcodeView.java:133) at com.journeyapps.barcodescanner.CaptureManager.initializeFromIntent(CaptureManager.java:167) at com.journeyapps.barcodescanner.CaptureActivity.onCreate(CaptureActivity.java:24) at android.app.Activity.performCreate(Activity.java:6876) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3207) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350) at android.app.ActivityThread.access$1100(ActivityThread.java:222) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:158) at android.app.ActivityThread.main(ActivityThread.java:7229) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) Caused by: java.lang.ClassNotFoundException: Didn’t find class «com.google.zxing.BarcodeFormat» on path: DexPathList[[zip file «/data/app/es.topdigital.locksmartkey-1/base.apk»],nativeLibraryDirectories=[/data/app/es.topdigital.locksmartkey-1/lib/arm64, /vendor/lib64, /system/lib64]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56) at java.lang.ClassLoader.loadClass(ClassLoader.java:511) at java.lang.ClassLoader.loadClass(ClassLoader.java:469) at com.google.zxing.client.android.DecodeFormatManager. (DecodeFormatManager.java:37) at com.journeyapps.barcodescanner.DecoratedBarcodeView.initializeFromIntent(DecoratedBarcodeView.java:133) at com.journeyapps.barcodescanner.CaptureManager.initializeFromIntent(CaptureManager.java:167) at com.journeyapps.barcodescanner.CaptureActivity.onCreate(CaptureActivity.java:24) at android.app.Activity.performCreate(Activity.java:6876) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3207) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350) at android.app.ActivityThread.access$1100(ActivityThread.java:222) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:158) at android.app.ActivityThread.main(ActivityThread.java:7229) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) Suppressed: java.lang.ClassNotFoundException: com.google.zxing.BarcodeFormat at java.lang.Class.classForName(Native Method) at java.lang.BootClassLoader.findClass(ClassLoader.java:781) at java.lang.BootClassLoader.loadClass(ClassLoader.java:841) at java.lang.ClassLoader.loadClass(ClassLoader.java:504) . 17 more Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available

The version I am using is 3.6.0 and implementation ‘com.android.support:appcompat-v7:28.0.0’

The text was updated successfully, but these errors were encountered:

pcamlop commented Mar 21, 2019

Include implementation ‘com.google.zxing:core:3.3.2’ solve this error

rkistner commented Sep 7, 2019

This is typically an issue with the dependency configuration.

If it’s not solved by «Clean Project» and «Rebuild Project», post a sample project reproducing the issue.

Источник

Читайте также:  Прикольные штуки для андроид
Оцените статью