Search code examples
androidandroid-servicegoogle-project-tango

Correct way of Starting Persistent Multithreaded Service in Android


I need to create a test application that will allows the starting/stopping of a persistent background service that runs several threads in the background. (Mainly a WebSocket Server and the Tango location Service). It needs to be persistent so I can start a web browser and connect to the ws socket.

According to what I read, the application should be structured as follows:

Activity -> Service (persistent) -> (Service (Tango) + Thread (WS))

The persistent service needs to be run as a foreground service using startForeground() and as a separate process (set in the manifest) so it doesn't close when the activity is closed.

Now, I got to questions : 1) Is my current understanding correct? Or am I approaching this the wrong way. 2) If I later want to stop the service, I want to start the activity and be able to stop it from there. How does the activity know that the service is running and how does it connect to it? Do I need to implement the binding part? How? 3) Could I achieve 2) using notifications instead and closing it from there?


Solution

  • This is the best I could come up with and so far it seems to work. However, if someone has a better way of implementing this or more "correct" I will change to that answer.

    The solution I went for boils down to what I stated above. The only thing is that I had to implement Runnable in new classes to pass the pointers around. It is very important that no network code is executed in the main thread of the Service, that needs to be in a separate thread.