Android Question Terminating GPS

iCAB

Well-Known Member
Licensed User
Longtime User
Hi There

I have an application that displays multiple activities and needs to use the GPS as long as the app is running.

I added GPS as a service. The service is started using Main Activity create as follows
B4X:
StartService(GPSService)

After the activity completes initialization, it starts another activity and so on
The GPS service is being used to update some globally shared data structure to provide GPS data through out the app.

I want to properly terminate the service when the user closes the application so that the battery is not wasted.

I added the following code in the main activity that started the GPS service

B4X:
Sub Activity_Pause (UserClosed As Boolean)

    If UserClosed = True Then
        StopService(GPSService)
        Log("App closed, GPS stopped ")
    End If
    

End Sub

I never see the Log message.

What is the best way of terminating the service on app closed?

Thanks in advance
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Applications are never closed in Android. At some point when the app is in the background the OS will kill the process.

Specifically your code will never be called if the user presses on the home button.

If you want to stop the GPS when the app is in the background then you can use CallSubUtils to call a sub in the GPSService after 5 seconds from Activity_Pause.
In this sub you can check whether all activities are paused and if yes, stop the GPS.
 
Upvote 0

iCAB

Well-Known Member
Licensed User
Longtime User
Hi Erel

Thanks for the reply
Is there a cleaner way (an attribute or something), where a service is somehow automatically attached to the application life cycle.
 
Upvote 0

iCAB

Well-Known Member
Licensed User
Longtime User
In other words, what I was hoping for is the following:

Since the service is being started by our app, is there a way to tell the OS to kill the GPS service when it kills the process
Applications are never closed in Android. At some point when the app is in the background the OS will kill the process.


I am not sure if the suggestion in post #2 will work for our application( unless if I don't fully understand the concept ).
What I need to able to achieve is the following. As long as the application is running (background or foreground), I should be able to send messages to the app to report current GPS location. Currently this works. Whoever I need to stop the GPS service if the user terminates the app or the OS kills the process so that the phone battery is not drained.

Thanks again
 
Upvote 0
Top