问题
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.
回答1:
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
回答2:
GCM is the correct way to handle this. Send the GCM alert to the device and then the user can click it to open your app. At that time you can re-open your socket and get the data needed.
If you ever plan to deploy your app to iOS this is the route you will be taking there. iOS kills your background tasks after 5 minutes or less if it feels like it.
来源:https://stackoverflow.com/questions/34404728/continuously-running-socket-io-service-in-android