There's two ways you can go about doing this depending on if you want to keep the socket open when the user isn't actively using your UI.
The first is a LocalService
it's the same as a regular Service
except it runs in the same process as your Activity
s UI thread and therefore you can gain a direct reference to it. This is a much lighter method of creating and using a Service than using AIDL. I only recommend using AIDL if you wish to create an out-of-process service that needs to be accessed either by different processes in your application or in different applications. This is most likely not what you need. The LocalService method will allow you to keep the service running in the background and in turn keep the socket open even when the UI isn't in use.
If you don't have the requirement of keeping the socket open and only wish to have access to it from multiple Activity
s then you can extend the Application
class and register it in your manifest. It allows you to manage global application state. You can put the socket creation and management functions into that class and then provide methods for your various Activity
s to gain access to it. The Application
class dies when the process dies so it is not suitable for keeping a socket open for long periods of time or during times when the user is not actively using your application.
There is the built in Activity#getApplication()
method that helps with this process. You can specify your custom Application
class in the AndroidManifest.xml via the android:name
attribute.