Android barcode scanner in 6 lines of Python code

After my last video about using a barcode scanner to add and search books in your library, I was feeling pretty happy. Bar code scanners are pretty cheap–mine cost about $65. But then Google released the Android Scripting Environment (ASE) and it turns out that you don’t even need a bar code scanner. Instead, you can use an Android phone such as the G1.

Just as a proof-of-concept, here’s a barcode scanner written in six lines of Python code:

import android
droid = android.Android()
code = droid.scanBarcode()
isbn = int(code[‘result’][‘SCAN_RESULT’])
url = “” % isbn
droid.startActivity(‘android.intent.action.VIEW’, url)

Thanks to fellow Googler Vijayakrishna Griddaluru for sending me this sample code. Visiting the resulting url offers the option to add that book to your library:

Android bar code scanner

Pretty easy, huh? You can read all about the new scripting environment. Not only can you scan bar codes, you can use text-to-speech, make phone calls, send text messages, read sensor data, and find your location–all from easy scripts. One person wrote a script to go into silent mode when the phone is placed screen-down on the table. It took less than 20 lines of code, and that’s including comments!

The Android Scripting Environment should make fun projects even easier. Brad Fitzpatrick wrote about using his Android phone to open his garage door automatically when his motorcycle gets close to home. Now those sorts of projects are even easier to write. 🙂

