Android Question Suddenly google code scanner (based on ML kit) not working

The ML kit based Google Scanner was working but no longer works. I haven't changed any thing in code. When the 'button' is tapped, brief black screen appears and app goes back to main page. No discernible error is shown. How to rectify it? This is the log: Is it got something to do with 'Transport backend 'cct' is not registered' ? Also what are all those strange com.hunantv.imgo.activity, com.tencent.qqlive, com.qiyi.video, com.hunantv.imgo.activity.inter, com.tencent.qqlivei18n, com.iqiyi.i18n, tv.danmaku.bili] ?
** Activity (main) Pause event (activity is not paused). **
MiuiMultiWindowAdapter::getFreeformVideoWhiteListInSystem::LIST_ABOUT_SUPPORT_LANDSCAPE_VIDEO = [com.hunantv.imgo.activity, com.tencent.qqlive, com.qiyi.video, com.hunantv.imgo.activity.inter, com.tencent.qqlivei18n, com.iqiyi.i18n, tv.danmaku.bili]
false
false
getWindowModeFromSystem windowmode is 1
onWindowFocusChanged hasWindowFocus false
vri.reportNextDraw android.view.ViewRootImpl.performTraversals:3890 android.view.ViewRootImpl.doTraversal:2622 android.view.ViewRootImpl$TraversalRunnable.run:9644 android.view.Choreographer$CallbackRecord.run:1494 android.view.Choreographer$CallbackRecord.run:1502
vri.Setup new sync id=0 syncSeqId=0
Session creation failed, mPreferredRateNanos: -1
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
vri.reportNextDraw android.view.ViewRootImpl.performTraversals:3890 android.view.ViewRootImpl.doTraversal:2622 android.view.ViewRootImpl$TraversalRunnable.run:9644 android.view.Choreographer$CallbackRecord.run:1494 android.view.Choreographer$CallbackRecord.run:1502
vri.Setup new sync id=1 syncSeqId=0
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
Transport backend 'cct' is not registered
** Activity (main) Resume **
onWindowFocusChanged hasWindowFocus true
refreshLastKeyboardType: 1
getCurrentKeyboardType: 1
** Activity (main) Pause event (activity is not paused). **
MiuiMultiWindowAdapter::getFreeformVideoWhiteListInSystem::LIST_ABOUT_SUPPORT_LANDSCAPE_VIDEO = [com.hunantv.imgo.activity, com.tencent.qqlive, com.qiyi.video, com.hunantv.imgo.activity.inter, com.tencent.qqlivei18n, com.iqiyi.i18n, tv.danmaku.bili]
false
false
getWindowModeFromSystem windowmode is 1
onWindowFocusChanged hasWindowFocus false
vri.reportNextDraw android.view.ViewRootImpl.performTraversals:3890 android.view.ViewRootImpl.doTraversal:2622 android.view.ViewRootImpl$TraversalRunnable.run:9644 android.view.Choreographer$CallbackRecord.run:1494 android.view.Choreographer$CallbackRecord.run:1502
vri.Setup new sync id=0 syncSeqId=0
Session creation failed, mPreferredRateNanos: -1
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
onWindowFocusChanged hasWindowFocus false
vri.reportNextDraw android.view.ViewRootImpl.performTraversals:3890 android.view.ViewRootImpl.doTraversal:2622 android.view.ViewRootImpl$TraversalRunnable.run:9644 android.view.Choreographer$CallbackRecord.run:1494 android.view.Choreographer$CallbackRecord.run:1502
vri.Setup new sync id=1 syncSeqId=0
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
 
Fresh download and running of code too doesn't work. The complete log is below:

