Android Question Capturing USB_DEVICE_ATTACHED and USB_DEVICE_DETACHED event

Filippo

Expert
Licensed User
Longtime User
Hi,

up to android version 10, my intent filter in Manifest has worked very well, ie the response(USB permission request) was fast(about 1-2 seconds).
Now with android 12 is the response(USB permission request) very slow(about 20 seconds) and the event USB_DEVICE_ATTACHED is not recognized.

Is there anything additional that needs to be considered for android 12?

B4X:
'intent-filter
AddReceiverText(smcmm, <intent-filter>
 <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/>
 <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED"/>
</intent-filter>)

usbService:
B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Service_Create
    Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER
End Sub

Sub Service_Start (StartingIntent As Intent)
    If StartingIntent.Action="android.hardware.usb.action.USB_DEVICE_ATTACHED" Then
        If Not(IsPaused(Starter)) And Not(IsPaused(Main)) Then
            'Log("USB_DEVICE_ATTACHED:" & StartingIntent.ExtrasToString)
            '...
        End If
    Else If StartingIntent.Action="android.hardware.usb.action.USB_DEVICE_DETACHED" Then
        If Not(IsPaused(Starter)) Then
            'Log("USB_DEVICE_DETACHED:" & StartingIntent.ExtrasToString)
            '...
        End If
    End If
    Service_Stop
End Sub

Sub Service_Destroy

End Sub

Public Sub Service_Stop
    StopService(Me)
End Sub
 
Last edited:
Solution
I have now solved my problem with a "broadcast".
Now everything works without any problem, even if several apps are waiting for this event.

Just replace the service with this class.

B4X:
Sub Class_Globals
    Private broadcast As BroadCastReceiver
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
    broadcast.Initialize("broadcast")
    broadcast.registerReceiver("android.hardware.usb.action.USB_DEVICE_ATTACHED")
    broadcast.registerReceiver("android.hardware.usb.action.USB_DEVICE_DETACHED")
    
    'Set priority to maximum value
    broadcast.SetPriority(2147483647)
End Sub

Private Sub broadcast_OnReceive(Action As String, Extras As Object)
    'Execute so that other...

Filippo

Expert
Licensed User
Longtime User
Check the unfiltered logs. Do you see any error message after you attach the usb?

In the unfiltered-logs I noticed this line of text:
FATAL EXCEPTION: main
Process: fg.cronomillemiglia, PID: 32614
java.lang.RuntimeException: Unable to start receiver fg.cronomillemiglia.smcmm$smcmm_BR: android.app.ForegroundServiceStartNotAllowedException: startForegroundService() not allowed due to mAllowStartForeground false: service fg.cronomillemiglia/.smcmm
 

Attachments

  • unfiltered-logs.txt
    148.3 KB · Views: 50
Upvote 0

Filippo

Expert
Licensed User
Longtime User
Check the unfiltered logs. Do you see any error message after you attach the usb?
At the first test my OTG adapter was somehow defective.
Now it works, but the response is much too slow.

