4

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!

SBotirov
  • 13,872
  • 7
  • 59
  • 81
  • 1
    I am using [nkzawa](https://github.com/nkzawa/socket.io-client.java) library to simulate _Gottox_ which even work with nodejs 1.x.x. And there is no need to create a separate thread, just a Service that keeps the socket alive. – Kush Dec 05 '14 at 07:20
  • @Kush Sharma Can i use this library with socket.io 0.9.18 ? – SBotirov Dec 05 '14 at 07:27

1 Answers1

1

Actually, I don't know is my way to use socket-io-client right, but I try to be completely clear. As I know socket-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:

public class SocketClient implements IOCallback {

    private SocketIO socket;
    private Context context; // for some cases (i.e. broadcasting via LocalBroadcastManager).

    public SocketClient(Context context) {
       this.context = context;
    }

    public synchronized void connect() {
        if (socket == null || !socket.isConnected()) {
            Properties properties = new Properties();
            // setting your properties...
            try {
                socket = new SocketIO("http://your.address", properties);
                socket.connect(this);
            } catch (MalformedURLException e) {
                Log.e("SocketClientException", e.getMessage());
            }
        }
    }

    @Override
    public void onDisconnect() {

    }

    @Override
    public void onConnect() {

    }

    @Override
    public void onMessage(String data, IOAcknowledge ack) {

    }

    @Override
    public void onMessage(JsonElement json, IOAcknowledge ack) {

    }

    @Override
    public void on(String event, IOAcknowledge ack, JsonElement... args) {
        LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("action_on"));
    }

    @Override
    public void onError(SocketIOException socketIOException) {

    }

}

Then I've created a Singleton that holds our SocketClient:

public class API {

    private static API instance;
    private SocketClient client;

    private API() {
    }

    public static API getInstance() {
        if (instance == null) {
            instance = new API();
        }
        return instance;
    }

    public void init(Context context) {
        client = new SocketClient(context);
    }

    public SocketClient getSocketIO() {
        return client;
    }
}

And then in the Service class onCreate() method I'am simply calling my singleton:

@Override
public void onCreate() {
    super.onCreate();
    Log.i("SocketService", "onCreate");
    API.getInstance().init(getApplicationContext());
    API.getSocketIO().connect();
}

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 via LocalBroadcastManager from on, onMessage methods in SocketClient.

SECOND WAY

Let's try to implement a SocketService:

public class SocketService extends Service implements IOCallback {
    private SocketIO socket;

    private synchronized void connect() {
        if (socket == null || !socket.isConnected()) {
            Properties properties = new Properties();
            // setting your properties...
            try {
                socket = new SocketIO("http://your.address", properties);
                socket.connect(this);
            } catch (MalformedURLException e) {
                Log.e("SocketClientException", e.getMessage());
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        connect();
    }

    @Override
    public void onDisconnect() {

    }

    @Override
    public void onConnect() {

    }

    @Override
    public void onMessage(String data, IOAcknowledge ack) {

    }

    @Override
    public void onMessage(JsonElement json, IOAcknowledge ack) {

    }

    @Override
    public void on(String event, IOAcknowledge ack, JsonElement... args) {
         LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("action_on"));
    }

    @Override
    public void onError(SocketIOException socketIOException) {

    }
}

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 :)

romtsn
  • 11,704
  • 2
  • 31
  • 49
  • thanks for great answer, but I've a question, your service running in main thread yes? I don't understand Why you don't create for separate thread for socket.io? – SBotirov Dec 01 '14 at 05:58
  • Maybe I am wrong, but as you can see in the link below, there is a separate thread that makes handshaking and connecting with the server. That thread starts when you call `SocketIO socket = new SocketIO(url, properties)`, so I think we no need to create one more separate thread to start `ConnectThread` inside it. I think it's redundantly. Link: https://github.com/Gottox/socket.io-java-client/blob/master/src/io/socket/IOConnection.java#L184 – romtsn Dec 01 '14 at 08:37
  • Vov, yes you are absolute right!, but I seen example gottox/socket.io, they are create separate thread for using socket io lib: https://github.com/Gottox/socket.io-java-client/blob/master/examples/chat/Chat.java . What about you for this? – SBotirov Dec 01 '14 at 09:16
  • What about your ideas for this https://github.com/Gottox/socket.io-java-client/blob/master/examples/chat/Chat.java ? – SBotirov Dec 01 '14 at 09:49
  • To be honest, I don't know why he is using a separate thread to "start another separate thread" :) I just think that it's because he has a habit to use separate threads when working with standard java sockets. I think using thread to start thread is redundant. In my experience, when I use socket-io, it's already working in the separate thread, so I have never had a "freezing UI" effect. Anyways, you can ask Gottox on the Github, why is he using yet another separate thread. – romtsn Dec 01 '14 at 10:35