JerabekJakub JerabekJakub - 2 months ago 20
Android Question

How to get detected barcode/QR automatically

I have tried new Google Play Services feature - Barcode/QR scanner. In sample application is scanning started by taping on button and result is returned also on tap.

Is there a way to change its behavior to return first detected barcode/QR immediately?

I am not the first one curious about this.

Thank you in advance.

Answer

UPDATE!

For future readers please use this project on my github, it includes a full screen preview on almost all devices as well. The previous answer was not a solid implementation but more of a quick solution. The github repository contains all the changes and check the changelog as well.

  1. MainAcitivity.java
  2. BarcodeCaptureActivity.java
  3. CameraSource.java
  4. BarcodeGraphicTracker.java

Old Answer: No Need To Use This Anymore

I have found a work around, not very secure but it's something right. Firstly if you go to the BarcodeCaptureActivity.java the onTap() gets the last barcode detected right and wraps the barcode object into an intent. While all the BarcodeGraphicTracker.java tracks the positions of any Barcode objects. So if you could use any of the two methods onNewItem() or onUpdate() you can easily send the barcode data to the calling activity using intents.

Now how i did this, since the BarcodeGraphicTracker is just a normal class:

1.Create a class that holds an static activity variable:

public class ActivitySource {
    public static Activity caller;
}
  1. In BarcodeCaptureActivity.java under the onCreate() add:

    ActivitySource.caller = this;

  2. In BarcodeGraphicTracker under the onNewItem(int id, Barcode item) add the following under mGraphic.setId(id);

    Intent data = new Intent();
    data.putExtra("Barcode", item.rawValue);
    ActivitySource.caller.setResult(Activity.RESULT_OK, data);
    ActivitySource.caller.finish();
    ActivitySource.caller = null;
    

When you start BarcodeCaptureActivity, start for result:

static final int GET_BAR_CODE = 1;//put somewhere in the class which starts the capture activity

Intent intent = new Intent(ACTIVITYNAME.this, BarcodeCaptureActivity.class);
startActivityForResult(intent, GET_BAR_CODE);

Then in the same class that you started the activity in, get the result

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if (resultCode == RESULT_OK && requestCode == GET_BAR_CODE) {
       String barcodeValue = data.getStringExtra("Barcode");
       Log.e(TAG, barcodeValue);
    }
}

Then that's it you don't have to click anything, the app will do everything now. Hope this helps :)

Comments