将ZXing库直接集成到我的Android应用程序中

我只是写这个绝望:)我已经被分配到一个Android 1.6手机独立的条码扫描器(作为概念certificate)。

为此我发现了ZXing库。

我google了,在这里阅读相关的主题StackOverflow使用常见的等等。 似乎没有什么帮助,我不能在这个精神封锁上打出一个洞:

我知道这是可能的,使用库,并创build自己的独立条形码扫描仪。 我读过使用Zxing人提供的“Barcode Scanner”,是迄今为止最简单的解决scheme(通过Intent)。 不幸的是,这不是一个选项,并且需要一个独立的应用程序。

所以总结一下我的问题:

  1. 如何通过Eclipse将ZXing源码库集成到我的Android代码项目中?
  2. 当集成…如何利用lib,“加载”扫描function?
  3. 一步一步的指导几乎是首选,因为我刚开始在Eclipse中工作。

我试图让我的代码项目依赖于ZXing源文件夹中的Android文件夹。 当我这样做的时候,出现了一个handfull错误,主要是关于'org.apache'(??)

我只是无法弄清楚…所以一些提示将是最有帮助的。

提前,谢谢:)

UPDATE! – 已解决+指导

我已经弄清楚了:)下面你可以阅读一步一步的指导,所以希望可以帮助其他人与我有同样的问题;)

  1. 安装Apache Ant – ( 请参阅此YouTubevideo以获取configuration帮助 )
  2. 从ZXing主页下载ZXing源码并解压
  3. 使用Windows命令行(Run-> CMD)导航到下载的zxing src的根目录。
  4. 在命令行窗口中 – inputant -f core/build.xml按回车让Apache工作是有魔力的[ 有问题吗? ]
  5. 进入Eclipse – >新的Android项目,基于刚解压缩的目录中的android文件夹
  6. 右键单击项目文件夹 – >属性 – > Java Build Path – > Library – > Add External JAR …
  7. 导航到新提取的文件夹并打开核心目录并selectcore.jar …点击进入!

现在,您只需要在翻译和AndroidManifest.xml文件中更正一些错误:)现在您可以愉快地进行编译,现在您将拥有一个基于ZXing源代码的独立条形码扫描器应用程序;)

快乐的编码家伙 – 我希望它可以帮助别人:)

