Jimlin Jimlin - 20 days ago 10
Android Question

Socket.io android socket.on not work after user kill the app

I have socket.on in onCreate and it work fine at first.
However, when I kill the app, reopen the app and server receive the message from other person but android socket.on is not working.
But emit function still work.
Have any suggestion?

Below is roughly code.



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

try {
mSocket = IO.socket("http://192.0.0.1/");
mSocket.connect();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}

mSocket.on("chat message", onNewMessage); // not working after kill the app and reopen.

}

private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
String message;
try {
message = data.getString("message");
Log.d("message", message );
} catch (JSONException e) {
return;
}
});
}
};
@Override
public void onDestroy() {
super.onDestroy();

mSocket.disconnect();
mSocket.off("chat message", onNewMessage);
}


Android client Socket.io version is socket.io-client:0.7.0.
Server is Node.js and "socket.io": "^1.4.5".

Answer

I figure out the problem. When we kill the app and restart, socket will kill now socket and create a new one. So we have to emit a new event to server to join the original room. And it work fine now.