Android Question Loss variable within service


Active Member
Licensed User
Services life cycle in Android 8+

This is not related to automatic foreground mode however it is another thing that you should be aware of when working with services in Android 8+.
Up until Android 7, the OS never killed the app services. Instead when the app was in the background it killed the complete process. Service_Destroy was never called in those cases.

Starting from Android 8, when the app is in the background (no activities and no foreground services), the OS can kill services without killing the process. In those cases the Service_Destroy sub will be called.
This means for example that we can no longer assume that the starter service is always running. It will be started when the process starts however later it can be destroyed.
You can call StartService or CallSubDelayed whenever an activity is resumed to make sure that the relevant service is started.
Note that process global variables are tied to the process and will not be destroyed when the service is stopped.

Update: Starting from B4A v8.3 the starter service will never be killed unless the whole process is killed. This means that you can always assume in your code that the starter service is running.
It is done internally by changing the starter service context to the application context.

I have a question about this.
Using B4A v8.80 with an Andriod 8 device, I have problems keeping my variables filled.

Like the MyLocation example, I use:
Sub Service_Create
    Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER 'we are handling it ourselves
Every time Service_Destroyed is fired. I read about "Service.StartForeground" preventing this from happening, but I don't need a Notification. After Destroyed, values of my variables are empty, even the one I put in Global of the Starter Service.

Do I need to save them and reload the every Service_Create or are there other possibilities?

Best regards,


Active Member
Licensed User
Process global variables will be kept as long as the process is alive. Specific services life cycle is not relevant here.

If the values were lost then it means that the process was killed. You can use Service_Create of the starter service to load their values.

KVS2 will be helpful for this.