以下是关于如何使用ZXing库生成和显示QR码的分步指南,无需安装第三方应用程序。 注意:您不必使用ANT或任何其他构build工具来构buildZXing。 core.jar文件可以在发布的zip压缩文件中find(阅读下面)。

  1. 下载最新版本的ZXing 。 – ( ZXing-*.zip
  2. 解压缩这个zip压缩包并在core/目录下findcore.jar
  3. 如果您使用Eclipse IDE,请将core.jar拖放到Android项目的libs目录中。 当被问到时,select复制
  4. 将下面给出的两个类( Contents.javaQRCodeEncoder.java )复制到Android项目的主包中。
  5. 在您的活动中创build一个ImageView项目,以显示生成的QR码,如果您还没有。 下面给出一个例子:
  6. 使用下面的代码片段来生成位图格式的QR码并将其显示在ImageView

这里是一个ImageView元素添加到您的活动布局XML文件:

 <ImageView android:id="@+id/qrCode" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:layout_centerHorizontal="true"/> 

代码片段:

 // ImageView to display the QR code in. This should be defined in // your Activity's XML layout file ImageView imageView = (ImageView) findViewById(R.id.qrCode); String qrData = "Data I want to encode in QR code"; int qrCodeDimention = 500; QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrData, null, Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), qrCodeDimention); try { Bitmap bitmap = qrCodeEncoder.encodeAsBitmap(); imageView.setImageBitmap(bitmap); } catch (WriterException e) { e.printStackTrace(); } 

这里是Contents.java

 // // * Copyright (C) 2008 ZXing authors // * // * Licensed under the Apache License, Version 2.0 (the "License"); // * you may not use this file except in compliance with the License. // * You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * See the License for the specific language governing permissions and // * limitations under the License. // import android.provider.ContactsContract; public final class Contents { private Contents() { } public static final class Type { // Plain text. Use Intent.putExtra(DATA, string). This can be used for URLs too, but string // must include "http://" or "https://". public static final String TEXT = "TEXT_TYPE"; // An email type. Use Intent.putExtra(DATA, string) where string is the email address. public static final String EMAIL = "EMAIL_TYPE"; // Use Intent.putExtra(DATA, string) where string is the phone number to call. public static final String PHONE = "PHONE_TYPE"; // An SMS type. Use Intent.putExtra(DATA, string) where string is the number to SMS. public static final String SMS = "SMS_TYPE"; public static final String CONTACT = "CONTACT_TYPE"; public static final String LOCATION = "LOCATION_TYPE"; private Type() { } } public static final String URL_KEY = "URL_KEY"; public static final String NOTE_KEY = "NOTE_KEY"; // When using Type.CONTACT, these arrays provide the keys for adding or retrieving multiple phone numbers and addresses. public static final String[] PHONE_KEYS = { ContactsContract.Intents.Insert.PHONE, ContactsContract.Intents.Insert.SECONDARY_PHONE, ContactsContract.Intents.Insert.TERTIARY_PHONE }; public static final String[] PHONE_TYPE_KEYS = { ContactsContract.Intents.Insert.PHONE_TYPE, ContactsContract.Intents.Insert.SECONDARY_PHONE_TYPE, ContactsContract.Intents.Insert.TERTIARY_PHONE_TYPE }; public static final String[] EMAIL_KEYS = { ContactsContract.Intents.Insert.EMAIL, ContactsContract.Intents.Insert.SECONDARY_EMAIL, ContactsContract.Intents.Insert.TERTIARY_EMAIL }; public static final String[] EMAIL_TYPE_KEYS = { ContactsContract.Intents.Insert.EMAIL_TYPE, ContactsContract.Intents.Insert.SECONDARY_EMAIL_TYPE, ContactsContract.Intents.Insert.TERTIARY_EMAIL_TYPE }; } 

QRCodeEncoder.java

 /* * Copyright (C) 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.provider.ContactsContract; import android.graphics.Bitmap; import android.os.Bundle; import android.telephony.PhoneNumberUtils; import java.util.Collection; import java.util.EnumMap; import java.util.HashSet; import java.util.Map; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; public final class QRCodeEncoder { private static final int WHITE = 0xFFFFFFFF; private static final int BLACK = 0xFF000000; private int dimension = Integer.MIN_VALUE; private String contents = null; private String displayContents = null; private String title = null; private BarcodeFormat format = null; private boolean encoded = false; public QRCodeEncoder(String data, Bundle bundle, String type, String format, int dimension) { this.dimension = dimension; encoded = encodeContents(data, bundle, type, format); } public String getContents() { return contents; } public String getDisplayContents() { return displayContents; } public String getTitle() { return title; } private boolean encodeContents(String data, Bundle bundle, String type, String formatString) { // Default to QR_CODE if no format given. format = null; if (formatString != null) { try { format = BarcodeFormat.valueOf(formatString); } catch (IllegalArgumentException iae) { // Ignore it then } } if (format == null || format == BarcodeFormat.QR_CODE) { this.format = BarcodeFormat.QR_CODE; encodeQRCodeContents(data, bundle, type); } else if (data != null && data.length() > 0) { contents = data; displayContents = data; title = "Text"; } return contents != null && contents.length() > 0; } private void encodeQRCodeContents(String data, Bundle bundle, String type) { if (type.equals(Contents.Type.TEXT)) { if (data != null && data.length() > 0) { contents = data; displayContents = data; title = "Text"; } } else if (type.equals(Contents.Type.EMAIL)) { data = trim(data); if (data != null) { contents = "mailto:" + data; displayContents = data; title = "E-Mail"; } } else if (type.equals(Contents.Type.PHONE)) { data = trim(data); if (data != null) { contents = "tel:" + data; displayContents = PhoneNumberUtils.formatNumber(data); title = "Phone"; } } else if (type.equals(Contents.Type.SMS)) { data = trim(data); if (data != null) { contents = "sms:" + data; displayContents = PhoneNumberUtils.formatNumber(data); title = "SMS"; } } else if (type.equals(Contents.Type.CONTACT)) { if (bundle != null) { StringBuilder newContents = new StringBuilder(100); StringBuilder newDisplayContents = new StringBuilder(100); newContents.append("MECARD:"); String name = trim(bundle.getString(ContactsContract.Intents.Insert.NAME)); if (name != null) { newContents.append("N:").append(escapeMECARD(name)).append(';'); newDisplayContents.append(name); } String address = trim(bundle.getString(ContactsContract.Intents.Insert.POSTAL)); if (address != null) { newContents.append("ADR:").append(escapeMECARD(address)).append(';'); newDisplayContents.append('\n').append(address); } Collection<String> uniquePhones = new HashSet<String>(Contents.PHONE_KEYS.length); for (int x = 0; x < Contents.PHONE_KEYS.length; x++) { String phone = trim(bundle.getString(Contents.PHONE_KEYS[x])); if (phone != null) { uniquePhones.add(phone); } } for (String phone : uniquePhones) { newContents.append("TEL:").append(escapeMECARD(phone)).append(';'); newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone)); } Collection<String> uniqueEmails = new HashSet<String>(Contents.EMAIL_KEYS.length); for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) { String email = trim(bundle.getString(Contents.EMAIL_KEYS[x])); if (email != null) { uniqueEmails.add(email); } } for (String email : uniqueEmails) { newContents.append("EMAIL:").append(escapeMECARD(email)).append(';'); newDisplayContents.append('\n').append(email); } String url = trim(bundle.getString(Contents.URL_KEY)); if (url != null) { // escapeMECARD(url) -> wrong escape eg http\://zxing.google.com newContents.append("URL:").append(url).append(';'); newDisplayContents.append('\n').append(url); } String note = trim(bundle.getString(Contents.NOTE_KEY)); if (note != null) { newContents.append("NOTE:").append(escapeMECARD(note)).append(';'); newDisplayContents.append('\n').append(note); } // Make sure we've encoded at least one field. if (newDisplayContents.length() > 0) { newContents.append(';'); contents = newContents.toString(); displayContents = newDisplayContents.toString(); title = "Contact"; } else { contents = null; displayContents = null; } } } else if (type.equals(Contents.Type.LOCATION)) { if (bundle != null) { // These must use Bundle.getFloat(), not getDouble(), it's part of the API. float latitude = bundle.getFloat("LAT", Float.MAX_VALUE); float longitude = bundle.getFloat("LONG", Float.MAX_VALUE); if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) { contents = "geo:" + latitude + ',' + longitude; displayContents = latitude + "," + longitude; title = "Location"; } } } } public Bitmap encodeAsBitmap() throws WriterException { if (!encoded) return null; Map<EncodeHintType, Object> hints = null; String encoding = guessAppropriateEncoding(contents); if (encoding != null) { hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class); hints.put(EncodeHintType.CHARACTER_SET, encoding); } MultiFormatWriter writer = new MultiFormatWriter(); BitMatrix result = writer.encode(contents, format, dimension, dimension, hints); int width = result.getWidth(); int height = result.getHeight(); int[] pixels = new int[width * height]; // All are 0, or black, by default for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = result.get(x, y) ? BLACK : WHITE; } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } private static String guessAppropriateEncoding(CharSequence contents) { // Very crude at the moment for (int i = 0; i < contents.length(); i++) { if (contents.charAt(i) > 0xFF) { return "UTF-8"; } } return null; } private static String trim(String s) { if (s == null) { return null; } String result = s.trim(); return result.length() == 0 ? null : result; } private static String escapeMECARD(String input) { if (input == null || (input.indexOf(':') < 0 && input.indexOf(';') < 0)) { return input; } int length = input.length(); StringBuilder result = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = input.charAt(i); if (c == ':' || c == ';') { result.append('\\'); } result.append(c); } return result.toString(); } } 

 compile 'com.google.zxing:core:2.3.0' 

不幸的是没有为我工作。

这对我来说是有效的:

 dependencies { compile 'com.journeyapps:zxing-android-embedded:3.0.1@aar' compile 'com.google.zxing:core:3.2.0' } 

请在这里find链接: https : //github.com/journeyapps/zxing-android-embedded

与ANTbuild立问题? 继续阅读

如果ant -f core/build.xml表示如下所示:

 Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre6\lib\tools.jar 

然后将您的JAVA_HOME环境variables设置为适当的java文件夹。 我在(对于Windows)中find了tools.jar:

 C:\Program Files\Java\jdk1.6.0_21\lib 

所以我把我的JAVA_HOME为:

 C:\Progra~1\Java\jdk1.6.0_25 

我在一些网站上发现的短语法的原因是:

“强烈build议您select一个不包含path名中空格的安装目录(例如,不要在C:\ Program Files中安装)。如果Java安装在这样的目录中,设置JAVA_HOME环境variables添加到不包含空格的path中(例如,C:\ Progra〜1);如果不执行此操作,则会导致某些依赖于JAVA_HOME值的程序抛出exception。

然后我重新启动cmd(重要,因为DOS shell在启动时只读取env vars,所以更改env var将需要您使用新的shell来获取更新的值)

最后是ant -f core/build.xml

由于一些答案已经过时,我想提供我自己的 –

要按照Wiki的build议将ZXing库集成到您的Android应用程序中,您需要将2个Java文件添加到您的项目中:

  • IntentIntegrator.java
  • IntentResult.java

然后在Android Studio中将以下行添加到build.gradle文件中:

 dependencies { .... compile 'com.google.zxing:core:3.2.1' } 

或者,如果仍然使用Eclipse和ADT-plugin,将core.jar文件添加到项目的libs子目录(此处为全屏Windows和全屏Mac ):

Windows截图

最后把这个代码添加到你的MainActivity.java中 :

 public void scanQRCode(View v) { IntentIntegrator integrator = new IntentIntegrator(MainActivity.this); integrator.initiateScan(IntentIntegrator.QR_CODE_TYPES); } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (result != null) { String contents = result.getContents(); if (contents != null) { showDialog(R.string.result_succeeded, result.toString()); } else { showDialog(R.string.result_failed, getString(R.string.result_failed_why)); } } } private void showDialog(int title, CharSequence message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(title); builder.setMessage(message); builder.setPositiveButton(R.string.ok_button, null); builder.show(); } 

由此产生的应用程序将要求ZXing安装并启动Barcode Scanner应用程序 (扫描完成后会自动返回到您的应用程序):

条码扫描器应用程序

此外,如果您想要构build并运行ZXing Test应用程序作为您自己的应用程序的灵感:

ZXing测试应用程序

那么你需要从GitHub获得 4个Java文件:

  • BenchmarkActivity.java
  • BenchmarkAsyncTask.java
  • BenchmarkItem.java
  • ZXingTestActivity.java

以及来自Maven仓库的 3个Jar文件:

  • core.jar添加
  • Android的core.jar添加
  • Android的integration.jar

(你可以用mvn package自己构buildJar文件 – 如果你从GitHub检出ZXing并在你的计算机上安装antmaven工具)。

注意:如果您的项目不能识别Jar文件,则可能需要在项目属性中启动Java版本:

属性截图

你有没有看到zxing网站上的维基页面 ? 看起来你可能会发现GettingStarted , DeveloperNotes和ScanningViaIntent有帮助。

 compile 'com.google.zxing:core:2.3.0' 

到您的Gradle依赖关系中。 就这么简单。 在使用Android Studio和Gradle构build系统之前。

如果您只需要zxing中的core.jar,则可以跳过该过程并从GettingStarted wiki页面获取预构build的JAR

最新的ZXing(2.2)在核心文件夹下没有core.jar,但是你可以在这里从zxing Maven仓库获得core.jar

在eclipse中一步步设置zxing 3.2.1

  1. 从“ https://github.com/zxing/zxing ”下载zxing-master.zip
  2. 解压zxing-master.zip,使用eclipse导入zxing-master中的“android”项目
  3. 从“ http://repo1.maven.org/maven2/com/google/zxing/core/3.2.1/ ”下载core-3.2.1.jar
  4. 在“android”项目中创build“libs”文件夹,并将cor-3.2.1.jar粘贴到libs文件夹中
  5. 点击项目:select“属性” – >“Java编译器”将级别更改为1.7。 然后点击“Android”将“Project build target”更改为android 4.4.2+,因为使用1.7需要使用Android 4.4编译
  6. 如果“zxing-master / android / app / src / main / java / com / google / zxing / client / android / camera /”中不存在“CameraConfigurationUtils.java”。 你可以从“zxing-master / android-core / src / main / java / com / google / zxing / client / android / camera /”复制它并粘贴到你的项目中。
  7. 清理并build立项目。 如果你的项目显示“switch-case”错误,你应该把它们改成“if-else”。
  8. 已完成。 清理并build立项目。
  9. 参考链接: 使用ZXing创build一个Android条码扫描应用程序

我尝试了所有可能的方法来实现这一目标,然后我发现JourneyApps的xZing的缩小版。 我已经移植了Eclipse并在GitHub上共享。

如果你使用eclipse,使用这个项目:

https://github.com/hiteshsahu/XZing-Barcode-Scanner-Minified-Eclipse

如果您正在使用Studio,请使用此项目: –

https://github.com/journeyapps/zxing-android-embedded

优点

  1. 内置的条码扫描器在您的应用程序不需要安装使用Playstore的第三方应用程序。

  2. 你不需要在Core,Android客户端等jar之间混淆,只需将这个包和相关的布局放在你的项目中,你就可以走了。 只有Jar需要com.google.zxing:core:3.2.0 ,您可以从中下载

    http://mvnrepository.com/artifact/com.google.zxing/core/3.2.0

  3. 无需添加大量的软件包,请参阅下面的图片进行比较

之前: –

在这里输入图像描述

之后: –

在这里输入图像描述

  1. 最重要的部分是他们是高度可定制的,即。 您可以添加闪光灯,在碎片中使用它并支持方向更改。

  2. 您可以在Cordova App中使用此Capture活动进行条码扫描。

应用程序清单中的捕获活动将如下所示

  <activity android:name="com.journeyapps.barcodescanner.CaptureActivity" android:clearTaskOnLaunch="true" android:configChanges="orientation|keyboardHidden" android:exported="false" android:screenOrientation="fullSensor" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:windowSoftInputMode="stateAlwaysHidden" > <intent-filter> <action android:name="com.google.zxing.client.android.SCAN" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> 

和插件将看起来像这样

 public class BarcodeScanner extends CordovaPlugin { public static final int REQUEST_CODE = 0x0ba7c0de; private static final String SCAN = "scan"; private static final String CANCELLED = "cancelled"; private static final String FORMAT = "format"; private static final String TEXT = "text"; private static final String SCAN_INTENT = "com.google.zxing.client.android.SCAN"; private static final String LOG_TAG = "BarcodeScanner"; private CallbackContext callbackContext; /** * Constructor. */ public BarcodeScanner() { } /** * Executes the request. * * This method is called from the WebView thread. To do a non-trivial amount of work, use: * cordova.getThreadPool().execute(runnable); * * To run on the UI thread, use: * cordova.getActivity().runOnUiThread(runnable); * * @param action The action to execute. * @param args The exec() arguments. * @param callbackContext The callback context used when calling back into JavaScript. * @return Whether the action was valid. * * @sa https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaPlugin.java */ @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { this.callbackContext = callbackContext; if (action.equals(SCAN)) { scan(args); } else { return false; } return true; } /** * Starts an intent to scan and decode a barcode. */ public void scan(JSONArray args) { Intent intentScan = new Intent(SCAN_INTENT); intentScan.addCategory(Intent.CATEGORY_DEFAULT); // add config as intent extras if(args.length() > 0) { JSONObject obj; JSONArray names; String key; Object value; for(int i=0; i<args.length(); i++) { try { obj = args.getJSONObject(i); } catch(JSONException e) { Log.i("CordovaLog", e.getLocalizedMessage()); continue; } names = obj.names(); for(int j=0; j<names.length(); j++) { try { key = names.getString(j); value = obj.get(key); if(value instanceof Integer) { intentScan.putExtra(key, (Integer)value); } else if(value instanceof String) { intentScan.putExtra(key, (String)value); } } catch(JSONException e) { Log.i("CordovaLog", e.getLocalizedMessage()); continue; } } } } // avoid calling other phonegap apps intentScan.setPackage(this.cordova.getActivity().getApplicationContext().getPackageName()); this.cordova.startActivityForResult((CordovaPlugin) this, intentScan, REQUEST_CODE); } /** * Called when the barcode scanner intent completes. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { JSONObject obj = new JSONObject(); try { obj.put(TEXT, intent.getStringExtra("SCAN_RESULT")); obj.put(FORMAT, intent.getStringExtra("SCAN_RESULT_FORMAT")); obj.put(CANCELLED, false); } catch (JSONException e) { Log.d(LOG_TAG, "JSONException "+e.getMessage()); } this.callbackContext.success(obj); } else if (resultCode == Activity.RESULT_CANCELED) { this.callbackContext.success(""); } else { this.callbackContext.error("Technical Problem"); } } } } 

快乐融合!

zxing人使得用1.7创build一个android项目更容易。 它不像以前那样痛苦。 这是一个快速的博客,任何人都想快速创build一个android的zxing项目。

  • 检出zxing.org的zxing资源
  • 在你的eclipse上创build一个Android项目
  • 删除main.xml
  • 右键单击“src”目录并点击导入。 按照提到的顺序浏览到以下目录。 在添加它们以便逐个导入时,请确保在导入向导的编辑字段中具有src目录。 而且您只select左侧目录树上的“com”目录。 不要selectsrc。
  • 核心
  • Android的整合
  • 安卓
  • 确保你的android sdk版本是9,更小,androidmanifest.xml会哭。
  • 其中一种语言的Strings.xml将crib,只是放在/字符之前

zxing 1.7(6月20日结帐)的android项目。

http://www.4shared.com/file/bFx8Y5Ys/zXingJune2010.html(NOT AVAILABLE ANYMORE

为什么使用外部库,当谷歌播放服务(自7.8.0版以来)包括一个条形码解码器。

更简单的方法。

只需在您的应用程序级别的gradle文件中包含依赖关系

 compile 'com.journeyapps:zxing-android-embedded:3.0.1@aar' compile 'com.google.zxing:core:3.2.0' 

在xml文件中定义一个button,然后在OnCreate()中的OnCreate()和OnClick侦听器的button

 new IntentIntegrator(this).initiateScan(); 

并在Java文件的OnCreate()之后写下代码

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if(result != null) { if(result.getContents() == null) { Log.d("MainActivity", "Cancelled scan"); Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show(); } else { Log.d("MainActivity", "Scanned"); st_scanned_result = result.getContents(); Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show(); } } } 

我最近使用谷歌手机视觉在iOS和Android。 我强烈build议使用Google Barcode Scan。 它对任何方向都非常敏感,处理时间相当快。 它被称为谷歌手机视觉。

条形码扫描仪API以任何方向实时检测条形码。 您也可以同时检测和parsing不同格式的几个条形码。

https://developers.google.com/vision/

https://codelabs.developers.google.com/codelabs/bar-codes/#0

我刚刚写了一个方法,它解码生成的条形码, Bitmap String

它确实正在请求,只是没有CaptureActivity

因此,可以跳过build.gradleandroid-integration库:

 dependencies { // https://mvnrepository.com/artifact/com.google.zxing compile('com.google.zxing:core:3.3.0') compile('com.google.zxing:android-core:3.3.0') } 

下面的方法(在jUnittesting中实际解码生成的条形码):

 import android.graphics.Bitmap; import com.google.zxing.BinaryBitmap; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.NotFoundException; import com.google.zxing.RGBLuminanceSource; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.Result; protected String decode(Bitmap bitmap) { MultiFormatReader reader = new MultiFormatReader(); String barcode = null; int[] intArray = new int[bitmap.getWidth() * bitmap.getHeight()]; bitmap.getPixels(intArray, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight()); LuminanceSource source = new RGBLuminanceSource(bitmap.getWidth(), bitmap.getHeight(), intArray); BinaryBitmap binary = new BinaryBitmap(new HybridBinarizer(source)); try { Result result = reader.decode(binary); // BarcodeFormat format = result.getBarcodeFormat(); // ResultPoint[] points = result.getResultPoints(); // byte[] bytes = result.getRawBytes(); barcode = result.getText(); } catch (NotFoundException e) { e.printStackTrace(); } return barcode; }