Implementation of Socket on Android Java Platform
Implementation of Socket on Android
Let us go through the steps for implementation.
I have ready fair amount of tutorials and videos. And finally able to get it running with little tweak.
Here goes the code.
Here we apply socket to MainActivity.java file. This is where we display different counts which changes based on the value emitted from socket.
We write this code before start of onCreate event.
private Socket mSocket;
TextView textview; // Here we display result obtained from server
{
try {
mSocket = IO.socket("https://your_server_name.com"); // http://chat.socket.io
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
Inside onCreate method:
textview = findViewById(R.id.tv_textview);
// Then inside onCreate method, initialise socket
mSocket.on("new message", onNewMessage);
mSocket.connect();// Here "new message" is the function we will observe.onNewMessage is is an object of the class Emitter.Listener.
We need to write function to read emitted data.
private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(final Object... args) {
if (args.length > 0) {
JSONObject data = (JSONObject) args[0];
String str_textview;
try {
// message = data.getString("message");
str_textview = data.getString("message");
Log.e("TAG_SOC", str_textview);
// Handle received message
} catch (JSONException e) {
e.printStackTrace();
return;
}
// add the message to view
addMessage(str_textview);}
}
};
Now in MainActivity Define the Class addMessage
private void addMessage(String str_textview) {
runOnUiThread(new Runnable() {
@Override
public void run() {
textview.setText(str_textview);
}
});
}
= = =
That's it.
The textview field will display the value it gets from server.
Comments
Post a Comment