Sunday, June 10, 2012

Using ZXing to create an android barcode scanning app


I've been searching on how to add a barcode scanner to my app. Does anybody know of any examples or know how to do this easily? Any help is greatly appreciated.



Source: Tips4all

3 comments:

  1. The ZXing project provides a standalone barcode reader application which — via Android's intent mechanism — can be called by other applications who wish to integrate barcode scanning.

    The easiest way to do this is to call the ZXing SCAN Intent from your application, like this:

    public Button.OnClickListener mScan = 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");
    startActivityForResult(intent, 0);
    }
    };

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == 0) {
    if (resultCode == RESULT_OK) {
    String contents = intent.getStringExtra("SCAN_RESULT");
    String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
    // Handle successful scan
    } else if (resultCode == RESULT_CANCELED) {
    // Handle cancel
    }
    }
    }


    Pressing the button linked to mScan would launch directly into the ZXing barcode scanner screen (or crash if ZXing isn't installed). Once a barcode has been recognised, you'll receive the result in your Activity, here in the contents variable.

    To avoid the crashing and simplify things for you, ZXing have provided a utility class which you could integrate into your application to make the installation of ZXing smoother, by redirecting the user to the Android Market if they don't have it installed already.

    Finally, if you want to integrate barcode scanning directly into your application without relying on having the separate ZXing application installed, well then it's an open source project and you can do so! :)

    ReplyDelete
  2. I had a problem with implimenting the code until I found some website (I can't find it again right now) that explained that you need to include the package name in the name of the intent.putExtra.

    It would pull up the application but wouldn't recognize any barcodes, and when I changed it from.

    intent.putExtra("SCAN_MODE", "QR_CODE_MODE");


    to

    intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");


    It worked great. Just a tip for any other novice andorid programmers.

    ReplyDelete
  3. Using the provided IntentInegrator is better. It allows you to prompt your user to install the barcode scanner if they do not have it. It also allows you to customize the messages. The IntentIntegrator.REQUEST_CODE constant holds the value of the request code for the onActivityResult to check for in the above if block.

    IntentIntegrator.initiateScan(YourActivity);


    IntentIntegrator.java

    ReplyDelete