Logger connected to: Xiaomi 23076RN4BI
--------- beginning of main
Using CollectorTypeCMC GC.
Not starting debugger since process cannot load the jdwp agent.
android.system.ErrnoException: open failed: ENOENT (No such file or directory)
at libcore.io.Linux.open(Native Method)
at libcore.io.ForwardingOs.open(ForwardingOs.java:563)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:274)
at libcore.io.ForwardingOs.open(ForwardingOs.java:563)
at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:8310)
at android.system.Os.open(Os.java:494)
at android.os.perfdebug.PerfDebugMonitorImpl.monitorVersionControl(PerfDebugMonitorImpl.java:204)
at android.os.perfdebug.PerfDebugMonitorImpl.prepareMonitor(PerfDebugMonitorImpl.java:185)
at android.app.ActivityThread.main(ActivityThread.java:8397)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:560)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:954)
Load libmiui_runtime
Compat change id reported: 171979766; UID 10517; state: ENABLED
Configuring clns-4 for other apk /data/app/~~M7VYR7JxmeP0MgB78jDwgA==/b4a.example-3O2ARzlyYKkYLxHpB9_fag==/base.apk. target_sdk_version=33, uses_libraries=, library_path=/data/app/~~M7VYR7JxmeP0MgB78jDwgA==/b4a.example-3O2ARzlyYKkYLxHpB9_fag==/lib/arm64, permitted_path=/data:/mnt/expand:/data/user/0/b4a.example
Connecting to perf service.
ANGLE Developer option for 'b4a.example' set to: 'default'
ANGLE GameManagerService for b4a.example: false
Neither updatable production driver nor prerelease driver is supported.
initialize for b4a.example , ForceDarkOrigin
JNI_OnLoad success
setConfig density:2.750000, mainRule:0, secondaryRule:0, tertiaryRule:0
10046-ScoutStateMachinecreated
No Network Security Config specified, using platform default
No Network Security Config specified, using platform default
MiuiMultiWindowAdapter::getFreeformVideoWhiteListInSystem::LIST_ABOUT_SUPPORT_LANDSCAPE_VIDEO = [com.hunantv.imgo.activity, com.tencent.qqlive, com.qiyi.video, com.hunantv.imgo.activity.inter, com.tencent.qqlivei18n, com.iqiyi.i18n, tv.danmaku.bili]
Access denied finding property "ro.vendor.df.effect.conflict"
common created.
false
false
Starting remote logger. Port: 35352
getWindowModeFromSystem windowmode is 1
tagSocket(93) with statsTag=0xffffffff, statsUid=-1
getCustomizedIconW 168
Compat change id reported: 210923482; UID 10517; state: ENABLED
--------- beginning of system
FramePredict init: true
QUALCOMM build : e49dc81, Id7642ef0e4
Build Date : 04/24/23
OpenGL ES Shader Compiler Version: EV031.36.08.19
Local Branch :
Remote Branch :
Remote Branch :
Reconstruct Branch :
Build Config : S P 12.1.1 AArch64
Driver Path : /vendor/lib64/egl/libGLESv2_adreno.so
Driver Version : 0615.66
vri.reportNextDraw android.view.ViewRootImpl.performTraversals:3890 android.view.ViewRootImpl.doTraversal:2622 android.view.ViewRootImpl$TraversalRunnable.run:9644 android.view.Choreographer$CallbackRecord.run:1494 android.view.Choreographer$CallbackRecord.run:1502
vri.Setup new sync id=0 syncSeqId=0
PFP: 0x016ee205, ME: 0x00000000
Access denied finding property "vendor.migl.debug"
pre_cache appList: ,,
"FramePredict won 't run in other process: b4a.example"
MiuiProcessManagerServiceStub setSchedFifo
setSchedFifo pid:10046, mode:3
pre_cache appList: ,,
tagSocket(103) with statsTag=0xffffffff, statsUid=-1
After accept
fail to open file: No such file or directory
fail to open node: No such file or directory
Session creation failed, mPreferredRateNanos: -1
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
tagSocket(122) with statsTag=0xffffffff, statsUid=-1
Compat change id reported: 147798919; UID 10517; state: ENABLED
tagSocket(127) with statsTag=0xffffffff, statsUid=-1
*** Debugger waiting for connection (0) ***
ignoring event: create_menu
onWindowFocusChanged hasWindowFocus true
refreshLastKeyboardType: 1
getCurrentKeyboardType: 1
getCurrentKeyboardType: 1
tagSocket(117) with statsTag=0xffffffff, statsUid=-1
*** Debugger waiting for connection (1) ***
tagSocket(120) with statsTag=0xffffffff, statsUid=-1
Copying updated assets files (1)
*** Service (starter) Create ***
PerfMonitor longMsg : seq=12 plan=06:21:43.611 late=145ms wall=1196ms h=android.app.ActivityThread$H w=114 procState=-1
** Service (starter) Start **
** Activity (main) Create (first time) **
Call B4XPages.GetManager.LogEvents = True to enable logging B4XPages events.
** Activity (main) Resume **
this model don't Support
** Activity (main) Pause event (activity is not paused). **
MiuiMultiWindowAdapter::getFreeformVideoWhiteListInSystem::LIST_ABOUT_SUPPORT_LANDSCAPE_VIDEO = [com.hunantv.imgo.activity, com.tencent.qqlive, com.qiyi.video, com.hunantv.imgo.activity.inter, com.tencent.qqlivei18n, com.iqiyi.i18n, tv.danmaku.bili]
false
false
getWindowModeFromSystem windowmode is 1
vri.reportNextDraw android.view.ViewRootImpl.performTraversals:3890 android.view.ViewRootImpl.doTraversal:2622 android.view.ViewRootImpl$TraversalRunnable.run:9644 android.view.Choreographer$CallbackRecord.run:1494 android.view.Choreographer$CallbackRecord.run:1502
vri.Setup new sync id=0 syncSeqId=0
Session creation failed, mPreferredRateNanos: -1
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
onWindowFocusChanged hasWindowFocus false
MiuiMagicPointerUtilsStubHeadImpl has been initialized !!
endAllActiveAnimators on 0xb40000727ec1ad00 (RippleDrawable) with handle 0xb40000720a7f68e0
Compat change id reported: 78294732; UID 10517; state: ENABLED
vri.reportNextDraw android.view.ViewRootImpl.performTraversals:3890 android.view.ViewRootImpl.doTraversal:2622 android.view.ViewRootImpl$TraversalRunnable.run:9644 android.view.Choreographer$CallbackRecord.run:1494 android.view.Choreographer$CallbackRecord.run:1502
vri.Setup new sync id=1 syncSeqId=0
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
Application info not found.
Could not retrieve metadata, returning empty list of transport backends.
Transport backend 'cct' is not registered
vri.reportNextDraw android.view.ViewRootImpl.performTraversals:3890 android.view.ViewRootImpl.doTraversal:2622 android.view.ViewRootImpl$TraversalRunnable.run:9644 android.view.Choreographer$CallbackRecord.run:1494 android.view.Choreographer$CallbackRecord.run:1502
vri.Setup new sync id=1 syncSeqId=0
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
** Activity (main) Resume **
vri.reportNextDraw android.view.ViewRootImpl.handleResized:1991 android.view.ViewRootImpl.-$$Nest$mhandleResized:0 android.view.ViewRootImpl$ViewRootHandler.handleMessageImpl:6025 android.view.ViewRootImpl$ViewRootHandler.handleMessage:5994 android.os.Handler.dispatchMessage:106
onWindowFocusChanged hasWindowFocus true
refreshLastKeyboardType: 1
getCurrentKeyboardType: 1
vri.Setup new sync id=2 syncSeqId=0
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
** Activity (main) Pause event (activity is not paused). **
MiuiMultiWindowAdapter::getFreeformVideoWhiteListInSystem::LIST_ABOUT_SUPPORT_LANDSCAPE_VIDEO = [com.hunantv.imgo.activity, com.tencent.qqlive, com.qiyi.video, com.hunantv.imgo.activity.inter, com.tencent.qqlivei18n, com.iqiyi.i18n, tv.danmaku.bili]
false
false
getWindowModeFromSystem windowmode is 1
vri.reportNextDraw android.view.ViewRootImpl.performTraversals:3890 android.view.ViewRootImpl.doTraversal:2622 android.view.ViewRootImpl$TraversalRunnable.run:9644 android.view.Choreographer$CallbackRecord.run:1494 android.view.Choreographer$CallbackRecord.run:1502
vri.Setup new sync id=0 syncSeqId=0
Session creation failed, mPreferredRateNanos: -1
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
onWindowFocusChanged hasWindowFocus false
vri.reportNextDraw android.view.ViewRootImpl.performTraversals:3890 android.view.ViewRootImpl.doTraversal:2622 android.view.ViewRootImpl$TraversalRunnable.run:9644 android.view.Choreographer$CallbackRecord.run:1494 android.view.Choreographer$CallbackRecord.run:1502
vri.Setup new sync id=1 syncSeqId=0
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
Transport backend 'cct' is not registered
** Activity (main) Resume **
onWindowFocusChanged hasWindowFocus true
refreshLastKeyboardType: 1
getCurrentKeyboardType: 1
** Activity (main) Pause event (activity is not paused). **
MiuiMultiWindowAdapter::getFreeformVideoWhiteListInSystem::LIST_ABOUT_SUPPORT_LANDSCAPE_VIDEO = [com.hunantv.imgo.activity, com.tencent.qqlive, com.qiyi.video, com.hunantv.imgo.activity.inter, com.tencent.qqlivei18n, com.iqiyi.i18n, tv.danmaku.bili]
false
false
getWindowModeFromSystem windowmode is 1
vri.reportNextDraw android.view.ViewRootImpl.performTraversals:3890 android.view.ViewRootImpl.doTraversal:2622 android.view.ViewRootImpl$TraversalRunnable.run:9644 android.view.Choreographer$CallbackRecord.run:1494 android.view.Choreographer$CallbackRecord.run:1502
vri.Setup new sync id=0 syncSeqId=0
Session creation failed, mPreferredRateNanos: -1
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
onWindowFocusChanged hasWindowFocus false
vri.reportNextDraw android.view.ViewRootImpl.performTraversals:3890 android.view.ViewRootImpl.doTraversal:2622 android.view.ViewRootImpl$TraversalRunnable.run:9644 android.view.Choreographer$CallbackRecord.run:1494 android.view.Choreographer$CallbackRecord.run:1502
vri.Setup new sync id=1 syncSeqId=0
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
Transport backend 'cct' is not registered
onWindowFocusChanged hasWindowFocus true
refreshLastKeyboardType: 1
getCurrentKeyboardType: 1
** Activity (main) Resume **
Cleared Reference was only reachable from finalizer (only reported once)
** Activity (main) Pause event (activity is not paused). **
MiuiMultiWindowAdapter::getFreeformVideoWhiteListInSystem::LIST_ABOUT_SUPPORT_LANDSCAPE_VIDEO = [com.hunantv.imgo.activity, com.tencent.qqlive, com.qiyi.video, com.hunantv.imgo.activity.inter, com.tencent.qqlivei18n, com.iqiyi.i18n, tv.danmaku.bili]
false
false
getWindowModeFromSystem windowmode is 1
vri.reportNextDraw android.view.ViewRootImpl.performTraversals:3890 android.view.ViewRootImpl.doTraversal:2622 android.view.ViewRootImpl$TraversalRunnable.run:9644 android.view.Choreographer$CallbackRecord.run:1494 android.view.Choreographer$CallbackRecord.run:1502
vri.Setup new sync id=0 syncSeqId=0
Session creation failed, mPreferredRateNanos: -1
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
onWindowFocusChanged hasWindowFocus false
vri.reportNextDraw android.view.ViewRootImpl.performTraversals:3890 android.view.ViewRootImpl.doTraversal:2622 android.view.ViewRootImpl$TraversalRunnable.run:9644 android.view.Choreographer$CallbackRecord.run:1494 android.view.Choreographer$CallbackRecord.run:1502
vri.Setup new sync id=1 syncSeqId=0
vri.reportDrawFinished syncSeqId=0 android.view.ViewRootImpl.lambda$createSyncIfNeeded$4$android-view-ViewRootImpl:3958 android.view.ViewRootImpl$$ExternalSyntheticLambda1.run:6 android.os.Handler.handleCallback:942 android.os.Handler.dispatchMessage:99 android.os.Looper.loopOnce:211
Transport backend 'cct' is not registered
** Activity (main) Resume **
onWindowFocusChanged hasWindowFocus true
refreshLastKeyboardType: 1
getCurrentKeyboardType: 1
** Activity (main) Pause event (activity is not paused). **
PerfMonitor: Slow Operation: Activity b4a.example/.main onPause took 55ms
onWindowFocusChanged hasWindowFocus false
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
com.hunantv.imgo.activity, com.tencent.qqlive, com.qiyi.video, com.hunantv.imgo.activity.inter, com.tencent.qqlivei18n, com.iqiyi.i18n, tv.danmaku.bili
You are seeing the system logs. It includes the output of all apps.