52 Responses to Android barcode scanner in 6 lines of Python code (Leave a comment)

  1. Hmmm, perhaps I should add an iPhone to my shopping list instead of that barcode scanner you recommended, eh Matt? Can I tell my wife you’re in favour of this purchase?! 😀

  2. That is very cool, I can’t wait to try this!!

  3. Not only can you scan bar codes, you can use text-to-speech, make phone calls, send text messages, read sensor data, and find your location–all from easy scripts.

    “make phone calls” are you mad 😉

  4. text-to-speech is cool, but I much prefer speech-to-text on cellphones.

    Any S60 apps you know of Matt? I mean, Symbian is the Linux of the mobile world. You must be interested in that OS as well.

  5. Android phone becoming more useful compare to iPhone, the applications are more industrialized. I salute the Android developer for this.

  6. hate to say admit it – but seriously tempted by an Android, after the #o2fail pricing of the new iPhone, its great but I am a poor broke SEO bloke with a family …

    Excellent that I can get my hands ‘mucky’ enough without breaking it …

  7. 6 lines of Python backed by a STRONG built in API!

    Without the heavy lifting of having :
    built in, it definitely would be a much different proof of concept.

    I’m with Gerry on the iPhone, absolutely love it, but 1) AT&T (on this side of the pond) really shot themselves in the foot with their $499/$699 pricing and 2) Trying to code for the iPhone is like trying to learn Chinese from a cow.

  8. Gotta say that I’m looking forward to this: It’s going to be really useful to write quick scripts, rather than having to take on the Android SDK, since testing even very basic applications is ridiculously laborious when you’re only running a Linux netbook.

    That said, I only bought a G1 a week or so ago, and aside from the usual battery issues (for which I’ve already ordered a larger battery), I’m noticing that I’m getting multiple issues with freezing and rebooting, sometimes just after loading the OS; I’m fairly sure it’s an app or widget I’m using causing it, since booting into Safe Mode seems to alleviate any problems, but since there seems to be no obvious form of logging or system monitoring apps available through the OS, it’s impossible to tell which might be the cause without individually removing each app, or making a clean start, then reinstalling each app one by one and testing each time.

    I don’t suppose you, or any of your readers have any tips for tracking down the cause of my woes? It’d be nice to have a stable phone before I start working on scripts 🙂

  9. When I saw your post about the barcode scanner I thought to myself, there has got to be a way to get my G1 to do this. It has all sorts of other barcode scanning applications.

    To those above excited about the iphone pricing, I got my G1 from T-mobile for $99 with a 2 year commitment. I think you may have to be a new customer, but we easily talked the guy at the mall into coming down $150. You just have to be willing to haggle. And if the T-mobile store you go to tells you no, try an independent reseller at a kiosk.

    I can’t say enough good things about my G1, though. I’ve played with the iphone, and you couldn’t get me to switch. 🙂

  10. Matt,

    So when are you going to get to the post where Android writes the books for me and I can retire? That’s what I call displacement technology:-)


  11. I like the bar code scanner app for the iphone, I wind up using it at best buy.

  12. Damn. Cool.

    Not as cool as the garage door opening automagically, but… Damn.

  13. Any chance that tech will come to the iPhone soon?

  14. seems its time to buy G1 now :)) and start using bar code applications

  15. This only emphasizes my point from a blog article I wrote: In the future everybody develops…

  16. Ralph Corderoy

    Does this work with those ISBN barcodes that end in an `X’ rather than a digit? Only I note you’re using `%d’ as a format specifier for the Google URL.

  17. Some guys have used the Barcode reader built into android (I believe it’s the zxing library) to scan barcodes in to Beep My Stuff (, disclaimer, I coded and run BMS). I don’t think it’s in the app store yet but the code is open source

  18. “Symbian is the Linux of the mobile world”

    Symbian is not Linux.

    Android is closest to Linux.
    iPhone has a *nix heart (BSD).

    Symbian is it’s own thing. And the hardest of the 3 to program for. But it’s been around a very long time.

  19. I wouldn’t try to coerce it to an integer — you’re using it as an unmodified string value.

    isbn = int(code['result']['SCAN_RESULT'])
    url = “” % isbn

    If you had an exception handler, I suppose it might make some sense. Anyways, knock that “6 lines” down to 5. 🙂

  20. Yea, go buy an G1 so you can buy more things “more easy”. I would like to see Intel’s OpenCV (Computer Vision) API implemented on the Android. So you could put your face on a Muscle Man or a Seal or something… Sony Camcorder style.

  21. that code doesn’t tell me much those are all encapsulated functions. Since I renewed my site with Google apps, it has been giving me hell. not showing up in SERP’s then reappearing like nothing. then saying that the site has expired, then going back to normal. now its sending me to a godaddy parked free page.

    the site is a solid music blog

  22. My friend has one and he loves it. Runs all kinds of crazy stuff on it. I’d love to get one as well. Alex, thats pretty weird. Having the same issue for my main term, there one day gone the next. Perhaps Matt could enlighten us?

  23. I’ve been in technology and business for about 20 years now, and I love how new technologies continually appear. There is always something getting faster and better yet cheaper, and there is always someone finding a new way to apply it. Gotta love that!

  24. Totally off subject, but I read an article that Google is looking at Twitter and may even display twitter returns in the serps.

    If that’s true, all I’ve got to say is “are you kidding me”?

    Many people, myself included would not like to search through useless 140 posts by narcissistic people when I’m looking for something. If I did, I would go to Twitter and search.

    If Google does this, you will be playing right into the hands of MS. I’ll stop using Google as I’m sure many others who find Twitter useless will.

  25. Looking forward to trying this out! Thanks Matt

  26. Is it possible to access the Speech Recognition engine in a similar manner using ASE? Specifically “RecognizerIntent”?

  27. It’s pretty oversized. Let’s start with removing the useless formatting code
    import android
    droid.startActivity(’android.intent.action.VIEW’, url)
    We still have some useless assignments
    import android
    droid.startActivity(’android.intent.action.VIEW’, “”+android.Android().scanBarcode()[‘result’][‘SCAN_RESULT’])
    Well, we still have an import. Let’s make it into a nice oneliner.Nathan
    droid.startActivity(’android.intent.action.VIEW’, “”+__import__(‘android’).Android().scanBarcode()[‘result’][‘SCAN_RESULT’])

  28. Wow, Nathan, you took an easily comprehensible script and turned it into a real mess. Missing the entire point of writing a script. Congrats. Please stay away from all code in the future.

  29. HI,
    Can someone post the complete working sample code of using the same script above for scanning the barcode

  30. I get a syntax error on line 2:
    Syntax error: “(” unexpected

    I also get “import: permission denied” just before that.

    Any ideas?

  31. I cannot make these six lines of code working.. It alwas comes with a syntax error for the isbn that says something about a tuple. I’m using ZXing’s barcode scanner.. is that the problem?

  32. Not able to start an activity.
    I have followed the same code.

  33. can anyone tell how to start an simple activity ?

  34. This is what worked for me:
    I have installed XZing barcode scanner from marked.

    Then I have this python code:

    import android

    droid = android.Android()

    (id, result, error) = droid.scanBarcode()

    isbn = int(result['SCAN_RESULT'])

    url = "" % isbn


    And it works! THANK YOU for this AWSOME POST!

  35. hmm.. a new bug… my browser
    Problem is that my browser do not work correctly at .. When I add the book to a shelf it’s not really done though I’ve pressed save…
    I don’t believe that this is something that ASE can bypass..

  36. Okay.. this is not a six line code. But I am totally new at coding..

    From the six lines and the ASE API about Android I have made this 77 lines code that will allow you to scan books without starting the application all the time.

    You can find the code here :

    Know it can be short and prettier, but I think it has a good layout that explains everything.

    If you can help me debug how to get the sendMail() working it would be awsome.

  37. Here’s what I’ve got now. Nothing above was working for me, and I figured it was the result of the scanBarcode function call, and I was right (see fix below). I’m on an HTC Incredible, and on Android 2.1. I hope this helps someone down the line:
    import android
    droid = android.Android()
    (id, result, error) = droid.scanBarcode()
    isbn = int(result[‘extras’][‘SCAN_RESULT’])
    url = “” % isbn

  38. hmm.. don’t know what happend at pastebin…
    you can download the script to your phone from this link:

  39. Some things that helped me get it working.

    #1 I had to have the interpreter set to Python. Change it by going to Menu > View > Interpreters hit the menu button again to add Python.

    Somehow in the mad copying and pasting that I was doing, some things got erased. Go through and double check to make sure everything’s there.

    I ended up using Carl M’s code and changing the url to a different url, but it works perfectly for me on a Droid running 2.2 after about an hour of tinkering.

    Thanks for the article!

  40. The original version failed to work for me, a complaint about using a string as an index for a tuple. The versions suggested by Carl M and Lasse Nørfeldt work for me… this may have something to do with the way particular barcode applications return their information?

    Does anyone know if there is a URL parameter for adding a book straight to your Google library?

  41. I’ve expanded on your script to allow adding the books automatically to your library through the gdata.books API. It isn’t quite 6 lines any more but it is still pretty simple.


  42. Okay, so here’s my question…..I’ve been wondering if anyone made a scanner or application for phones that would scan a bar code of a book and tell you that you had already read or bought this book. I cannot tell you how many times I have bought the same book, because they’ve brought it out again, but in a new cover!!!! My mother, who’s 80 and her friends are also curious about this. It has to be simple, though. I’ve been reading about the other phones that will scan bar codes, but I don’t understand half of what they’re saying, so… there an item (that is portable…you don’t hook it up to your computer to complete the scannning process) that will do this for us older people who are technically unable to mess around with aps and codes and whatever….and if not, Christmas is coming and boy, wouldn’t that be a great thing to sell to us older people?

  43. Moira:

    There is a reference to in this thread, but they are closing the site. They recommend these services as more complete and crucially better supported products. Give them a try:

    Delicious Library, Library Thing and Shelfworthy

  44. @ Peter (IMC)

    ewww Symbian is the Linux of phones? how about Symbian is the swamp of eternal despair of phones?

    can’t install: not signed
    can’t install: certificate expired
    pre-installed pdf reader takes up 30% of the screen for the UI with no full screen option
    ever tried to make a playlist in the audio player? ouch… stoneage
    70mb PC sync software that is absolute crap
    oh and the occasional OS crashes that suddenly reset everything including the date to 1980 or something?

    Was it really that iPhone and Android are so amazing or was there just such an incredible vacuum, anything would have been good enough to fill the void?

    Well, I guess Android is pretty amazingly well thought out… thanks for the light

  45. This is actually going to be really useful for me to scan books at thrift stores to check their prices, to see if I should buy them for resale on Ebay/Amazon. Very neat tool!

  46. Anyone had luck with decoding ITF (Interleaved 2 of 5) barcodes using python scripting. I need to scan some lengths that the scanner does not read. Is there a way to send DecodeHints like “Allowed_Lengths” with Python scripting?

  47. I have started learning Android Programming with Python!
    You can’t survive in futuer without Android programming!

  48. I get the following error ,

    TypeError : list indices must be integers , not str

    I used the folliwing code

    import android
    droid = android.Android()
    (id, result, error) = droid.scanBarcode()
    isbn = int(result['extras']['SCAN_RESULT'])
    url = “” % isbn

    The error comes up at line

    isbn = int(result['extras']['SCAN_RESULT'])

    I’m using Nexus with android 2.3.4 (build GRJ22)
    and i have QRDroid as the barcode scanner app , the QRDroid intent opens when i run the script , but when the intent returns , this error is thrown and the script stops


  49. In PHP:

    $isbn = $code[“result”]->extras->SCAN_RESULT;
    $url = “”.$isbn;
    $droid->startActivity(“android.intent.action.VIEW”, $url);

  50. require_once("Android.php");
    $droid = new Android();
    $code = $droid->scanBarcode();
    $isbn = $code["result"]->extras->SCAN_RESULT;
    $url = "".$isbn;
    $droid->startActivity("android.intent.action.VIEW", $url);

  51. I had the same problem, Vidhuran.

    Switch the lines 3 and 4 from your code to:

    code = droid.scanBarcode()
    isbn = int(code.result[‘extras’][‘SCAN_RESULT’])

  52. i solve problem.

    import android
    droid = android.Android()
    (id, result, error)=droid.scanBarcode()
    barcode = (result[‘extras’])
    droid.view(‘’ + barcode[‘SCAN_RESULT’])