Question

J'écris ceci dans le désespoir simple :) J'ai été affecté à faire un scanner de codes à barres autonome (comme une preuve de concept) à un téléphone Android 1.6.

Pour cela, je l'ai découvert la bibliothèque ZXing.

J'ai googlé, lisez des sujets connexes ici sur StackOverflow utilisés commun et donc sence de suite. Rien ne semblait avoir aidé, et je ne peux pas percer un trou sur ce blocus mentale: /

Je sais qu'il est possible, d'utiliser le répertoire lib, et créez votre propre scanner de code à barres autonome. J'ai lu que l'utilisation du « Barcode Scanner » fourni par les gens ZXing, est de loin la solution la plus simple (par intention). Malheureusement, ce n'est pas une option, et une application autonome est souhaitée.

Donc, pour résumer mon problème:

  1. Comment intégrer la source ZXing lib dans mon projet de code Android par Eclipse?
  2. Une fois intégré ... comment utiliser la lib, pour « charger » la fonction de balayage?
  3. Une étape de guide étape est presque parce que je viens préféré de travail a commencé dans Eclipse.

J'ai essayé de faire mon projet de code dépendant du dossier Android du dossier source ZXing. Quand je le fais, une erreur de Handfull émergent, principalement en ce qui concerne 'org.apache' (??)

Je ne peux pas comprendre ... donc quelques conseils seraient plus utile.

Par avance, je vous remercie:)

Était-ce utile?

La solution

Mise à jour! - RESOLU + GUIDE

J'ai réussi à le découvrir :) Et en bas, vous pouvez lire le guide étape par étape afin qu'il espère pouvoir aider les autres avec le même problème que j'avais;)

  1. Installer Apache Ant - ( Voir cette vidéo YouTube à l'aide de config )
  2. Télécharger la source ZXing de la page d'accueil ZXing et l'extraire
  3. Avec l'utilisation de Windows Commandline (Run-> CMD) Accédez au répertoire racine du zxing src téléchargé.
  4. Dans la fenêtre de ligne de commande - Type ant -f core/build.xml appuyez sur Entrée et laisser le travail Apache, il est magique [ avoir des problèmes? ]
  5. Entrez Eclipse -> nouveau projet Android, basé sur le dossier android dans le répertoire que vous venez d'extraire
  6. Faites un clic droit dossier de projet -> Propriétés -> Chemin de génération Java -> Library -> Ajouter des fichiers JAR externes ...
  7. Accédez au dossier nouvellement extrait et ouvrez le répertoire de base et sélectionnez core.jar ... appuyez sur Entrée!

Maintenant, il vous suffit de corriger quelques erreurs dans les traductions et le fichier AndroidManifest.xml :) Maintenant, vous pouvez compiler avec plaisir, et vous allez maintenant avoir une application du scanner de codes à barres autonome de travail, en fonction de la source ZXing;)

Heureux de codage gars - je l'espère, il peut aider les autres:)

Autres conseils

Voici un guide étape par étape sur la façon de générer et afficher QR code en utilisant la bibliothèque ZXing sans avoir à installer l'application tierce. Remarque: vous ne devez pas construire ZXing avec ANT ou tout autre outil de construction. Le core.jar de fichier est disponible dans l'archive zip publié (lire ci-dessous).

  1. Télécharger dernière version de ZXing. - (ZXing-*.zip)
  2. décompressez l'archive zip et trouver core.jar sous le répertoire core/.
  3. Si vous utilisez Eclipse IDE, glisser-déposer core.jar dans le répertoire libs de votre projet Android. Lorsqu'on lui a demandé, sélectionnez Copier .
  4. Copiez les deux classes données ci-dessous (Contents.java & QRCodeEncoder.java) au paquet principal de votre projet Android.
  5. Créer un élément ImageView dans votre activité pour afficher le code généré QR si vous ne l'avez pas déjà. Un exemple est donné ci-dessous:
  6. Utilisez le extrait de code ci-dessous pour générer le code QR au format Bitmap et l'afficher dans un ImageView.

Voici un élément ImageView ajouter à votre mise en page Activité fichier XML:

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

Extrait de code:

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

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

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

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

n'a malheureusement pas de travail pour moi.