Change the scan method code to:
B4X:
Public Sub Scan (Formats As List) As ResumableSub
    Dim builder As JavaObject
    builder.InitializeNewInstance("com/google/mlkit/vision/codescanner/GmsBarcodeScannerOptions.Builder".Replace("/", "."), Null)
    Dim f(Formats.Size - 1) As Int
    For i = 1 To Formats.Size - 1
        f(i - 1) = Formats.Get(i)
    Next
    builder.RunMethod("setBarcodeFormats", Array(Formats.Get(0), f))
'    builder.RunMethod("enableAutoZoom", Null)
    Dim options As JavaObject = builder.RunMethod("build", Null)
    Dim scanning As JavaObject
    Dim ctxt As JavaObject
    ctxt.InitializeContext
    Dim scanner As JavaObject = scanning.InitializeStatic("com/google/mlkit/vision/codescanner/GmsBarcodeScanning".Replace("/", ".")).RunMethod("getClient", Array(ctxt, options))
    Dim o As JavaObject = scanner.RunMethod("startScan", Null)
    Do While o.RunMethod("isComplete", Null).As(Boolean) = False
        Sleep(50)
    Loop
    Dim res As ScannerResult
    res.Initialize
    If o.RunMethod("isSuccessful", Null) Then
        res.Success = True
        res.Barcode = o.RunMethod("getResult", Null)
        res.Value = res.Barcode.RunMethod("getRawValue", Null)
    Else
        Log("error: " & o.RunMethod("getException", Null))
    End If
    Return res
