Pregunta

Estoy escribiendo esto en mera desesperación :) Me han asignado para hacer un escáner de código de barras independiente (como prueba de concepto) a un teléfono Android 1.6.

Para esto he descubierto la biblioteca ZXing.

He buscado en Google, leí temas relacionados aquí en StackOverflow usado Common Sence, etc. Nada parecía haber ayudado, y no puedo hacer un hoyo en este bloqueo mental:/

Sé que es posible, usar la lib y crear su propio escáner de código de barras independiente. He leído que usar el "escáner de código de barras" proporcionado por la gente de ZXing es, con mucho, la solución más fácil (a través de la intención). Desafortunadamente, esta no es una opción, y se desea una aplicación independiente.

Entonces, para resumir mi problema:

  1. ¿Cómo integrar ZXing Source lib en mi proyecto de código Android a través de Eclipse?
  2. Cuando está integrado ... ¿cómo hacer uso de LIB, para "cargar" la función de escaneo?
  3. Casi se prefiere una guía de paso a paso porque comencé a trabajar en Eclipse.

He intentado hacer que mi proyecto de código dependa de la carpeta Android de la carpeta de origen ZXing. Cuando lo hago, surgen un puñado de errores, principalmente en relación con 'org.apache' (??)

Simplemente no puedo resolverlo ... así que algunas pistas serían muy útiles.

De antemano, gracias :)

¿Fue útil?

Solución

¡ACTUALIZAR! - Guía resuelta +

He logrado resolverlo :) y abajo puede leer una guía paso a paso para que con suerte pueda ayudar a otros con el mismo problema que yo.

  1. Instale la hormiga apache - (Vea este video de YouTube para obtener ayuda de configuración)
  2. Descargue la fuente de Zxing de la página de inicio de Zxing y extraiga
  3. Con el uso de Windows Commandline (run-> cmd) navegue al directorio raíz del descargado zxing src.
  4. En la ventana de línea de comandos - escriba ant -f core/build.xml Presione Entrar y deje que Apache funcione es mágico [¿teniendo problemas?]
  5. Ingrese Eclipse -> Nuevo proyecto Android, basado en la carpeta Android en el directorio que acaba de extraer
  6. Haga clic con el botón derecho en la carpeta del proyecto -> Propiedades -> ruta de construcción de Java -> Biblioteca -> Agregar frascos externos ...
  7. Navegue a la carpeta recién extraída y abra el directorio principal y seleccione core.jar ... ¡Presione enter!

Ahora solo tiene que corregir algunos errores en las traducciones y el archivo AndroidManifest.xml :) Ahora puede compilar felizmente, y ahora tendrá una aplicación de escáner de código de barras independiente, basada en la fuente de ZXing;)

Chicos de codificación feliz, espero que pueda ayudar a otros :)

Otros consejos

Aquí hay una guía paso a paso sobre cómo generar y mostrar el código QR usando la biblioteca ZXing sin tener que instalar la aplicación de terceros. Nota: No tiene que construir ZXing con hormiga o cualquier otra herramienta de compilación. El archivo core.jar está disponible en el archivo zip lanzado (lea a continuación).

  1. Descargar el Último lanzamiento de ZXing. -- (ZXing-*.zip)
  2. Extraiga este archivo zip y encuentre core.jar por debajo core/ directorio.
  3. Si está utilizando Eclipse IDE, arrastre y suelte core.jar hacia libs Directorio de su proyecto Android. Cuando se le pide, seleccione Copiar.
  4. Copie las dos clases que se dan a continuación (Contents.java & QRCodeEncoder.java) al paquete principal de su proyecto Android.
  5. Crear un ImageView Elemento en su actividad para mostrar el código QR generado si aún no tiene uno. A continuación se da un ejemplo:
  6. Use el fragmento de código a continuación para generar el código QR en formato de mapa de bits y mostrarlo en un ImageView.

Aquí hay un ImageView elemento para agregar a su archivo de diseño de actividad archivo XML:

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

Fragmento de código:

// 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();
}

Aquí está 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
    };
}

Y 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 e.g. 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();
    }
}

los

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

Lamentablemente no funcionó para mí.

Esto es lo que funcionó para mí:

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

