Put your TCP connection code in the service, then connect to the Activity, if necessary. For example, see this
So, what happens when you need your main activity, it will connect to this service and disconnect when it goes into onPause state, and another action, which is in the foreground, will take over the management of the service and do what you need to do,
source share