End Sub

Post the filtered logs.
 
Upvote 0
You are seeing the system logs. It includes the output of all apps.

Change the scan method code to:
B4X:
Public Sub Scan (Formats As List) As ResumableSub
    ...

Post the filtered logs.
Thanks for looking into the issue. The filtered Log after changing code:

Logger connected to: Xiaomi 23076RN4BI
--------- beginning of main
Copying updated assets files (1)
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create (first time) **
Call B4XPages.GetManager.LogEvents = True to enable logging B4XPages events.
** Activity (main) Resume **
** Activity (main) Pause event (activity is not paused). **
error: com.google.mlkit.common.MlKitException: Failed to scan code.
** Activity (main) Resume **
** Activity (main) Pause event (activity is not paused). **
error: com.google.mlkit.common.MlKitException: Failed to scan code.
** Activity (main) Resume **
 
Upvote 0
Upvote 0
If you have another device to test then try it.

Deleting Google Play Services cache might help. Also try to restart the device.
Interestingly, it works in older phone! First time it shows error as it apparently downloads 'Barcode UI module' and then it starts working.
Log:
Logger connected to: Xiaomi Redmi 6 Pro
--------- beginning of main
Copying updated assets files (1)
*** Service (starter) Create ***
--------- beginning of system
** Service (starter) Start **
** Activity (main) Create (first time) **
Call B4XPages.GetManager.LogEvents = True to enable logging B4XPages events.
** Activity (main) Resume **
error: com.google.mlkit.common.MlKitException: Waiting for the Barcode UI module to be downloaded.
** Activity (main) Pause event (activity is not paused). **
** Activity (main) Resume **
8904287000178
** Activity (main) Pause event (activity is not paused). **
** Activity (main) Resume **
096619183289
** Activity (main) Pause event (activity is not paused). **
 
