How to destroy service and close app if running in the background

aaronk

Well-Known Member
Licensed User
Longtime User
Hello,

I am using multiple activity's and a service.

My service connects to a socket to get data and will stay open so it can receive events etc. which is fine.

However I want to destroy the service/socket if my app is running in the background or if the user presses the home button.

Is there a way to tell by using the service if my app is running in the background so I can close this socket connection?

Each of the activity's uses this socket connection to display data, so by saying when the activity closes to destroy the service, will not work as when you close one activity another one might open and I don't want to re-connect to the socket every time you change the activity.

Anyone got any ideas on how to do this or know how to detect if the app is not visible on the screen?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
How do you want to handle an incoming phone call? Should it break the connection?

Here is one possible solution:
In your service create a sub named ActivityPaused and Activity Resumed:
B4X:
Sub ActivityPaused
 timer1.Enabled = True
End Sub

Sub ActivityResumed
 timer1.Enabled = False
End Sub

The timer should be initialized in Service_Create with an interval of 30 seconds. Close the connection in Timer_Tick event.

You should use CallSubDelayed to call these two subs from all of the activities.
 
Upvote 0
Top