Android Question There is no servicetype paramerter in Service.StartForeground

Mr.Coder

Member
Licensed User
Longtime User
Hi,

Starting from android 14 i think, We should set the type for each service, I know that i can set the service type in the manifest file but what if i set the Service.AutomaticForegroundMode to Never then in OnStart event i put Service.StartForeground and there is just two parameters in this method there is no parameter for the service type, Is it important to set the type of the service in Service.StartForeground method or its not needed if i already define the service type in manifest file.

Thank you.
 

Mr.Coder

Member
Licensed User
Longtime User
Thank you, I know all of that, I am just asking to make sure, Does the Android OS with API Level 34+ if the type of the service paramerter not found in Service.StartForeground method will search in the manifest file for the type of the service or it will throw error or the B4A is the one who does this task?

- In Service_Create event I put this code :

B4X:
Dim uPhone As Phone

If uPhone.SdkVersion >= 29 Then
    Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER       
Else                                               
    Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_ALWAYS                   
End If

And in Service_Start event I put this code :

B4X:
Dim uPhone As Phone
Dim oContext As JavaObject

oContext.InitializeContext

If uPhone.SdkVersion >= 29 Then
    oContext.RunMethod("startForeground", Array(iNotificationID, lNotification, lServiceType))
Else
    oContext.RunMethod("startForeground", Array(iNotificationID, lNotification))
End If

And I put the foreground permissions and I specified the type of service in the manifest file :

B4X:
AddPermission(android.permission.FOREGROUND_SERVICE)
AddPermission(android.permission.ACCESS_BACKGROUND_LOCATION)
AddPermission(android.permission.FOREGROUND_SERVICE_LOCATION)
SetServiceAttribute(svLocationUpdater, android:foregroundServiceType, "location")
 
Last edited:
Upvote 0

giggetto71

Active Member
Licensed User
Longtime User
I am afraid the answer is "it depends". the service type is indeed mandatory from API34 and based on what I read, in many cases that can be read from the manifest but it's not garanteed in all phone. I do have the type in the manifest and in some (very few but not 0) cases I get on the google console the "Missing foreground service type" at runtime erro on android 14 phones (again not all..most of them are ok for now). I am inclined to think that sooner or later google will enfornce the runtime parameter so I think the approach above is very robust and futur proof.
I was wondering if make sense for the future make a new method in the Service object something like "Service.StartForeground2" where we could pass the service type Id in native b4a..just a thought.
 
Upvote 0
Top