Upvote 0

Johan Schoeman

Expert
Licensed User
Longtime User
Looks like a bug in the SDK itself. Try to change the package name and see if it starts working.
@Erel, I know that this is an old thread but nevertheless - might be a solution for the problem.

I have had the same problem and have tried everything from uninstalling the app, change the package name, clear the Google Play Services cache, change barcode_ui to barcode in the manifest, restart device, etc but just could not get the scanner to start. Always gave the error "failed to scan code" (...or something like that). I came across some Java code on the web and added it as inline Java code that are called from the Initialize method in the B4A class GoogleCodeScanner. The inline Java code apparently requests GPS for an urgent install of the dependency.

My hack of it is VERY UNTIDY but it did the trick. After days of trying everything else the scanner is now working on first run of the B4A project. Perhaps you can add it to your class via Java Object or fix up my hack of the inline Java Code.

Project attached.

My hack:

Initialize of class GoogleCodeScanner:
Public Sub Initialize
    Dim m As JavaObject
    m = Me
    m.RunMethod("onScanButtonClicked", Null)

My hack of the inline Java Code:

Force an install via inline Java code:
#if Java

BA ba;

import com.google.android.gms.common.moduleinstall.InstallStatusListener;
import com.google.android.gms.common.moduleinstall.ModuleInstallStatusUpdate;
import com.google.android.gms.common.moduleinstall.ModuleInstallClient;
import com.google.android.gms.common.moduleinstall.ModuleInstall;
import com.google.android.gms.common.moduleinstall.ModuleInstallRequest;
import com.google.mlkit.vision.codescanner.GmsBarcodeScannerOptions;
import com.google.mlkit.vision.codescanner.GmsBarcodeScanning;
import com.google.mlkit.vision.codescanner.GmsBarcodeScanner;
import com.google.android.gms.common.api.OptionalModuleApi;

import com.google.android.gms.tasks.Task;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

ModuleInstallClient moduleInstallClient;

public void onScanButtonClicked() {

    GmsBarcodeScannerOptions.Builder optionsBuilder = new GmsBarcodeScannerOptions.Builder();

    moduleInstallClient = ModuleInstall.getClient(ba.applicationContext);

    OptionalModuleApi optionalModuleApi = GmsBarcodeScanning.getClient(ba.applicationContext);
    moduleInstallClient
            .areModulesAvailable(optionalModuleApi);
 
    moduleInstall();
}

final class ModuleInstallProgressListener implements InstallStatusListener {
    @Override
    public void onInstallStatusUpdated(ModuleInstallStatusUpdate update) {
        ModuleInstallStatusUpdate.ProgressInfo progressInfo = update.getProgressInfo();
        // Progress info is only set when modules are in the progress of downloading.
        if (progressInfo != null) {
            int progress =
                    (int) (progressInfo.getBytesDownloaded() * 100 / progressInfo.getTotalBytesToDownload());
            // Set the progress for the progress bar.
            BA.Log("" + progress);
        }
        // Handle failure status maybe…

        // Unregister listener when there are no more install status updates.
        if (isTerminateState(update.getInstallState())) {

            moduleInstallClient.unregisterListener(this);
        }
    }

    public boolean isTerminateState(@ModuleInstallStatusUpdate.InstallState int state) {
        return  true;    //state == STATE_CANCELED || state == STATE_COMPLETED || state == STATE_FAILED;
    }
}

