Tutorial : Scanner et générer des codes QR (2D) sur Android
Par Florent le vendredi 17 avril 2009, 06:00 - Tutorial - Lien permanent
Vous
avez une idée d’application s’appuyant sur les codes QR ? ZXing vous permettra
de la réaliser (presque) sans effort !
En effet, l’une des principales forces d’Android est de pouvoir réutiliser des fonctionnalités déjà implémentées par des applications existantes. Le principe est de créer des objets Intent qui vont cibler l’application implémentant la fonction qui nous intéresse, éventuellement de lui passer des paramètres (méthode «putExtra») et de faire appel à l’activité capable de répondre à ce besoin en utilisant «startActivityForResult». Cette dernière renverra une réponse sous forme d’un objet Intent passé en paramètre à «onActivityResult». Je ne m’étenderai pas plus à ce sujet (plus d’infos ici: http://developer.android.com/guide/topics/fundamentals.html#actcomp).
Le projet ZXing (se prononce «Zebra Crossing») est un ensemble de bibliothèques et d’applications de lecture de code-barres visant un large spectre de plateformes : Java SE /Java ME, C++, C#, iPhone, Blackberry, … et bien sûr Android :).
L’ensemble du projet est à télécharger à cette adresse:
Les scripts Ant vous permettront de générer une version optimisée de l’application :
Pour cela, vous aurez besoin de Ant (http://ant.apache.org) et de Proguard (http://sourceforge.net/project/showfiles.php?group_id=54750&package_id=49483). Dézippez l’archive de proguard et copier-collez «lib\proguard.jar» dans «bin».
Puis dans le répertoire de ZXing, d’abord dans «core» qui contient les fonctions de reconnaissance/génération des codes-barres :
ant -f build.xml build-no-debug
Dans «android» :
ant -f build.xml -Dandroid-home=«racine du SDK android» -DWTK-home=«racine du répertoire de proguard»
Lancez l’émulateur («android SDK»\tools\emulator). Et finalement, installez l’application avec la commande suivante :
ant -f build.xml install -Dandroid-home=«racine du SDK android»
Vous devriez alors trouver une application «Barcode Scanner» dans l’émulateur.
Vous ne pourrez malheureusement pas la tester pleinement dans l’émulateur (Nous vous apprendrons dans un autre billet à utiliser une Webcam depuis l’émulateur), mais sachez que cette application est capable de partager vos contacts/favoris via code QR, rechercher des produits grâce à leur code-barre, etc.
Maintenant créez un nouveau projet Android, changez le layout main.xml:
-
<?xml version="1.0" encoding="utf-8"?>
-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-
android:orientation="vertical"
-
android:layout_width="fill_parent"
-
android:layout_height="fill_parent"
-
>
-
<Button
-
android:id="@+id/scanButton"
-
android:layout_width="fill_parent"
-
android:layout_height="wrap_content"
-
android:text="Click to scan"
-
/>
-
</LinearLayout>
Et remplacez le code de votre activité par:
-
private static final int REQUEST_SCAN = 0;
-
-
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.main);
-
Button btScan = (Button) this.findViewById(R.id.scanButton);
-
btScan.setOnClickListener(btScanListener);
-
}
-
-
private Button.OnClickListener btScanListener = new Button.OnClickListener() {
-
public void onClick(View v) {
-
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
-
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
-
-
-
try {
-
startActivityForResult(intent, REQUEST_SCAN);
-
} catch (ActivityNotFoundException e) {
-
Toast.makeText(Main.this, "Barcode Scanner ne semple pas être installé", 2000).show();
-
}
-
}
-
};
-
-
public void onActivityResult(int reqCode, int resCode, Intent intent) {
-
if (REQUEST_SCAN == reqCode) {
-
if (RESULT_OK == resCode) {
-
String contents = intent.getStringExtra("SCAN_RESULT");
-
Toast.makeText(this, "Succès : " + contents, 2000).show();
-
} else if (RESULT_CANCELED == resCode) {
-
Toast.makeText(this, "Scan annulé", 2000).show();
-
}
-
}
-
}
-
-
Lancez votre projet dans l’émulateur, cliquez sur le bouton, puis à défaut de pouvoir scanner, appuyez sur le bouton «Back», le message «scan annulé» devrait alors s’afficher, nous indiquant que «Barcode Scanner» nous a bel et bien renvoyé un résultat.
L’aspect visuel n’est certes pas spectaculaire, mais constatez que notre application n’a aucune dépendance en terme de code vis-à-vis de «Barcode Scanner», ce qui est topissime !
Si Barcode Scanner n’est pas présent dans l’émulateur, alors l’exception ActivityNotFoundException est levée. Une classe IntentIntegrator (http://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentIntegrator.java) est à votre disposition pour générer l’Intent de scan qui vous permet de réduire le code émettant une Intent à:
IntentIntegrator.initiateScan(Main.this);
De plus, cette méthode propose le cas échéant de télécharger Barcode Scanner depuis la Marketplace Android (ne fonctionne que sur un vrai téléphone).
Pour générer un code QR, l’Intent à créer est la suivante:
Intent intent = new Intent("com.google.zxing.client.android.ENCODE");
intent.putExtra("ENCODE_DATA", “votre message”);
intent.putExtra("ENCODE_TYPE", "TEXT_TYPE");
Les types de contenu que vous pouvez encoder sont dans la classe com.google.zxing.client.android.Contents.Type.
Vous trouverez les sources complètes de ma démo ici : http://code.google.com/p/example-zxing/source/checkout
Commentaires
Slt,
J'ai un problème de compilation sur : ant -f build.xml build-no-debug
D:\Android\apache-ant-1.7.1\bin>ant -f D:\Android\zxing\core\build.xml
Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre6\li
b\tools.jar
Buildfile: D:\Android\zxing\core\build.xml
clean:
[delete] Deleting directory D:\Android\zxing\core\build
build:
init:
compile:
[mkdir] Created dir: D:\Android\zxing\core\build
[javac] Compiling 123 source files to D:\Android\zxing\core\build
BUILD FAILED
D:\Android\zxing\core\build.xml:53: The following error occurred while executing
this line:
D:\Android\zxing\core\build.xml:36: Error running javac.exe compiler
Total time: 2 seconds
Aurais-tu une idée ?
Merci
Source inutile car pas de réponses lors de commentaires et surtout rien ne fonctionne, à oublier
Savez vous ou je peux trouver un tutorial valide pour adapter le lecteur de codes de barre sous android a une application
Merci
Merci pour ce tuto mais je bloque à la compilation de android :
ant -f build.xml -Dandroid-home=«racine du SDK android» -DWTK-home=«racine du répertoire de proguard»
J'ai bien remplacé par les bons chemins et j'obtiens l'erreur suivant : Unable to resolve target 'Google Inc.:Google APIs:4'
à la ligne 75
Merci
Personne n'est là ? Dommage le tuto était bien rédigé !
@Jay_Elco, Es-ce que ton java est bien installé ?
@Montspy, Il faut que tu crée des targets (Profil matériel d'un téléphone android qui la version du sdk, les spécificités matièrielle). Il faut soit que tu en crée un qui se nome "Google Inc.:Google APIs:4" qui contient le SDK version 4 (Android 2.0) avec les APIs Google ou alors tu modifie le fichier build.xml pour mettre le nom que tu as définie.
Bonjour patou,
La target "Google Inc.:Google APIs:4" se créée dans le build.xml?
comment y associer le SDK v4?
La properties android-home ne sert pas à la même chose?
merci !
Ca y'est j'y suis ;o)
C'est la target pour un 'device', je l'ajoute sous eclipse avec le "Android SDK and AVD Manager"
@patr2is Exactement, c'est la configuration d'un profil matériel donné avec le sdk 4 et les bibliothèques Google.
bonjour, quant je telecharge le code avec hg
hg clone https://example-zxing.googlecode.co... example-zxing
j'ai un projet vide (toto.java)
ou puis-je telecharger le code svp
un grand merci
bonjour,
comment je peux recuperer le contenu de 1 er taost qui s'affche qui indique si (URL,Produit,Text,etc).
merci d'avance
Excellent post. It makes me realize the energy of words and pictures. I learn a lot, thank you! Wish you make a further progress in the future.
http://www.moncler2012vestes.com/mo... MONCLER veste femmes
http://www.moncler2012vestes.com/mo... MONCLER veste hommes
http://www.moncler2012vestes.com MONCLER veste
http://www.moncler2012vestes.com moncler hommes
http://www.moncler2012vestes.com MONCLER
Hey man Very inspiring article. basicall,I am a .Net programmer. But earlier I I wanted to be a system programmer. But I could not succeeded in that field. When I read this article It inspire me about system programming. Please provide me good site where I could read such articles.
worshiped stones brindle with authorization in story of Cartier watches is a share of admirable and admired. The Tankissime tends to brand more than the <a href="http://www.rolexsreplica.co.uk">rolex replica uk</a> choosing. If you do not separate what brand of watches to elect, you can elect Breitling dupe watches. Not barely are the cheapest honorarium, but <a href="http://www.ukrolexreplicass.org.uk">swiss rolex</a> What all over Rolex Day-Date? This model is rightly regarded as one of the most clever models of Rolex watches. If you've not ever extraordinary a <a href="http://www.wholesalebeadss.com">wholesale beads</a> are at ones disposal today in photocopy watches.It is widely known that Switzerland is exceptionally amateur in both the reach and breadth of scads <a href="http://www.designerhandbagsforsale....">Designer Handbags</a> This sort of sports watches, you may not have on the agenda c trick to upset that they would be recognized near others in spite of not thriving to put the <a href="http://www.replica0watches.org.uk">swiss replica watches</a> If you after to allow a Tag Heuer Replica Watch, it is despotic that you understand the annals of TAG Heuer watches. Living in modern people, all and <a href="http://www.rolexsreplica.co.uk">rolex replicas</a> scold. Now, I found that is facsimile watches is as a matter of fact an quiet constituent to engage in. Compared with other products, likeness watches <a href="http://www.replicasonline.org.uk">uk replica watches</a> Precise approach and excellent a battering purloin turn out these watches rubber-coated copy watches are boss.With the development of facts and <a href="http://www.replica0watches.org.uk">replica watches</a> success in watch-making field, it never stopped adopting advanced technology and creating new models to its fans due to the competition among those <a href="http://www.designerhandbagsforsale....">Designer Handbags</a> lone click from any other corner of the soil. This has allowed likely customers to swallow things of their prize and circulate 100% compensation of <a href="http://www.designerhandbagsforsale....">Cheap Handbags</a> effective and healthful. A likeness is observed in a traditional design and the design belongs to its stable elongated tradition and offers alike <a href="http://www.fakecheapbagshandbags.co...">cheap handbags</a> IWC watches are valued around people in multitudinous professions that make unmixed explicit, and pre-eminently nigh pilots who foster the reliability of <a href="http://www.replicasonline.org.uk">replica watches</a> suitable most puny lido, not all and sundry has the know-how to onset respecting that.The a knock-off has a to some degree cheaper than can be <a href="http://www.hermesreplicabagshandbag...">replica hermes</a> out less capital repayment for replicas of these. A look after copy frequently we only costs 200 $ 400, while a true can get individual thousand <a href="http://www.wholesalebeadss.com">bead supplies</a> prune the other 7 in criminal ceramic. Two fixed rings 18 karat fair-skinned gold with round diamonds-low. Marked influence ivory sunlight hollowware. <a href="http://www.rolexsreplica.co.uk">rolex replica</a> pre-eminent juxtaposing. Therefore, it is merit their investment. The take advantage of of these distinguished watches during unparalleled occasions, <a href="http://www.designerhandbagsforsale....">Cheap Designer Handbags</a> for. Sellers of forgery Rolex watches chance to circumvent on the clock as an creative put together.As manufacturers of reproduction Rolex watches, <a href="http://www.ukrolexreplicass.org.uk">replica rolex</a> the actually that carbon copy watches are remarkably habitual in the modern superstore nigh hundreds of thousands of search results. The largest <a href="http://www.ukrolexreplicass.org.uk">swiss rolex</a>
A great post but How to select a cool handbags. we sell cheap handbags We are the best store provided various cheap designer handbags but only a little white to make coach handbags online http://www.xtruereligionoutlet.com
Great.I will continue to pay attention to your article.