I have a service. I create a Thread
for using socket.io-java-client
library on separate thread in this Service.
I keep thread with following way:
@Override
public void run() {
while (canLiveThread) {
// keep thread
}
}
And this way fully wrong yes? To fix this solution I need find answer to following questions:
1. Are need to me create separately thread to use socket.io-java-client library in Service? Or I can use this library without thread, simply implement socket.io-java-client library in Service?
2. If need create thread to use this library, then how to manage thread with right way to not draining battery in background Service?
If anybody have any Solution, please answer to this question ...
Thanks in Advance!
Actually, I don't know is my way to use
socket-io-client
right, but I try to be completely clear. As I knowsocket-io-client
is already using background threads to connect, send, receive events.FIRST WAY
I think that it's not what you want, but I show this variant as possible. So, firstly, I've created a
SocketClient
, like this:Then I've created a Singleton that holds our
SocketClient
:And then in the
Service
classonCreate()
method I'am simply calling my singleton:After that the socket will be alive as long as a
Service
, so we will be able to receive, send socket commands in background via our singleton from anywhere in our application. We can send received data viaLocalBroadcastManager
fromon
,onMessage
methods inSocketClient
.SECOND WAY
Let's try to implement a
SocketService
:That's all. You can startService from your activity and communicate via broadcasts or messagehandlers. I have never tried the second way, but I think it should work like a charm.
CONCLUSION
No one of this methods uses separately background threads, and it's working for me, I have three apps based on the first way, and all of them are working in background without any supporting things. Hope the answer will be helpful for all interesting in
SocketIO
usage :)