private void moduleInstall(){
    InstallStatusListener listener = new ModuleInstallProgressListener();

    OptionalModuleApi optionalModuleApi = GmsBarcodeScanning.getClient(ba.applicationContext);
    ModuleInstallRequest moduleInstallRequest =
            ModuleInstallRequest.newBuilder()
                    .addApi(optionalModuleApi)
                    // Add more API if you would like to request multiple optional modules
                    //.addApi(...)
                    // Set the listener if you need to monitor the download progress
                    .setListener(listener)
                    .build();

    moduleInstallClient.installModules(moduleInstallRequest)
            /*.addOnSuccessListener(
                    response -> {
                        if (response.areModulesAlreadyInstalled()) {
                            // Modules are already installed when the request is sent.
                            BA.Log("Modules are already installed when the request is sent.");
                        }
                    })
            .addOnFailureListener(
                    e -> {
                        // Handle failure...
                        BA.Log("" + e);
                    })*/;

}
#End If
 

Attachments

  • BarcodeScannerModified.zip
    12.7 KB · Views: 117
Last edited:
Upvote 0
@Erel, I know that this is an old thread but nevertheless - might be a solution for the problem.

I have had the same problem and have tried everything from uninstalling the app, change the package name, clear the Google Play Services cache, change barcode_ui to barcode in the manifest, etc but just could not get the scanner to start. Always gave the error "scanner not found" (...or something like that). I came across some Java code on the web and added it as inline Java code that are called from the Initialize method in the B4A class GoogleCodeScanner. The inline Java code apparently requests GPS for an urgent install of the dependency.

My hack of it is VERY UNTIDY but it did the trick. After days of trying everything else the scanner is now working on first run of the B4A project. Perhaps you can add it to your class via Java Object or fix up my hack of the inline Java Code.

Project attached.
I get this error after tapping the button. Could you please figure out why this happens?:
** Activity (main) Pause event (activity is not paused). **
*** mainpage: B4XPage_Disappear [mainpage]
Shutting down VM
FATAL EXCEPTION: main
Process: jhs.example, PID: 17051
java.lang.NoClassDefFoundError: Failed resolution of: Lkotlin/jvm/internal/Intrinsics;
at androidx.savedstate.SavedStateRegistryController$Companion.create(Unknown Source:2)
at androidx.savedstate.SavedStateRegistryController.create(Unknown Source:2)
at androidx.activity.ComponentActivity.<init>(ComponentActivity.java:146)
at com.google.mlkit.vision.codescanner.internal.GmsBarcodeScanningDelegateActivity.<init>(com.google.android.gms:play-services-code-scanner@@16.1.0:1)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at android.app.Instrumentation.newActivity(Instrumentation.java:1390)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3878)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4140)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:99)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2585)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:224)
at android.os.Looper.loop(Looper.java:318)
at android.app.ActivityThread.main(ActivityThread.java:8772)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:561)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1013)
Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics
... 20 more
java.lang.NoClassDefFoundError: Failed resolution of: Lkotlin/jvm/internal/Intrinsics;
at androidx.savedstate.SavedStateRegistryController$Companion.create(Unknown Source:2)
at androidx.savedstate.SavedStateRegistryController.create(Unknown Source:2)
at androidx.activity.ComponentActivity.<init>(ComponentActivity.java:146)
at com.google.mlkit.vision.codescanner.internal.GmsBarcodeScanningDelegateActivity.<init>(com.google.android.gms:play-services-code-scanner@@16.1.0:1)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at android.app.Instrumentation.newActivity(Instrumentation.java:1390)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3878)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4140)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:99)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2585)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:224)
at android.os.Looper.loop(Looper.java:318)
at android.app.ActivityThread.main(ActivityThread.java:8772)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:561)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1013)
Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics
... 20 more
Failed to mkdir /data/miuilog/stability/memleak/heapdump/
 
Upvote 0

Johan Schoeman

Expert
Licensed User
Longtime User
As suggested by @Johan Schoeman in PM, I updated to latest b4a and now the fix works with the phone which showed error earlier. Thanks a lot!:D
An absolutely NASTY HACK by me of some good code but it forced the scanner on my device to start working after days of trying various options. I had it working before and was surprised that it also suddenly stopped working. Will monitor its "availability" over the next few days/weeks to see if it "disappears" again subsequent to it working now again - as what has been reported by numerous developers on the web.
 
Upvote 0

Johan Schoeman

Expert
Licensed User
Longtime User
I have "fixed" the inline Java code to do away with Lamda expressions and converted it to non-Lamda inline Java Code.
Have also added 2 x Events to the inline java code that will be raised in the B4A class - you can add additional Events everywhere where there are BA.Log(...) in the inline Java code. Eg:

