Q:

Continuously Running Socket.io Service in Android

I am developing a chat client using Socket.io as a means of communicating with the server. As such, using GCM is not exactly an option.
I want be able to receive chats at any time (even if the application is closed); essentially the socket needs to be listening at all times. I understand that a service can be started when the phone boots and kept running. However, this seems to be a rather bad idea on a mobile device, draining battery and the like.
Researching, it seems that GCM is the most common implementation for this sort of issue. Unfortunately, I cannot replace Socket.io at the moment. I was wondering how I would go about implementing this chat design - having a socket listening in the background.

A:

You should run one service(e.g. ListenerService) when your application start and inside that service you must start one thread(e.g. ListenerThread). And keep that thread and service alives till your application is in onResume()/onPause(). Through that thread connect your client socket to server. and receive all updates on ListenerThread. and if you want send some packets to server then send on another thread/handler(e.g tempThread) and close that thrad after sending request.
When your application close/exit then stop that service(e.g ListenerService). And In that service you must sleep ListenerThread.
Do not try to stop thread for more information about thread you can follow this link and this link. Thread.stop() is deprecated in android from API level 1, please see document.
Start service(ListenerService) with START_STICKY. for reference please refer android documention of service

