How to use Zxing in android
If the zxing barcode scanner is installed in the mobile, its very easy:
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "PRODUCT_MODE");//for Qr code, its "QR_CODE_MODE" instead of "PRODUCT_MODE"
intent.putExtra("SAVE_HISTORY", false);//this stops saving ur barcode in barcode scanner app's history
startActivityForResult(intent, 0);
and in OnActivityResult
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT"); //this is the result
} else
if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
If its not installed: u can put this code in try-catch block and catching the exception, u can do this:
Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
startActivity(marketIntent);
So it redirects the app to android market
and ur app continues running once if the barcode scanner
is installed.
If u dont want to use the other app in ur app, U have to download zxing library and try using the classes from core.jar file(it is created using apache ant). Follow this tutorial to do that: https://github.com/zxing/zxing/wiki/Getting-Started-Developing
All Intent options can be found here:
http://code.google.com/p/zxing/source/browse/trunk/android/src/com/google/zxing/client/android/Intents.java
Using ZXing to create an Android barcode scanning app
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! :)
Edit: Somebody edited this guide into this answer (it sounds a bit odd, I can't vouch as to its accuracy, and I'm not sure why they're using Eclipse in 2015):
Step by step to setup zxing 3.2.1 in eclipse
- Download zxing-master.zip from "https://github.com/zxing/zxing"
- Unzip zxing-master.zip, Use eclipse to import "android" project in zxing-master
- Download core-3.2.1.jar from "http://repo1.maven.org/maven2/com/google/zxing/core/3.2.1/"
- Create "libs" folder in "android" project and paste cor-3.2.1.jar into the libs folder
- Click on project: choose "properties" -> "Java Compiler" to change level to 1.7. Then click on "Android" change "Project build target" to android 4.4.2+, because using 1.7 requires compiling with Android 4.4
- If "CameraConfigurationUtils.java" don't exist in "zxing-master/android/app/src/main/java/com/google/zxing/client/android/camera/". You can copy it from "zxing-master/android-core/src/main/java/com/google/zxing/client/android/camera/" and paste to your project.
- Clean and build project. If your project show error about "switch - case", you should change them to "if - else".
- Completed. Clean and build project. You can click on "Proprties" > "Android" > click on "Is Libraries" to use for your project.
Integrating the ZXing library directly into my Android application
UPDATE! - SOLVED + GUIDE
I've managed to figure it out :) And down below you can read step-by-step guide so it hopefully can help others with the same problem as I had ;)
- Install Apache Ant - (See this YouTube video for config help)
- Download the ZXing source from ZXing homepage and extract it
- With the use of Windows Commandline (Run->CMD) navigate to the root directory of the downloaded
zxing src
. - In the commandline window - Type
ant -f core/build.xml
press enter and let Apache work it's magic [having issues?] - Enter Eclipse -> new Android Project, based on the android folder in the directory you just extracted
- Right-click project folder -> Properties -> Java Build Path -> Library -> Add External JARs...
- Navigate to the newly extracted folder and open the core directory and select
core.jar
... hit enter!
Now you just have to correct a few errors in the translations and the AndroidManifest.xml file :) Now you can happily compile, and you will now have a working standalone barcode scanner app, based on the ZXing source ;)
Happy coding guys - I hope it can help others :)
Integrate ZXing in Android Studio
I was integrating ZXING into an Android application and there were no good sources for the input all over, I will give you a hint on what worked for me - because it turned out to be very easy.
There is a real handy git repository that provides the zxing
android library project as an AAR archive.
- https://github.com/journeyapps/zxing-android-embedded
All you have to do is add this to your build.gradle
repositories {
jcenter()
}
dependencies {
implementation 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
implementation 'com.google.zxing:core:3.2.0'
}
and Gradle does all the magic to compile the code and makes it accessible in your app.
To start the Scanner afterwards, use this class/method:
From the Activity:
new IntentIntegrator(this).initiateScan(); // `this` is the current Activity
From a Fragment:
IntentIntegrator.forFragment(this).initiateScan(); // `this` is the current Fragment
// If you're using the support library, use IntentIntegrator.forSupportFragment(this) instead.
There are several customizing options:
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0); // Use a specific camera of the device
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(true);
integrator.initiateScan();
They have a sample-project and are providing several integration examples:
- AnyOrientationCaptureActivity
- ContinuousCaptureActivity
- CustomScannerActivity
- ToolbarCaptureActivity
If you already visited the link you going to see that I just copy&pasted the code from the git README. If not, go there to get some more insight and code examples.
ZXing android use front camera
The source code uses Java 7. Android does not require Java <= 6. You can see that the build provided in the project happily feeds Java 7 bytecode to dex and produces a working app. I am not sure what tool you are using that suggests otherwise. Maybe it is old.
You should not need to copy and compile the project's code though. Why is that necessary? use the core.jar
file.
You don't need any of this to use the front camera. Just invoke by Intent (https://github.com/zxing/zxing/wiki/Scanning-Via-Intent) and set extra SCAN_CAMERA_ID
to the ID of the camera you want -- usually 1 for the front one.
Example:
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
intent.putExtra("SCAN_CAMERA_ID", 1);
How to integrate Zxing Barcode Scanner without installing the actual zxing app (cannot resolve symbol: .android.CaptureActivity)?
I don't know why it happened, but finally I use another library. I use Zxing-android-minimal and tutorial from here and here. Now it works.
how to start Zxing on a Fragment?
how do i do that line but to open up the scan on a fragment ?
Use getActivity() to pass Context in IntentIntegrator
as:
new IntentIntegrator(getActivity()).initiateScan();
how will i get them on my Fragment that i'm going to run Zxing on ?
override onActivityResult
in both Fragment container Activity with super.onActivityResult(requestCode, resultCode, data);
line and in Fragment just override onActivityResult
method.
Android I use Zxing Qr code, how to scan local Qr code image?
you can use these links below
https://zxing.org/w/decode.jspx
and if you want an example use this link below
https://github.com/zxing/zxing
How to use ZXing with android CameraX to decode Barcode and QR Codes
Here below the ImageAnalyzer
I've built up to do that:
class ZxingQrCodeAnalyzer(
private val onQrCodesDetected: (qrCode: Result) -> Unit
) : ImageAnalysis.Analyzer {
companion object {
val reader = MultiFormatReader()
}
/*
https://developer.android.com/training/camerax/configuration
Default resolution: The default target resolution setting is 640x480.
Adjusting both target resolution and corresponding aspect ratio will result
in a best-supported resolution under 1080p (max analysis resolution).
*/
override fun analyze(imageProxy: ImageProxy, rotationDegrees: Int) {
// okay - manage rotation, not needed for QRCode decoding [-;
// okay - manage it for barcode scanning instead!!!
try {
imageProxy.image?.let {
// ImageProxy uses an ImageReader under the hood:
// https://developer.android.com/reference/androidx/camera/core/ImageProxy.html
// That has a default format of YUV_420_888 if not changed.
// https://developer.android.com/reference/android/graphics/ImageFormat.html#YUV_420_888
// https://developer.android.com/reference/android/media/ImageReader.html
if ((it.format == ImageFormat.YUV_420_888
|| it.format == ImageFormat.YUV_422_888
|| it.format == ImageFormat.YUV_444_888)
&& it.planes.size == 3) {
val buffer = it.planes[0].buffer // We get the luminance plane only, since we
// want to binarize it and we don't wanna take color into consideration.
val bytes = ByteArray(buffer.capacity())
buffer.get(bytes)
// Create a LuminanceSource.
val rotatedImage = RotatedImage(bytes, imageProxy.width, imageProxy.height)
rotateImageArray(rotatedImage, rotationDegrees)
val source = PlanarYUVLuminanceSource(rotatedImage.byteArray,
rotatedImage.width,
rotatedImage.height,
0,
0,
rotatedImage.width,
rotatedImage.height,
false)
// Create a Binarizer
val binarizer = HybridBinarizer(source)
// Create a BinaryBitmap.
val binaryBitmap = BinaryBitmap(binarizer)
// Try decoding...
val result: Result
try {
result = reader.decode(binaryBitmap)
onQrCodesDetected(result)
} catch (e: NotFoundException) {
e.printStackTrace()
}
} else {
// Manage other image formats
// TODO - https://developer.android.com/reference/android/media/Image.html
}
}
} catch (ise: IllegalStateException) {
ise.printStackTrace()
}
}
// 90, 180. 270 rotation
private fun rotateImageArray(imageToRotate: RotatedImage, rotationDegrees: Int) {
if (rotationDegrees == 0) return // no rotation
if (rotationDegrees % 90 != 0) return // only 90 degree times rotations
val width = imageToRotate.width
val height = imageToRotate.height
val rotatedData = ByteArray(imageToRotate.byteArray.size)
for (y in 0 until height) { // we scan the array by rows
for (x in 0 until width) {
when (rotationDegrees) {
90 -> rotatedData[x * height + height - y - 1] =
imageToRotate.byteArray[x + y * width] // Fill from top-right toward left (CW)
180 -> rotatedData[width * (height - y - 1) + width - x - 1] =
imageToRotate.byteArray[x + y * width] // Fill from bottom-right toward up (CW)
270 -> rotatedData[y + x * height] =
imageToRotate.byteArray[y * width + width - x - 1] // The opposite (CCW) of 90 degrees
}
}
}
imageToRotate.byteArray = rotatedData
if (rotationDegrees != 180) {
imageToRotate.height = width
imageToRotate.width = height
}
}
}
private data class RotatedImage(var byteArray: ByteArray, var width: Int, var height: Int)
Related Topics
How to Display Progress Dialog Before Starting an Activity in Android
Could Not Find Com.Android.Tools.Build:Aapt2:3.2.0
Android Studio Fails to Debug with Error Org.Gradle.Process.Internal.Execexception
Gles10.Glgetintegerv Returns 0 in Lollipop Only
Vectordrawable - Is It Available Somehow for Pre-Lollipop Versions of Android
Any Way to Run Shell Commands on Android Programmatically
How to Get an Android Wakelock to Work
Edittext: Disable Paste/Replace Menu Pop-Up on Text Selection Handler Click Event
How to Show an Activity Before My App Is Uninstalled (Android)
How to Avoid "Illegalstateexception: Scrollview Can Host Only One Direct Child"
Blur or Dim Background When Android Popupwindow Active
Android; Check If File Exists Without Creating a New One
Making Data Persistent in Android
Navigation Drawer (Google+ VS. Youtube)
Difference Between Onstart() and Onresume()