Encuentre el enlace aquí:https://github.com/journeyapps/zxing-nroid-embedded

¿Tiene problemas para construir con hormiga? Sigue leyendo

Si ant -f core/build.xmldice algo como:

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

Entonces establece tu JAVA_HOME Variable de entorno a la carpeta Java adecuada. Encontré herramientas. Jar en mi (para Windows):

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

Entonces configuré mi JAVA_HOME a:

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

La razón de la sintaxis más corta que encontré en algún sitio que dice:

"Se recomienda encarecidamente que elija un directorio de instalación que no incluya espacios en el nombre de la ruta (por ejemplo, no se instale en los archivos C: del programa). Si Java está instalado en dicho directorio, es fundamental establecer el Java_Home El entorno variable a una ruta que no incluye espacios (p. Ej.

Luego relanzé CMD (importante porque DOS Shell solo lee VAR Vars al iniciar, por lo que cambiar una VAR ENV requerirá que use un nuevo shell para obtener el valor actualizado)

y finalmente el ant -f core/build.xml trabajó.

Como algunas de las respuestas están desactualizadas, me gustaría proporcionar la mía -

Para integrar la biblioteca ZXing en su aplicación de Android como lo sugiere su wiki, debe agregar 2 archivos Java a su proyecto:

Luego en Android Studio Agregue la siguiente línea a Build.gradle expediente:

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

O si sigue usando Eclipse con ADT-Plugin agregar core.jar archivo al libbos Subdirectorio de su proyecto (aquí ventanas de pantalla completa y Mac de pantalla completa):

Windows screenshot

Finalmente, agregue este código a su 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();
}

La aplicación resultante solicitará instalar y iniciar Aplicación de escáner de código de barras por zxing (que volverá a su aplicación automáticamente después del escaneo):

Barcode Scanner app

Además, si desea construir y ejecutar el Aplicación de prueba de Zxing Como inspiración para su propia aplicación:

ZXing Test app

Luego necesita 4 archivos Java de Github:

  • BenchmarkActivity.java
  • Benchmarkasynctask.java
  • Benchmarkitem.java
  • Zxingtestactivity.java

Y 3 archivos jar de Repositorio maven:

  • core.jar
  • android-core.jar
  • Android Integration.Jar

(Puede construir los archivos jar usted mismo mvn package - Si está check out zxing desde github e instalar hormiga y aturdir herramientas en su computadora).

Nota: Si su proyecto no reconoce los archivos JAR, es posible que deba aumentar la versión Java en las propiedades del proyecto:

properties screenshot

Has visto la Wiki Pages ¿En el sitio web de Zxing? Parece que podrías encontrar Empezando, Developernotes y Escanningviaintent útil.

Poner

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

en sus dependencias de gradle. Tan fácil como eso. Antes de usar Android Studio y Gradle Build System.

Si solo necesita el core.jar de Zxing, puede omitir ese proceso y obtener los frascos preconstruidos del Página de wiki entrelazada

Último ZXing (2.2) no tiene core.jar en la carpeta de núcleo, pero puede obtener el nore.jar de la zxing Repositorio maven aquí

Paso a paso para configurar Zxing 3.2.1 en Eclipse

  1. Descargar zxing-Master.zip desde "https://github.com/zxing/zxing"
  2. Unzip Zxing-Master.zip, use Eclipse para importar el proyecto "Android" en ZXing-Master
  3. Descargue Core-3.2.1.jar desde "http://repo1.maven.org/maven2/com/google/zxing/core/3.2.1/"
  4. Cree la carpeta "LIBS" en el proyecto "Android" y pegue COR-3.2.1.Jar en la carpeta Libs
  5. Haga clic en el proyecto: elija "Propiedades" -> "Compilador Java" para cambiar el nivel a 1.7. Luego haga clic en el objetivo de compilación del proyecto "Android" Cambiar "a Android 4.4.2+, porque el uso de 1.7 requiere compilar con Android 4.4
  6. Si "CameraconfigurationUtils.java" no existe en "Zxing-Master/Android/App/Src/Main/Java/Com/Google/Zxing/Client/Android/Camera/". Puede copiarlo de "Zxing-Master/Android-Core/SRC/Main/Java/Com/Google/ZXing/Client/Android/Camera/" y pegar a su proyecto.
  7. Proyecto de limpieza y construcción. Si su proyecto muestra un error sobre "Switch - Case", debe cambiarlos a "si - else".
  8. Terminado. Proyecto de limpieza y construcción.
  9. Link de referencia: Uso de Zxing para crear una aplicación de escaneo de código de barras de Android

