Page Banner

Android – Optimally Using Zxing Barcode Scanner and Camera Orientation

Need a barcode scanner for your app? Yes, “Zxing” is the best solution. Zxing (https://github.com/zxing/zxing) is the most popular library of its kind which can scan and decode result in a fraction of a second.

Now what?? Unable to figure out how to configure the camera to rotate automatically? Yes, free version of this library support landscape mode only while scanning a code. There are some situations where automatic rotation of the camera is a must. If you had tried to fix this already, probably you would know how much time you have spent on this and what is the level of complexity! Yes, there is a simple solution to this. Use zxing-android-embedded (https://github.com/journeyapps/zxing-android-embedded) library instead. Internally, this library uses Zxing core for decoding and the camera supports both landscape and portrait modes. You can set your desired orientation in AndroidManifest.xml file by setting up the orientation for the corresponding activity.Step 1 – Modification in XML part:
Use CompoundBarcodeView component in xml layout (e.g. scanner_activity.xml) file-

<com.journeyapps.barcodescanner.CompoundBarcodeView android:id=“@+id/scanner” android:layout_width=“match_parent” android:layout_height=“match_parent” android:layout_alignParentTop=“true”> com.journeyapps.barcodescanner.CompoundBarcodeView>

Step 2 – Modification in Activity class:
Initialize the above component in your activity class (e.g. MyBarCodeScannerActivity.java)-

Create an instance variable

private CompoundBarcodeView mBarcodeView;

Initialize inside onCreate()

mBarcodeView = (CompoundBarcodeView) findViewById(R.id.scanner);

barcodeView.decodeSingle(callback);

Impliment a callback to handle the result –

private BarcodeCallback callback = new BarcodeCallback() {
   @Override
   public void barcodeResult(final BarcodeResult result) {
	//code to handle “result”
      Toast.makeText(YourActivityName.this, result.getText(), Toast.LENGTH_SHORT).show();
   }
   @Override
   public void possibleResultPoints(List resultPoints) {
   }
};

Step 3 – Modification in AndroidMenifest.xml file:
Setting up the screen orientations:
Add the following property to the activity declaration of MyBarCodeScannerActivity.java in AndroidMenifest.xml file

For landscape- android:screenOrientation="landscape",
For portrait- android:screenOrientation="portrait",

To support both the orientation just remove android:screenOrientation property from that activity.