unfiltered-logs:
APP_FirstTime-Start=11:11:56
** Activity (main) Resume **
notifyKeepScreenOnChanged: keepScreenOn=false
mIsDeviceDefault = false, mIsSamsungBasicInteraction = false, isMetaDataInActivity = false
[INFO] isPopOver=false, config=false
updateCaptionType >> DecorView@86a1842[], isFloating=true, isApplication=true, hasWindowControllerCallback=false, hasWindowDecorCaption=false
setCaptionType = 0, this = DecorView@86a1842[]
initGoToTop
initGoToTop
setView = com.android.internal.policy.DecorView@86a1842 TM=true
setSurface called with nullptr
dispatchDetachedFromWindow
Input channel destroyed: '1e52058', fd=155
Skipped 72 frames! The application may be doing too much work on its main thread.
ensureControlAlpha: for ITYPE_NAVIGATION_BAR on fg.cronomillemiglia/fg.cronomillemiglia.main
Relayout returned: old=(65,0,2408,1080) new=(65,0,2408,1080) req=(2343,1080)0 dur=4 res=0x1 s={true 4047400960} ch=false fn=3
onsize change changed
onsize change changed
ensureControlAlpha: for ITYPE_NAVIGATION_BAR on fg.cronomillemiglia/fg.cronomillemiglia.main
sendUserActionEvent() mView returned.
Davey! duration=1333ms; Flags=0, FrameTimelineVsyncId=2454278, IntendedVsync=84536151150526, Vsync=84537351150550, InputEventId=0, HandleInputStart=84537363001807, AnimationStart=84537363005807, PerformTraversalsStart=84537363683037, DrawStart=84537383818960, FrameDeadline=84536167817193, FrameInterval=84537362869114, FrameStartTime=16666667, SyncQueued=84537398690037, SyncStart=84537398876576, IssueDrawCommandsStart=84537432713191, SwapBuffers=84537478184807, FrameCompleted=84537484750960, DequeueBufferDuration=3048616, QueueBufferDuration=960385, GpuCompleted=84537484750960, SwapBuffersCompleted=84537481594422, DisplayPresentTime=2348912816720838657,
NativeAlloc concurrent copying GC freed 76422(3213KB) AllocSpace objects, 29(580KB) LOS objects, 49% free, 6674KB/13MB, paused 190us,63us total 141.548ms
*** Service (httputils2service) Create ***
setSurface called with nullptr
A resource failed to call close.
A resource failed to call close.
A resource failed to call close.
** Service (httputils2service) Start **
mIsDeviceDefault = false, mIsSamsungBasicInteraction = false, isMetaDataInActivity = false
[INFO] isPopOver=false, config=false
updateCaptionType >> DecorView@58e8346[], isFloating=true, isApplication=true, hasWindowControllerCallback=false, hasWindowDecorCaption=false
setCaptionType = 0, this = DecorView@58e8346[]
initGoToTop
initGoToTop
setView = com.android.internal.policy.DecorView@58e8346 TM=true
Skipped 56 frames! The application may be doing too much work on its main thread.
Davey! duration=1032ms; Flags=0, FrameTimelineVsyncId=2454377, IntendedVsync=84537489893651, Vsync=84538423227003, InputEventId=0, HandleInputStart=84538429356268, AnimationStart=84538429363960, PerformTraversalsStart=84538432829499, DrawStart=84538435448576, FrameDeadline=84537523226985, FrameInterval=84538429173422, FrameStartTime=16666667, SyncQueued=84538443199576, SyncStart=84538443658653, IssueDrawCommandsStart=84538445066422, SwapBuffers=84538519621499, FrameCompleted=84538522730653, DequeueBufferDuration=55077, QueueBufferDuration=1015308, GpuCompleted=84538522730653, SwapBuffersCompleted=84538522730653, DisplayPresentTime=-6879236683525979185,
[](id:3a8a00000001,api:0,p:-1,c:14986) connect: controlledByApp=false
[ViewRootImpl@644b51e[main]#1] constructor()
ensureControlAlpha: for ITYPE_NAVIGATION_BAR on fg.cronomillemiglia/fg.cronomillemiglia.main
Relayout returned: old=(0,0,2273,1080) new=(451,152,1886,928) req=(1435,776)0 dur=9 res=0x7 s={true 3260985344} ch=true fn=-1
[ViewRootImpl@644b51e[main]#1(BLAST Consumer)1](id:3a8a00000001,api:1,p:14986,c:14986) connect: api=1 producerControlledByApp=true
eglCreateWindowSurface
onsize change changed
onsize change changed
[DP] dp(1) 1 android.view.ViewRootImpl.reportNextDraw:11420 android.view.ViewRootImpl.performTraversals:4193 android.view.ViewRootImpl.doTraversal:2919
Creating frameDrawingCallback nextDrawUseBlastSync=false reportNextDraw=true hasBlurUpdates=false
Creating frameCompleteCallback
Received frameDrawingCallback frameNum=1. Creating transactionCompleteCallback=false
Received frameCompleteCallback lastAcquiredFrameNum=1 lastAttemptedDrawFrameNum=1
[DP] pdf(0) 1 android.view.ViewRootImpl.lambda$addFrameCompleteCallbackIfNeeded$3$ViewRootImpl:4995 android.view.ViewRootImpl$$ExternalSyntheticLambda16.run:6 android.os.Handler.handleCallback:938
[DP] rdf()
reportDrawFinished (fn: -1)
Davey! duration=1083ms; Flags=1, FrameTimelineVsyncId=2454377, IntendedVsync=84537489893651, Vsync=84538423227003, InputEventId=0, HandleInputStart=84538429356268, AnimationStart=84538429363960, PerformTraversalsStart=84538432829499, DrawStart=84538538544576, FrameDeadline=84537506560318, FrameInterval=84538429173422, FrameStartTime=16666667, SyncQueued=84538540713114, SyncStart=84538540969730, IssueDrawCommandsStart=84538541100191, SwapBuffers=84538567080268, FrameCompleted=84538573239884, DequeueBufferDuration=3466385, QueueBufferDuration=2316923, GpuCompleted=84538573239884, SwapBuffersCompleted=84538572512499, DisplayPresentTime=0,
mIsDeviceDefault = false, mIsSamsungBasicInteraction = false, isMetaDataInActivity = false
[INFO] isPopOver=false, config=false
updateCaptionType >> DecorView@9407acf[], isFloating=true, isApplication=true, hasWindowControllerCallback=false, hasWindowDecorCaption=false
setCaptionType = 0, this = DecorView@9407acf[]
initGoToTop
initGoToTop
setView = com.android.internal.policy.DecorView@9407acf TM=true
[](id:3a8a00000002,api:0,p:-1,c:14986) connect: controlledByApp=false
[ViewRootImpl@69be606[main]#2] constructor()
ensureControlAlpha: for ITYPE_NAVIGATION_BAR on fg.cronomillemiglia/fg.cronomillemiglia.main
Relayout returned: old=(0,0,2273,1080) new=(451,182,1886,897) req=(1435,715)0 dur=9 res=0x7 s={true 3260993536} ch=true fn=-1
[ViewRootImpl@69be606[main]#2(BLAST Consumer)2](id:3a8a00000002,api:1,p:14986,c:14986) connect: api=1 producerControlledByApp=true
eglCreateWindowSurface
onsize change changed
onsize change changed
[DP] dp(1) 1 android.view.ViewRootImpl.reportNextDraw:11420 android.view.ViewRootImpl.performTraversals:4193 android.view.ViewRootImpl.doTraversal:2919
Creating frameDrawingCallback nextDrawUseBlastSync=false reportNextDraw=true hasBlurUpdates=false
Creating frameCompleteCallback
Received frameDrawingCallback frameNum=1. Creating transactionCompleteCallback=false
Received frameCompleteCallback lastAcquiredFrameNum=1 lastAttemptedDrawFrameNum=1
[DP] pdf(0) 1 android.view.ViewRootImpl.lambda$addFrameCompleteCallbackIfNeeded$3$ViewRootImpl:4995 android.view.ViewRootImpl$$ExternalSyntheticLambda16.run:6 android.os.Handler.handleCallback:938
[DP] rdf()
reportDrawFinished (fn: -1)
updateAppliedLetterboxDirection, direction=1, Caller=android.view.ViewRootImpl.handleDispatchLetterboxDirectionChanged:12773
MSG_WINDOW_FOCUS_CHANGED 0 1
MSG_WINDOW_FOCUS_CHANGED 0 1
updateAppliedLetterboxDirection, direction=1, Caller=android.view.ViewRootImpl.handleDispatchLetterboxDirectionChanged:12773
MSG_WINDOW_FOCUS_CHANGED 0 1
MSG_WINDOW_FOCUS_CHANGED 1 1
ViewPostIme pointer 0
ViewPostIme pointer 1
setSurface called with nullptr
setSurface() destroyed EGLSurface
destroyEglSurface
[ViewRootImpl@69be606[main]#2(BLAST Consumer)2](id:3a8a00000002,api:1,p:14986,c:14986) disconnect: api 1
endAllActiveAnimators on 0xc26fe300 (RippleDrawable) with handle 0xd5b5efb0
dispatchDetachedFromWindow
[ViewRootImpl@69be606[main]#2] destructor()
[ViewRootImpl@69be606[main]#2(BLAST Consumer)2](id:3a8a00000002,api:0,p:-1,c:14986) disconnect
Input channel destroyed: 'a598e8e', fd=151
ensureControlAlpha: for ITYPE_NAVIGATION_BAR on fg.cronomillemiglia/fg.cronomillemiglia.main
MSG_WINDOW_FOCUS_CHANGED 1 1
ViewPostIme pointer 0
ViewPostIme pointer 1
setSurface called with nullptr
setSurface() destroyed EGLSurface
destroyEglSurface
[ViewRootImpl@644b51e[main]#1(BLAST Consumer)1](id:3a8a00000001,api:1,p:14986,c:14986) disconnect: api 1
endAllActiveAnimators on 0xd5f2d100 (RippleDrawable) with handle 0xf02739a0
dispatchDetachedFromWindow
[ViewRootImpl@644b51e[main]#1] destructor()
[ViewRootImpl@644b51e[main]#1(BLAST Consumer)1](id:3a8a00000001,api:0,p:-1,c:14986) disconnect
Input channel destroyed: 'a21dd19', fd=108
ensureControlAlpha: for ITYPE_NAVIGATION_BAR on fg.cronomillemiglia/fg.cronomillemiglia.main
MSG_WINDOW_FOCUS_CHANGED 1 1
startInputInner - Id : 0
startInputInner - mService.startInputOrWindowGainedFocus
Background young concurrent copying GC freed 84997(4213KB) AllocSpace objects, 32(868KB) LOS objects, 39% free, 8124KB/13MB, paused 357us,112us total 116.975ms
Input channel destroyed: 'ClientS', fd=107
setSurface called with nullptr
setSurface called with nullptr
** Receiver (smcmm) OnReceive **
*** Service (smcmm) Create ***
** Service (smcmm) Start **
Service_Start=11:12:24
StartingIntent.Action:android.hardware.usb.action.USB_DEVICE_ATTACHED
Compat change id reported: 160794467; UID 10288; state: ENABLED
** Activity (main) Pause, UserClosed = false **
** Service (smcmm) Destroy **
MSG_WINDOW_FOCUS_CHANGED 0 1
ensureControlAlpha: for ITYPE_NAVIGATION_BAR on fg.cronomillemiglia/fg.cronomillemiglia.main
stopped(false) old=false
notifyKeepScreenOnChanged: keepScreenOn=false
** Activity (main) Resume **
notifyKeepScreenOnChanged: keepScreenOn=false
WakeLock already held.
Relayout returned: old=(65,0,2408,1080) new=(65,0,2408,1080) req=(2343,1080)0 dur=2 res=0x1 s={true 4047400960} ch=false fn=282
MSG_WINDOW_FOCUS_CHANGED 1 1
startInputInner - Id : 0
startInputInner - mService.startInputOrWindowGainedFocus
Buffer size: 16384
Interface succesfully claimed
Control Transfer Response: 7
Control Transfer Response: 0
init
Control Transfer Response: 7
Control Transfer Response: 7
Control Transfer Response: 7
Control Transfer Response: 7
Data obtained from Read buffer:
Raw data from Read buffer:
Number of bytes obtained from Read buffer: 0
Background concurrent copying GC freed 108766(4676KB) AllocSpace objects, 52(1360KB) LOS objects, 49% free, 7253KB/14MB, paused 286us,94us total 194.966ms
Input channel destroyed: 'ClientS', fd=141
Log reader error: java.io.InterruptedIOException: read interrupted
-1 received
writer error
java.lang.InterruptedException
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.reportInterruptAfterWait(AbstractQueuedSynchronizer.java:2042)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2076)
at java.util.concurrent.ArrayBlockingQueue.take(ArrayBlockingQueue.java:387)
at anywheresoftware.b4a.remotelogger.Connector$Writer.run(Connector.java:160)
at java.lang.Thread.run(Thread.java:920)
Starting remote logger. Port: 11031
After accept
** Receiver (smcmm) OnReceive **
*** Service (smcmm) Create ***
** Service (smcmm) Start **
Service_Start=11:13:33
StartingIntent.Action:android.hardware.usb.action.USB_DEVICE_DETACHED
**** StopUSB *****
Control Transfer Response: -1
close
** Service (smcmm) Destroy **
 
Upvote 0

Filippo

Expert
Licensed User
Longtime User
I don't see anything in the logs from the last post. The foreground error can be a real issue as the OS prevents services from starting in the background.
When I connect the USB device, the app is in the foreground. The service does not need to be started in background.

Here is another test. Now has something to do with the time(ForegroundServiceDidNotStartInTimeException):
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
APP_FirstTime-Start=12:28:45
** Activity (main) Resume **
*** Service (httputils2service) Create ***
** Service (httputils2service) Start **
** Activity (main) Pause, UserClosed = false **
Reposting event: billing_connected
** Activity (main) Create, isFirst = false **
** Activity (main) Resume **
WakeLock already held.
** Receiver (smusb) OnReceive **
** Receiver (smusb) OnReceive **
** Receiver (smmaster) OnReceive **
** Receiver (smcmm) OnReceive **
*** Service (smcmm) Create ***
** Service (smcmm) Start **
Service_Start=12:28:52
StartingIntent.Action:android.hardware.usb.action.USB_DEVICE_ATTACHED
** Receiver (smusb) OnReceive **
** Activity (main) Pause, UserClosed = false **
** Service (smcmm) Destroy **
** Activity (main) Resume **
WakeLock already held.
Buffer size: 16384
** Receiver (smusb) OnReceive **
** Receiver (smusb) OnReceive **
** Receiver (smcmm) OnReceive **
*** Service (smcmm) Create ***
** Service (smcmm) Start **
Service_Start=12:31:52
StartingIntent.Action:android.hardware.usb.action.USB_DEVICE_ATTACHED
** Activity (main) Pause, UserClosed = false **
** Service (smcmm) Destroy **
** Receiver (smcmm) OnReceive **
*** Service (smcmm) Create ***
** Service (smcmm) Start **
Service started in foreground mode.
Service_Start=12:31:52
StartingIntent.Action:android.hardware.usb.action.USB_DEVICE_DETACHED
**** StopUSB *****
** Service (smcmm) Destroy **
android.app.ForegroundServiceDidNotStartInTimeException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{c09bed7 u0 fg.cronomillemiglia/.smcmm}
at android.app.ActivityThread.throwRemoteServiceException(ActivityThread.java:2152)
at android.app.ActivityThread.access$2800(ActivityThread.java:315)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2381)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8751)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
 
Upvote 0

Filippo

Expert
Licensed User
Longtime User
Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{c09bed7 u0

This happens because you disabled the automatic foreground mode. You need to call Service.StartForeground yourself, in Service_Start.
Hi Erel,

I have now made some progress.

Whether the "Service.AutomaticForegroundMode" function is enabled or not makes no difference.
I think the problem is that I have 4 apps responding to the same USB device.
Connecting the USB device is registered by the current app after a few seconds, only removing it takes about 3 minutes for the app to give the info.

If I use the function "Service.StartForeground(1, CreateNotification("..."))" then I don't see any difference.
B4X:
Private Sub CreateNotification (Body As String) As Notification
    Dim notification As Notification
    notification.Initialize2(notification.IMPORTANCE_LOW)
    notification.Icon = "icon"
    notification.SetInfo("USB-Trigger", Body, Main)
    Return notification
End Sub

Logger connected to: PT99653AA1152600807
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
APP_FirstTime-Start=10:54:15
Can use persistant uri!
** Activity (main) Resume **
*** Service (httputils2service) Create ***
** Service (httputils2service) Start **
ResponseError. Reason: java.net.UnknownHostException: Unable to resolve host "www.google.com": No address associated with hostname, Response:
** Receiver (smstopwatch) OnReceive **
** Receiver (smc4timekeeper) OnReceive **
** Receiver (smcronovesparaid) OnReceive **
** Receiver (smcmm) OnReceive **
*** Service (smcmm) Create ***
** Service (smcmm) Start **
StartingIntent.Action:android.hardware.usb.action.USB_DEVICE_ATTACHED
USB_Start=10:54:40
** Activity (main) Pause, UserClosed = false **
** Service (smcmm) Destroy **
** Activity (main) Resume **
WakeLock already held.
Buffer size: 16384
** Receiver (smmaster) OnReceive **
** Receiver (smcmm) OnReceive **
*** Service (smcmm) Create ***
** Service (smcmm) Start **
StartingIntent.Action:android.hardware.usb.action.USB_DEVICE_DETACHED
USB_Stop=10:57:45
**** StopUSB *****
** Service (smcmm) Destroy **
** Receiver (smspeedpilot) OnReceive **
 
Upvote 0

Filippo

Expert
Licensed User
Longtime User
When I uninstall all other applications, everything works as it should.
That's very nice, but that can't be the solution, can it?
 
Upvote 0

Filippo

Expert
Licensed User
Longtime User
This log output is from a cell phone with android 10.
Here it works without problems even if the other apps are installed.
Logger connected to: CTLGAP1890703438
--------- beginning of crash
--------- beginning of system
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
Error initializing TTS engine.
** Activity (main) Create, isFirst = true **
APP_FirstTime-Start=12:47:07
** Activity (main) Resume **
*** Service (httputils2service) Create ***
** Service (httputils2service) Start **
** Activity (main) Pause, UserClosed = false **
Reposting event: billing_connected
** Activity (main) Create, isFirst = false **
** Activity (main) Resume **
WakeLock already held.
** Activity (main) Pause, UserClosed = true **
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = false **
** Service (starter) Destroy (ignored)**
** Activity (main) Resume **
** Activity (main) Pause, UserClosed = true **
*** Service (starter) Create ***
** Service (starter) Start **
Error initializing TTS engine.
** Activity (main) Create, isFirst = true **
APP_FirstTime-Start=12:55:12
** Activity (main) Resume **
*** Service (httputils2service) Create ***
** Service (httputils2service) Start **
** Receiver (smstopwatch) OnReceive **
*** Service (starter) Create ***
** Service (starter) Start **
** Service (smstopwatch) Create **
** Service (smstopwatch) Start **
Service started in foreground mode.
** Service (smstopwatch) Destroy **
** Receiver (smc4timekeeper) OnReceive **
*** Service (starter) Create ***
** Service (starter) Start **
** Service (smc4timekeeper) Create **
** Service (smc4timekeeper) Start **
Service started in foreground mode.
*** Service (httputils2service) Create ***
** Service (httputils2service) Start **
** Service (smc4timekeeper) Destroy **
** Receiver (smcronovesparaid) OnReceive **
** Receiver (smusb) OnReceive **
*** Service (smusb) Create ***
** Service (smusb) Start **
Service started in foreground mode.
** Service (smusb) Destroy **
*** Service (starter) Create ***
** Service (starter) Start **
Error initializing TTS engine.
** Service (smcronovesparaid) Create **
** Service (smcronovesparaid) Start **
Service started in foreground mode.
*** Service (httputils2service) Create ***
** Service (httputils2service) Start **
** Service (smcronovesparaid) Destroy **
** Receiver (smmaster) OnReceive **
** Receiver (smcmm) OnReceive **
*** Service (smcmm) Create ***
** Service (smcmm) Start **
StartingIntent.Action:android.hardware.usb.action.USB_DEVICE_ATTACHED
USB_Start=12:55:20
*** Service (starter) Create ***
** Activity (main) Pause, UserClosed = false **
** Service (smcmm) Destroy **
** Receiver (smspeedpilot) OnReceive **
*** Service (starter) Create ***
** Service (starter) Start **
** Service (smspeedpilot) Create **
** Service (smspeedpilot) Start **
Service started in foreground mode.
*** Service (httputils2service) Create ***
** Service (httputils2service) Start **
** Service (smspeedpilot) Destroy **
** Service (starter) Start **
Error initializing TTS engine.
** Service (smmaster) Create **
** Service (smmaster) Start **
Service started in foreground mode.
*** Service (httputils2service) Create ***
** Service (httputils2service) Start **
** Service (smmaster) Destroy **
** Activity (main) Resume **
WakeLock already held.
Buffer size: 16384
** Receiver (smstopwatch) OnReceive **
*** Service (smstopwatch) Create ***
** Service (smstopwatch) Start **
Service started in foreground mode.
** Receiver (smc4timekeeper) OnReceive **
** Service (smstopwatch) Destroy **
*** Service (smc4timekeeper) Create ***
** Service (smc4timekeeper) Start **
Service started in foreground mode.
** Receiver (smcronovesparaid) OnReceive **
*** Service (smcronovesparaid) Create ***
** Service (smcronovesparaid) Start **
Service started in foreground mode.
** Receiver (smusb) OnReceive **
** Service (smc4timekeeper) Destroy **
** Service (smcronovesparaid) Destroy **
*** Service (smusb) Create ***
** Service (smusb) Start **
Service started in foreground mode.
** Receiver (smmaster) OnReceive **
*** Service (smmaster) Create ***
** Service (smmaster) Start **
** Service (smusb) Destroy **
** Receiver (smcmm) OnReceive **
*** Service (smcmm) Create ***
** Service (smcmm) Start **
StartingIntent.Action:android.hardware.usb.action.USB_DEVICE_DETACHED
USB_Stop=12:55:24
**** StopUSB *****
** Receiver (smspeedpilot) OnReceive **
Service started in foreground mode.
*** Service (smspeedpilot) Create ***
** Service (smspeedpilot) Start **
Service started in foreground mode.
** Service (smcmm) Destroy **
** Service (smmaster) Destroy **
**** StopUSB *****
** Service (smspeedpilot) Destroy **
** Activity (main) Pause, UserClosed = false **
** Activity (main) Resume **
WakeLock already held.
 
Upvote 0

Filippo

Expert
Licensed User
Longtime User
Hi Erel,
thank you very much for your answer.
But I don't understand one thing, if all other apps are not running (all processes are finished), why should they get the event that a usb-device is connected?
Normally only the app that is currently running should receive this event.
Ok, if this is a system error, then nothing can be done.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
But I don't understand one thing, if all other apps are not running (all processes are finished), why should they get the event that a usb-device is connected?
Normally only the app that is currently running should receive this event.
Intent filters do not depend on the app running or not. The system starts the app when it receives the intent.
 
Upvote 0

Filippo

Expert
Licensed User
Longtime User
I have now solved my problem with a "broadcast".
Now everything works without any problem, even if several apps are waiting for this event.

Just replace the service with this class.

B4X:
Sub Class_Globals
    Private broadcast As BroadCastReceiver
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
    broadcast.Initialize("broadcast")
    broadcast.registerReceiver("android.hardware.usb.action.USB_DEVICE_ATTACHED")
    broadcast.registerReceiver("android.hardware.usb.action.USB_DEVICE_DETACHED")
    
    'Set priority to maximum value
    broadcast.SetPriority(2147483647)
End Sub

Private Sub broadcast_OnReceive(Action As String, Extras As Object)
    'Execute so that other applications do not receive this event
    broadcast.AbortBroadcast
    
    If Action="android.hardware.usb.action.USB_DEVICE_ATTACHED" Then
        'your code
    Else If Action="android.hardware.usb.action.USB_DEVICE_DETACHED" Then
        'your code
    End If
End Sub
 
Upvote 0
Solution
Top