Add Events:
Public Sub gcs_module_installed (installed As String)
 
    Log("Back in B4A : " & installed)

End Sub

public Sub gcs_modules_present_on_device (present As String)
 
    Log("Back in B4A : " & present)
 
End Sub

The GoogleCodeScanner class in the B4A project now looks as follows:

B4A GoogleCodeScanner class:
'version: 1.00
Sub Class_Globals
    Public Const FORMAT_ALL_FORMATS = 0, FORMAT_AZTEC = 4096, FORMAT_CODABAR = 8, FORMAT_CODE_128 = 1, FORMAT_CODE_39 = 2, FORMAT_CODE_93 = 4 As Int
    Public Const FORMAT_DATA_MATRIX = 16, FORMAT_EAN_13 = 32, FORMAT_EAN_8 = 64, FORMAT_ITF = 128, FORMAT_PDF417 = 2048, FORMAT_QR_CODE = 256 As Int
    Public Const FORMAT_UPC_A = 512, FORMAT_UPC_E = 1024 As Int
    Type ScannerResult (Success As Boolean, Value As String, Barcode As JavaObject)
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
    Dim m As JavaObject
    m = Me
    Dim eventName As String = "gcs"
    m.RunMethod("checkModuleIntalled", Array(eventName))

End Sub

Public Sub Scan (Formats As List) As ResumableSub
    Dim builder As JavaObject
    builder.InitializeNewInstance("com/google/mlkit/vision/codescanner/GmsBarcodeScannerOptions.Builder".Replace("/", "."), Null)
    Dim f(Formats.Size - 1) As Int
    For i = 1 To Formats.Size - 1
        f(i - 1) = Formats.Get(i)
    Next
    builder.RunMethod("setBarcodeFormats", Array(Formats.Get(0), f))
    builder.RunMethod("enableAutoZoom", Null)
'    builder.RunMethod("allowManualInput", Null)
    Dim options As JavaObject = builder.RunMethod("build", Null)
    Dim scanning As JavaObject
    Dim ctxt As JavaObject
    ctxt.InitializeContext
    Dim scanner As JavaObject = scanning.InitializeStatic("com/google/mlkit/vision/codescanner/GmsBarcodeScanning".Replace("/", ".")).RunMethod("getClient", Array(ctxt, options))
    Dim o As JavaObject = scanner.RunMethod("startScan", Null)
    Do While o.RunMethod("isComplete", Null).As(Boolean) = False
        Sleep(50)
    Loop
    Dim res As ScannerResult
    res.Initialize
    If o.RunMethod("isSuccessful", Null) Then
        res.Success = True
        res.Barcode = o.RunMethod("getResult", Null)
        res.Value = res.Barcode.RunMethod("getRawValue", Null)
    Else
        Log("error: " & o.RunMethod("getException", Null))
    End If
    Return res
End Sub


Public Sub gcs_module_installed (installed As String)
 
    Log("Back in B4A : " & installed)

End Sub

public Sub gcs_modules_present_on_device (present As String)
 
    Log("Back in B4A : " & present)
 
End Sub


#if Java

import com.google.android.gms.common.moduleinstall.InstallStatusListener;
import com.google.android.gms.common.moduleinstall.ModuleInstallStatusUpdate;
import com.google.android.gms.common.moduleinstall.ModuleInstallClient;
import com.google.android.gms.common.moduleinstall.ModuleInstall;
import com.google.android.gms.common.moduleinstall.ModuleInstallRequest;
import com.google.android.gms.common.moduleinstall.ModuleInstallResponse;
import com.google.android.gms.common.moduleinstall.ModuleAvailabilityResponse;
import com.google.mlkit.vision.codescanner.GmsBarcodeScannerOptions;
import com.google.mlkit.vision.codescanner.GmsBarcodeScanning;
import com.google.mlkit.vision.codescanner.GmsBarcodeScanner;
import com.google.android.gms.common.api.OptionalModuleApi;

import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BA.Events;

import com.google.android.gms.tasks.Task;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;

import androidx.annotation.NonNull;

ModuleInstallClient moduleInstallClient;

private BA ba;
private String eventName = "";

//https://stackoverflow.com/questions/76075230/how-to-fix-google-code-scanner-throwing-mlkitexception-failed-to-scan-code
// ORIGINAL

