Android Question Copilot questions StartService

JackKirk

Well-Known Member
Licensed User
Longtime User
I am involved in a lengthy dialog with Copilot to develop a B4A app that has a service that survives the aggressive service kill characteristics of Samsung S23 Ultra (and I assume other similar phones).

Part of that dialog:
Is this true or is Copilot hallucinating?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
A better implementation of StartForegroundService is available in the background location example: https://www.b4x.com/android/forum/threads/background-location-tracking.99873/#content

B4X:
Private Sub StartForegroundService(Service As Object)
    Dim p As Phone
    If p.SdkVersion <= 26 Then
        StartService(Service)
        Return
    End If
    Dim ctxt As JavaObject
    ctxt.InitializeContext
    Dim intent As JavaObject
    intent.InitializeNewInstance("android.content.Intent", Array(ctxt, Service))
    ctxt.RunMethod("startForegroundService", Array(intent))
End Sub

It is needed there because the service is started from a receiver.

Assuming that your app is running and visible, and only then you start the service, then you don't need it.

You still need to declare the foreground service type. For example (B4A-Bridge):
B4X:
SetServiceAttribute(Service1, android:foregroundServiceType, connectedDevice)
 
Upvote 0

JackKirk

Well-Known Member
Licensed User
Longtime User
Erel thanks for your response but I was interested in establishing if Copilot was correct or hallucinating.
Whoops should have looked a bit closer:

Copilot:
B4X:
Private wrk_jo_context As JavaObject
wrk_jo_context.InitializeContext
Private wrk_intent As JavaObject
wrk_intent.InitializeNewInstance("android.content.Intent", Array(wrk_jo_context, Monitor_XUpload))
Try
    wrk_jo_context.RunMethod("startForegroundService", Array(wrk_intent))
Catch
    Log("Main: startForegroundService failed: " & LastException.Message)
End Try

Erel's code (sdk > 26):
B4X:
    Dim ctxt As JavaObject
    ctxt.InitializeContext
    Dim intent As JavaObject
    intent.InitializeNewInstance("android.content.Intent", Array(ctxt, Service))
    ctxt.RunMethod("startForegroundService", Array(intent))

- essentially the same - Copilot might have found the example Erel was referencing
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…