I have a project that scan QR Codes . It works fine using Samsung mobiles but I can't scan QR Codes using OPPO CPH1923 device . I made a debug and I found that , debugger didn't get into
receiveDetections override function .I don't know why this device dose that and I'm wasting my time .
I use Google mobile vision API
Note : I don't have a sim card in the mobile
Here is my code
barcodeDetector = new BarcodeDetector.Builder(MainActivity.this)
.setBarcodeFormats(Barcode.ALL_FORMATS)
.build();
cameraSource = new CameraSource.Builder(MainActivity.this,barcodeDetector)
.setRequestedPreviewSize(640,480)
.setAutoFocusEnabled(true)
.build();
surface.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if(ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.CAMERA},REQUEST_CAMERA_PERMISSION);
}
else {
cameraSource.start(holder);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
scannerDilaog.dismiss();
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodeSparseArray = detections.getDetectedItems();
if(barcodeSparseArray!=null&&barcodeSparseArray.size()>0){
if(!flag) {
final Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
int times =0;
//flag = true;
cameraSource.stop();
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
intent.putExtra("result", barcodeSparseArray.valueAt(0).displayValue);
Log.e("result"," "+barcodeSparseArray.valueAt(0).displayValue);
if(!flag) {
times++;
Log.d("times"," "+times);
startActivity(intent);
}
flag=true;
cameraSource.stop();
}
});
}
}
}
});
Finally I found the solution at this part of this Answer
Here
Based on the Google Samples(a comment in the source):
// Note: The first time that an app using the barcode or face API is installed on a
// device, GMS will download a native libraries to the device in order to do detection.
// Usually this completes before the app is run for the first time. But if that
// download has not yet completed, then the above call will not detect any barcodes
// and/or faces.
Related
I am trying to register a app with the DJI android SDK, but the call to DJISDKManager.getInstance() just hangs.
I am following the tutorial here: https://developer.dji.com/mobile-sdk/documentation/application-development-workflow/workflow-integrate.html
After the app verifies it has all the required permissions it calls startSDKRegistration:
I have the call to DJISDKManager.getInstance() on a single line for testing. It hangs on the call, and doesn't throw any errors.
private void startSDKRegistration() {
if (isRegistrationInProgress.compareAndSet(false, true)) {
Thread registrationThread = new Thread() {
#Override
public void run() {
showToast("registering, pls wait...");
try {
DJISDKManager temp = DJISDKManager.getInstance();
} catch (InterruptedException e) {
e.printStackTrace();
}
DJISDKManager.getInstance().registerApp(MainActivity.this.getApplicationContext(), new DJISDKManager.SDKManagerCallback() {
#Override
public void onRegister(DJIError djiError) {
if (djiError == DJISDKError.REGISTRATION_SUCCESS) {
showToast("Register Success");
DJISDKManager.getInstance().startConnectionToProduct();
} else {
showToast("Register sdk fails, please check the bundle id and network connection!");
}
Log.v(TAG, djiError.getDescription());
}
#Override
public void onProductDisconnect() {
Log.d(TAG, "onProductDisconnect");
showToast("Product Disconnected");
notifyStatusChange();
}
#Override
public void onProductConnect(BaseProduct baseProduct) {
Log.d(TAG, String.format("onProductConnect newProduct:%s", baseProduct));
showToast("Product Connected");
notifyStatusChange();
}
#Override
public void onProductChanged(BaseProduct baseProduct) {
// there was nothing in the tutorial for this method
}
#Override
public void onComponentChange(BaseProduct.ComponentKey componentKey, BaseComponent oldComponent,
BaseComponent newComponent) {
if (newComponent != null) {
newComponent.setComponentListener(new BaseComponent.ComponentListener() {
#Override
public void onConnectivityChange(boolean isConnected) {
Log.d(TAG, "onComponentConnectivityChanged: " + isConnected);
notifyStatusChange();
}
});
}
Log.d(TAG,
String.format("onComponentChange key:%s, oldComponent:%s, newComponent:%s",
componentKey,
oldComponent,
newComponent));
}
#Override
public void onInitProcess(DJISDKInitEvent djisdkInitEvent, int i) {
}
#Override
public void onDatabaseDownloadProgress(long l, long l1) {
}
});
}
};
GlobalParams.getInstance().getThreadPool().submit (registrationThread);
}
private void notifyStatusChange() {
mHandler.removeCallbacks(updateRunnable);
mHandler.postDelayed(updateRunnable, 500);
}
private Runnable updateRunnable = new Runnable() {
#Override
public void run() {
Intent intent = new Intent(FLAG_CONNECTION_CHANGE);
sendBroadcast(intent);
}
};
private void showToast(final String toastMsg) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toastMsg, Toast.LENGTH_LONG).show();
}
});
}
The problem occurs after Android Gradle plugin version 3.6.0+
https://developer.android.google.cn/studio/releases/gradle-plugin#3-6-0-behavior
Native libraries packaged uncompressed by default
When you build your app, the plugin now sets extractNativeLibs to "false" by default. That is, your native libraries are page aligned and packaged uncompressed. While this results in a larger upload size, your users benefit from the following:
Smaller app install size because the platform can access the native libraries directly from the installed APK, without creating a copy of the libraries.
Smaller download size because Play Store compression is typically better when you include uncompressed native libraries in your APK or Android App Bundle.
If you want the Android Gradle plugin to instead package compressed native libraries, include the following in your app's manifest:
<application
android:extractNativeLibs="true">
</application>
Question: What is the setting for minSdkVersion and targetSdkVersion?
I ask because there is a known issue with the values. I don't remember exactly but setting the following should work.
minSdkVersion 22
targetSdkVersion 29
I am using Mobile Vision API to scan QR code.
I have this method in the activity to use the camera to capture the code:
private void createCameraSource() {
final BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this).build();
if(!barcodeDetector.isOperational()){
Toast.makeText(this,
"No se puede utilizar el detector de códigos de barra", Toast.LENGTH_LONG).show();
this.finish();
}
else {
final CameraSource cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setAutoFocusEnabled(true)
.setRequestedPreviewSize(1600, 1024)
.build();
cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
if (ActivityCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
try {
cameraSource.start(cameraPreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if (!RegisterActivity.this.isProcessing() && barcodes.size() > 0) {
barcodeDetector.release();
RegisterActivity.this.setProcessing(true);
Intent intent = new Intent(RegisterActivity.this, ResultActivity.class);
intent.putExtra("code", codigo);
intent.putExtra("data", barcodes.valueAt(0));
setResult(CommonStatusCodes.SUCCESS, intent);
startActivity(intent);
RegisterActivity.this.setProcessing(false);
finish();
}
}
});
}
}
When a code is detected and read, I need to pass that code to other activity. That's why I have this code:
if (!RegisterActivity.this.isProcessing() && barcodes.size() > 0) {
barcodeDetector.release();
RegisterActivity.this.setProcessing(true);
Intent intent = new Intent(RegisterActivity.this, ResultActivity.class);
intent.putExtra("code", codigo);
intent.putExtra("data", barcodes.valueAt(0));
setResult(CommonStatusCodes.SUCCESS, intent);
startActivity(intent);
RegisterActivity.this.setProcessing(false);
finish();
}
When I run the application, this exception is shown in the logcat:
2020-08-27 18:19:53.894 11076-11746/com.company.myapp E/CameraSource: Exception thrown from receiver.
java.lang.IllegalStateException: Detector processor must first be set with setProcessor in order to receive detection results.
at com.google.android.gms.vision.Detector.receiveFrame(com.google.android.gms:play-services-vision-common##19.1.2:17)
at com.google.android.gms.vision.CameraSource$zza.run(com.google.android.gms:play-services-vision-common##19.1.2:47)
at java.lang.Thread.run(Thread.java:929)
2020-08-27 18:19:53.956 11076-11746/com.company.myapp E/CameraSource: Exception thrown from receiver.
java.lang.IllegalStateException: Detector processor must first be set with setProcessor in order to receive detection results.
at com.google.android.gms.vision.Detector.receiveFrame(com.google.android.gms:play-services-vision-common##19.1.2:17)
at com.google.android.gms.vision.CameraSource$zza.run(com.google.android.gms:play-services-vision-common##19.1.2:47)
at java.lang.Thread.run(Thread.java:929)
The application works because the new activity is opened and I can receive the read code there, but, if I set a breakpoint in that activity and start debugging, debugger session ends with no more errors after a few seconds.
What's wrong with that code?
Debugging sometimes changes the behavior of your code. Especially when your framework works with a lot of threads like android.
From the stacktrace at java.lang.Thread.run(Thread.java:929) I would say, that some code, in a thread, which is currently not under debugging wants to use the Decoder, before your call of setProcessor.
In Java only the thread which is under debugging will stop at a breakpoint other threads are not touched and won't be stopped when a breakpoint is reached.
i am trying to implement Google vision text recognizer to read text on image with camera in my app. The text recognition works for some times and returns this error on every read text code executed.
E/native: jni_helper.cc:760 No valid text recognizer: initialize the OCR engine before use, and make sure it has not been shut down.
D/skia: onFlyCompress
E/native: jni_helper.cc:760 No valid text recognizer: initialize the OCR engine before use, and make sure it has not been shut down.
D/skia: onFlyCompress
E/native: jni_helper.cc:760 No valid text recognizer: initialize the OCR engine before use, and make sure it has not been shut down.
D/skia: onFlyCompress
The Google vision text recognizer code
textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (textRecognizer.isOperational()) {
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1280, 720)
.setAutoFocusEnabled(true)
.setRequestedFps(2.0f)
.build();
surface_view.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
cameraSource.start(surface_view.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
Toast.makeText(getApplicationContext(), "surface released", Toast.LENGTH_LONG).show();
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
final SparseArray<TextBlock> items = detections.getDetectedItems();
if (items.size() != 0) {
final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append(",");
}
captured_txt.post(new Runnable() {
#Override
public void run() {
String[] sbuilerArray = stringBuilder.toString().split(",");
for (String s : sbuilerArray) {
Log.d("Textarray", s);
if (s.trim().length() >= 12 && s.trim().matches("[0-9 ]*")) {
ScannedAirtime(s);
cameraSource.stop();
}
}
}
});
}
}
});
} else {
Log.d("Airtime Topup:", "Detector dependencies are not available");
}
I had a similar problem.
For me, it was the order, when unloading.
MultiDetector.release();
CameraSource.stop();
FaceDetector.release();
BarcodeDetector.release();
TextRecognizer.release();
//here the loading process continues as if it were the first time
Then, the error woke me up.
I got the same error but I'm using DexGuard.
It was fixed for me by this DexGuard rules:
-keepresourcefiles assets/mlkit*/**
Need Help in code optimization. I have developed an android app which scans QR code labeled on the product.
I have tested few scenarios where other apps like Inigma is working fine but my app fails to scan : following cases :
1 ) when I scan online generated QR code my app and inigma both works fine
.2) When I scan printed QR code on product such as bottle .my apps fail to scan but inigma scans perfectly .
where I am lagging ? can Anybody please help me out ? I have to try to solve this from past 1 week but not getting the solution.
Techincal Details: I am using ZXING library for QR code scanning.
Please help ... :(
Try using this method and call the method at onResume() cycle
private void initialiseDetectorsAndSources() {
// Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.ic_notfound)).getBitmap();
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(BarCodeScanActivity.this)
.setBarcodeFormats(Barcode.ALL_FORMATS)
.build();
cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setRequestedPreviewSize(1920, 1080)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setAutoFocusEnabled(true) //you should add this feature
.build();
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
if (ActivityCompat.checkSelfPermission(BarCodeScanActivity.this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
cameraSource.start(surfaceView.getHolder());
} else {
ActivityCompat.requestPermissions(BarCodeScanActivity.this, new
String[]{Manifest.permission.CAMERA}, AppUtils.CAMERA_PERMISSION);
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
// Toast.makeText(BarCodeScanActivity.this, "To prevent memory leaks barcode scanner has been stopped", Toast.LENGTH_SHORT).show();
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if (barcodes != null && barcodes.size() > 0) {
available.post(new Runnable() {
#Override
public void run() {
String scandata = barcodes.valueAt(0).displayValue;
// the scandata is your barcode
}
});
}
}
});
}
I have a problem with my code:
private ScanCallback mLeScanCallback = new ScanCallback(){
//Callback when a BLE advertisement has been found.
#Override
public void onScanResult(int callbackType, final android.bluetooth.le.ScanResult result) {
super.onScanResult(callbackType, result);
new Thread(){
#Override
public void run() {
final BluetoothDevice device = result.getDevice();
runOnUiThread(new Runnable() {
#Override
public void run() {
if (device != null){
mDevices.add(device);
}
}
});
}
}.start();
}
//Callback when batch results are delivered.
#Override
public void onBatchScanResults(List<android.bluetooth.le.ScanResult> results) {
super.onBatchScanResults(results);
}
//Callback when scan could not be started.
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
}
currently I am using this code to get the results of my scan. This was based on: https://github.com/RedBearLab/Android/blob/master/Examples/Chat/src/com/redbear/chat/Main.java#L138
The app where is was based on had a lower API level, and my app has a higher one. So I changed it to on startScan() method.
I am honestly stuck, because when I run the app i get no errors. I checked if the mDevices array is empty and it is. Meaning that the code doesn't add the devices to the array or that there aren't any devices to be found by my app specifically.
Any help would be greatly appreciated.
Code of activating scanning
private void scanDevice(){
new Thread() {
#Override
public void run(){
BTScanner.startScan(mLeScanCallback);
try {
Thread.sleep(SCAN_PERIOD);
} catch (InterruptedException e){
e.printStackTrace();
}
BTScanner.stopScan(mLeScanCallback);
}
}.start();
}
Found the problem. It has to do with the permissions for ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION to get the scan results.