public void checkModuleIntalled(String eventName) {

      this.eventName = eventName;
//    GmsBarcodeScannerOptions.Builder optionsBuilder = new GmsBarcodeScannerOptions.Builder();
//    WE DON'T NEED A MANUAL INPUT
//    if (allowManualInput) {
//        optionsBuilder.allowManualInput();
//   }
//    THIS IS ALREADY COVERED BY @EREL's JavaObject CODE
//    if (enableAutoZoom) {
//        optionsBuilder.enableAutoZoom();
//    }

    ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(ba.applicationContext);

    OptionalModuleApi optionalModuleApi = GmsBarcodeScanning.getClient(ba.applicationContext);
    moduleInstallClient
            .areModulesAvailable(optionalModuleApi)
            .addOnSuccessListener(new OnSuccessListener<ModuleAvailabilityResponse>()  {
                    @Override
                    public void onSuccess(@NonNull ModuleAvailabilityResponse response) {
                       if (response.areModulesAvailable()) {        
                          // Modules are present on the device...
                          //BA.Log("Modules are present on the device");
                         
                          if (ba.subExists(eventName + "_modules_present_on_device")) {
                            ba.raiseEvent2(ba, false, eventName + "_modules_present_on_device", true, new Object[]{"Modules are present on the device"});
                          }                        
                                     
                            //THE BELOW "STARTSCAN()" CODE IS HANDLED BY @EREL's JavaObject Code
                            //GmsBarcodeScanner gmsBarcodeScanner = GmsBarcodeScanning.getClient(ba.applicationContext, optionsBuilder.build());
                            //gmsBarcodeScanner
                            //        .startScan()
                            //        .addOnSuccessListener(barcode -> barcodeResultView.setText(getSuccessfulMessage(barcode)))
                            //        .addOnFailureListener(
                            //                e -> barcodeResultView.setText(getErrorMessage(e)))
                            //        .addOnCanceledListener(
                            //                () -> barcodeResultView.setText(getString(R.string.error_scanner_cancelled)));
                        } else {
                            // Modules are Not present on the device...
                            BA.Log("Modules are not present on the device");
                            moduleInstall();
                        }
                    }
             })
            .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        BA.Log("ERROR = " + e);
                    }
                });
}

final class ModuleInstallProgressListener implements InstallStatusListener {
    @Override
    public void onInstallStatusUpdated(ModuleInstallStatusUpdate update) {
        ModuleInstallStatusUpdate.ProgressInfo progressInfo = update.getProgressInfo();
        // Progress info Is only set when modules are in the progress of downloading.
        if (progressInfo != null) {
            int progress =
                    (int) (progressInfo.getBytesDownloaded() * 100 / progressInfo.getTotalBytesToDownload());
            // Set the progress For the progress bar.
            BA.Log("Progress = " + progress);
        }
        // Handle failure status maybe…

        // Unregister listener when there are no more install status updates.
        if (isTerminateState(update.getInstallState())) {

            moduleInstallClient.unregisterListener(this);
        }
    }

    public boolean isTerminateState(@ModuleInstallStatusUpdate.InstallState int state) {
        return state == ModuleInstallStatusUpdate.InstallState.STATE_CANCELED || state == ModuleInstallStatusUpdate.InstallState.STATE_COMPLETED || state == ModuleInstallStatusUpdate.InstallState.STATE_FAILED;
    }
}

private void moduleInstall(){
    InstallStatusListener listener = new ModuleInstallProgressListener();

    OptionalModuleApi optionalModuleApi = GmsBarcodeScanning.getClient(ba.applicationContext);
    ModuleInstallRequest moduleInstallRequest =
            ModuleInstallRequest.newBuilder()
                    .addApi(optionalModuleApi)
                    // Add more API If you would like To request multiple optional modules
                    //.addApi(...)
                    // Set the listener If you need To monitor the download progress
                    .setListener(listener)
                    .build();

    moduleInstallClient.installModules(moduleInstallRequest)
            .addOnSuccessListener(new OnSuccessListener<ModuleInstallResponse>() {
                    @Override
                    public void onSuccess(@NonNull ModuleInstallResponse response) {
                        if (response.areModulesAlreadyInstalled()) {
                            // Modules are already installed when the request is sent.
                         
                      if (ba.subExists(eventName + "_module_installed")) {
                        ba.raiseEvent2(ba, false, eventName + "_module_installed", true, new Object[]{"Modules are already installed when the request was sent"});
                      }
                   
                      //BA.Log("Modules are already installed when the request was sent.");
                        } else {
                            // Modules are Not present on the device...
                            BA.Log("Modules are not present on the device");
                            moduleInstall();
                        }
                    }
                })
            .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        BA.Log("ERROR = " + e);
                    }
                });

}

#End If

Sample project is attached - it will force a download of the dependencies as it seems to be unreliable when making it dependent on the Manifest entry only:
Unreliable Manifest entry:
AddApplicationText(
<meta-data
      android:name="com.google.mlkit.vision.DEPENDENCIES"
      android:value="barcode_ui"/>
 

Attachments

  • BarcodeScannerModifiedFixedILJ.zip
    13.7 KB · Views: 125
Last edited:
Upvote 0
Top