Intenté todas las formas posibles de lograr esto y luego descubrí la versión minificada de Xzing por JourneyApps. Lo he portado para Eclipse y compartido en GitHub.

Si está utilizando Eclipse, use este proyecto:-

https://github.com/hiteshsahu/xzing-barcode-scanner-minified-eclipse

Si está utilizando Studio, use este proyecto:-

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

Ventajas

  1. El escáner de código de barras incorporado en su aplicación no requiere instalar aplicaciones de terceros utilizando PlayStore.

  2. No necesita confundirse entre los frascos de Core, Android, etc., simplemente deje caer estos paquetes y diseños relevantes en su proyecto y está listo para comenzar. Solo el frasco requerido es com.google.zxing: Core: 3.2.0 de la cual puedes descargar

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

  3. No es necesario agregar toneladas de paquetes Ver imágenes a continuación para comparar

Antes :-

enter image description here

Después :-

enter image description here

  1. La parte más importante es que son altamente personalizable es decir. Puede agregar luz flash, usarla en fragmento y soportar el cambio de orientación.

  2. Puedes usar esta actividad de captura en Aplicación Cordova para escaneo de código de barras.

Su actividad de captura en App Manifest se vería así

  <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>

y el complemento se verá así

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");
            }
        }
    }
}

¡Feliz integración!

Los chicos de ZXing han facilitado la creación de un proyecto de Android con 1.7. No es tan doloroso como solía ser. Este es un blog rápido para cualquiera que desee crear un proyecto ZXing para Android rápidamente.

  • Consulte las fuentes de Zxing de zxing.org
  • Cree un proyecto de Android en su eclipse
  • Eliminar main.xml
  • Haga clic derecho en el directorio "SRC" y presione la importación. Explore los siguientes directorios en el orden mencionado. A medida que los agrega para importar uno por uno, asegúrese de tener el directorio SRC en el campo Editar del Asistente de importación. Y que seleccione solo el directorio "Com" en el árbol del directorio izquierdo. No seleccione SRC.
  • centro
  • Información de Android
  • androide
  • Asegúrese de que su versión SDK de Android sea 9, cualquier cosa menor y AndroidManifest.xml llorará.
  • Strings.xml en uno de los idiomas cunas, simplemente ponga un / antes del personaje

Un proyecto de Android para ZXing 1.7 (pago del 20 de junio).

http://www.4shared.com/file/bfx8y5ys/zxingjune2010.html (NO DISPONIBLE NUNCA MÁS)

Por qué usar una lib externa, cuando Google Play Service (desde la versión 7.8.0) incluye un decodificador de código de barras.

Acabo de escribir un método, que decodifica los codos de barras, Bitmap a String.

Hace exactamente lo que se solicita, solo sin el CaptureActivity...

Por lo tanto, uno puede omitir el android-integration biblioteca en el build.gradle :

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')
}

El método como lo siguiente (que en realidad decodifica los codificaciones de barras, dentro de una prueba JUnit):

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;
}

Recientemente he usado Google Mobile Vision en iOS y Android. Recomiendo usar Google Barcode Scan. Es bastante receptivo con cualquier orientación y tiempo de procesamiento es bastante rápido. Se llama Google Mobile Vision.

La API del escáner de código de barras detecta códigos de barras en tiempo real en cualquier orientación. También puede detectar y analizar varios códigos de barras en diferentes formatos al mismo tiempo.

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

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

Enfoque mucho más fácil.

Solo incluya la dependencia en el archivo de gradle de su nivel de aplicación

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

Defina un botón en su archivo XML y escriba el código a continuación en el archivo Java en onCreate () y dentro del oyente de OnClick del botón

new IntentIntegrator(this).initiateScan();

Y escriba el código a continuación después de OnCreate () del archivo Java

@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");
            String st_scanned_result = result.getContents();
            Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();

        }
    }

}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top