I’m new to Android development, i’m trying to port an IOS app to Android. Basically my App need to communicate with a server in real time with socket IO. It connect to the server and then handle the various message until the server finish to process the request.
In my IOS app i use a Singleton pattern to send the requests to my websocket server, and i use the same instance to delegate the server response.
In Android i was going to use the same pattern, with a callback object in my activity to redirect the user after getting a server response.
I need my app to keep the socket connection open until we got the right status from the server, even if the app goes in background.
Some people recommend using Service with Broadcast receiver instead of Singleton. Is it the best thing to do in my case ?
Using a
Serviceis exactly what I have done for very similar purposes (doing socket communication for Bluetooth and TCP/IP applications) and think you’ll certainly want to be using aServiceif the communication should continue even when the user has closed the application.A
Serviceis essentially a means to run code on the UI thread (but of course you can then start off other threads within it) but without a user interface, unlike anActivitywhich has a UI associated with it.If you were to try to do this in a static singleton class as you propose as an alternative, then I think the problem would be that you wouldn’t have very good control over the lifecycle of it. If the user navigates away from the application, then my understanding is that it’s up to the framework when it chooses to remove the process and all the static objects along with it. For this reason, if you have singleton classes populated with data and you exit your application and then later come back to the application, you may or may not find that the ‘old’ singleton instances are still around. For this reason, in my application (which uses a very large amount of global state) I’ve resorted to holding my singletons’ actual instances in an extension of the
.Applicationclass, to (hopefully) better control their lifecycle.With a
Serviceyou have a well-defined lifecycle with appropriate lifecycle callbacks (onCreate(),onDestroy(), etc.) just as you do with anActivity.