Pages

Sunday, March 20, 2011

Including QR-reader in your app

Thanks to android intents, it is easy to include functionality from other apps to you own. Say for example you have an app that should be able to read QR-codes. You could easily call a barcode scanner to do the dirty work for you and just bother about the result.

Create a button that will launch Barcode Scanner from Zxing:
public Button.OnClickListener mScan = new Button.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.setPackage("com.google.zxing.client.android");
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, 0);
    }
};

Handle the callback for result:
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
        }
    }
}

This is a raw copy/paste from the ZXING-project. Nothing that I can take credit for, but I have tested it and it works as a charm.

Yes, it requires the user to have the Barcode Scanner installed. This can be handled smoothly by calling url instead - if the barcoder is installed - it will launch - otherwise launch a web browser (with a install guide of course). Very nice!

No comments:

Post a Comment