est ce qui a fonctionné pour moi:

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

S'il vous plaît trouver le lien ici: https://github.com/journeyapps/zxing-android-embedded

Vous rencontrez des problèmes avec la construction ANT? Continuez à lire

Si ant -f core/build.xml dit quelque chose comme:

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

puis définissez votre variable d'environnement JAVA_HOME dans le dossier java approprié. J'ai trouvé dans mon tools.jar (pour Windows):

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

donc je mis mon JAVA_HOME à:

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

la raison de la syntaxe plus courte que je trouve à un emplacement qui dit:

"Il est fortement conseillé que vous choisir un répertoire d'installation ne comprend pas d'espaces dans le chemin nom (par exemple, ne pas installer dans C: \ Program Files). Si Java est installé dans le répertoire un tel, il est critique pour définir la JAVA_HOME variable d'environnement à un chemin qui ne tiennent pas compte des espaces (par exemple, C: \ Progra ~ 1); manquement à cette volonté entraîner des exceptions lancées par certains programmes qui dépendent de la valeur de JAVA_HOME. "

Je relancée cmd (importante car shell DOS ne lit que env vars lors du lancement, en changeant donc une var env vous demandera d'utiliser un nouveau shell pour obtenir la valeur actualisée)

et enfin le ant -f core/build.xml travaillé.

Je voudrais fournir Puisque certaines des réponses sont dépassées, mon -

Pour intégrer la bibliothèque ZXing dans votre application Android comme suggéré par leur Wiki , vous devez ajouter 2 fichiers Java à votre projet:

Ensuite Android Studio Ajouter la ligne suivante à build.gradle fichier:

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

Ou si vous utilisez toujours Eclipse avec le plugin ADT- core.jar fichier pour libs sous-répertoire de votre projet (ici plein écran de Windows et rel="noreferrer"> plein écran):

Windows capture d'écran

Enfin ajouter ce code à votre Barcode Scanner application par ZXing (qui retournera à votre application automatiquement après la numérisation):

Barcode Scanner app

En outre, si vous voulez construire et exécuter le ZXing test app comme source d'inspiration pour votre propre application:

ZXing app Test

Ensuite, vous avez besoin de 4 fichiers Java à partir de GitHub :

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

3 fichiers Jar de Maven dépôt :

  • core.jar
  • android-core.jar
  • android-integration.jar

(Vous pouvez construire les fichiers JAR vous-même avec mvn package - si votre chèque ZXing de GitHub et installer ant et maven outils à votre ordinateur).

Note: si votre projet ne reconnaît pas les fichiers JAR, vous devrez peut-être la version Java dans les propriétés du projet:

propriétés Capture d'écran

Avez-vous vu les pages wiki sur le site ZXing? Il semble que vous pourriez trouver GettingStarted , DeveloperNotes et ScanningViaIntent utile.

Mettre

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

dans vos dépendances Gradle. Aussi facile que cela. Avant d'utiliser Android Studio système de construction Gradle.

Si vous avez juste besoin core.jar de ZXing, vous pouvez sauter ce processus et obtenir les fichiers JAR pré-construit à partir de la La page de GettingStarted

Dernières ZXing (2.2) n'a pas core.jar sous le dossier de base, mais vous pouvez obtenir le core.jar de la ZXing dépôt Maven

étape par étape pour la configuration ZXing 3.2.1 dans Eclipse

  1. Télécharger zxing-master.zip de « https://github.com/zxing/zxing «
  2. Décompressez zxing-master.zip, utiliser Eclipse pour importer "android" projet ZXing-maître
  3. Télécharger core-3.2.1.jar de « http://repo1.maven.org/maven2/com/google/zxing/core/3.2.1/ "
  4. Créer "libs" dossier dans le projet "Android" et collez-cor 3.2.1.jar dans le dossier libs
  5. Cliquez sur le projet: choisissez « Propriétés » -> « compilateur Java » pour changer le niveau de 1,7. Cliquez ensuite sur « Android » changement « cible build projet » android 4.4.2+, parce que l'utilisation 1.7 nécessite la compilation avec Android 4.4
  6. Si "CameraConfigurationUtils.java" n'existe pas dans "ZXing-maître / android / app / src / main / java / com / google / ZXing / client / android / appareil photo /". Vous pouvez le copier à partir de "ZXing-maître / android-core / src / main / java / com / google / ZXing / client / android / appareil photo /" coller à votre projet.
  7. propre et projet de construction. Si votre erreur show projet de « switch - cas », vous devez les changer pour « si - autre ».
  8. Terminé. projet de nettoyage et de construction.
  9. lien Référence: Utiliser ZXing pour créer une application android code à barres à balayage

J'ai essayé tous les moyens possibles pour y parvenir et je découvre la version minified de xZing par JourneyApps. Je l'ai porté que pour eclipse et partagé sur GitHub.

Si vous utilisez une utilisation éclipse ce projet: -

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

Si vous utilisez ce projet avec Studio: -

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

Avantages

  1. Inbuilt scanner de codes à barres dans votre application ne pas besoin d'installer des applications tierces en utilisant Playstore.

  2. Vous ne avez pas besoin de se confondre entre le noyau, client Android pots etc suffit de déposer ce colis et mises en page relevent dans votre projet et vous êtes bon pour aller. Pot uniquement requis est com.google.zxing: Noyau: 3.2.0 que vous pouvez télécharger à partir de

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

  3. Pas besoin d'ajouter des tonnes de paquets voir images ci-dessous pour la comparaison

Avant: -

Après: -

  1. La partie la plus importante est qu'ils sont hautement personnalisable à savoir. vous pouvez ajouter de la lumière flash, l'utiliser dans le fragment et le soutien changement d'orientation.

  2. Vous pouvez utiliser cette activité de capture Cordova App scanneing de codes à barres.

votre activité de capture dans le manifeste d'application ressemblerait à ceci

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

et le plugin ressemblera à ceci

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

Happy intégration !!

Les gars ZXing ont rendu plus facile de créer un projet Android avec 1,7. Ce ne est pas aussi douloureux que cela était. Ceci est un blog rapide pour tous ceux qui souhaitent créer un projet ZXing pour android rapidement.

  • Commander les sources ZXing de zxing.org
  • Créer un projet Android sur votre éclipse
  • Supprimer main.xml
  • Faites un clic droit sur le répertoire « src » et l'importation hit. Parcourir les répertoires suivants dans l'ordre indiqué. Comme vous les ajoutez pour une importation par un, assurez-vous que vous avez le répertoire src dans le champ d'édition de l'assistant d'importation. Et que vous sélectionnez uniquement le répertoire « com » sur l'arborescence à gauche. Ne sélectionnez src.
  • core
  • android-intégration
  • Android
  • Assurez-vous que votre version android sdk est 9, quoi que ce soit moins et AndroidManifest.xml pleurera.
  • strings.xml dans l'une des langues sera crèche, il suffit de mettre un / avant le « caractère

Un projet Android pour ZXing 1.7 (caisse 20 Juin).

http://www.4shared.com/file/bFx8Y5Ys/zXingJune2010 .html ( ne sont plus disponible )

Pourquoi utiliser un lib externe, lorsque Google services de jeu (depuis la version 7.8.0 ) comprend un décodeur de codes à barres.

Je viens d'écrire une méthode, qui décode généré des codes-barres, Bitmap à String.

Il fait exactement ce qui est demandé, juste sans CaptureActivity ...

Par conséquent, on peut sauter la bibliothèque android-integration dans le 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')
}

Le procédé suivant (qui décode effectivement des codes à barres générés, dans un test 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;
}

J'ai récemment utilisé Google vision mobile dans les deux ios et android. Je recommande fortement d'utiliser Google de numérisation de codes à barres. Il est assez réactif avec une orientation et le temps de traitement est assez rapide. Il est appelé Google Mobile Vision.

L'API Barcode Scanner détecte les codes-barres en temps réel dans toute orientation. Vous pouvez également détecter et analyser plusieurs codes-barres dans différents formats en même temps.

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

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

Much Easier approach.

Just include dependency in your app level gradle file

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

Define one button in your xml file and and write below code in Java file in OnCreate()and inside the OnClick listener of button

new IntentIntegrator(this).initiateScan();

And write below code after OnCreate() of the Java file

@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();

        }
    }

}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top