There are multiple ways to approach this problem (REST, WebSocket, etc.) I recommend using sockets in this case but I’ll leave it up to you to read up on the pros/cons of different approaches.
Socket.IO has a popular Android library for real-time bidirectional event-based communication between two nodes.
At a high level, to use Socket.IO in your application, you first need to create an instance of it. This will allow you to send and receive messages. For example:
private Socket mSocket;
mSocket = IO.socket("http://chat.socket.io");
mSocket.connect();
To send a message, you need to emit
to an event. Let’s call this event "new message"
. The following code sends a message using emit
.
mSocket.emit("new message", message);
In a chat application, you would emit
a new message when the user clicks the Send button. In your specific case, you need to first get the value of your EditText
like this:
mEditText.getText().toString()
and then emit
your message in your Send button’s OnClickListener
.
Now that we know how to send a message, we need to know how to receive a message. To receive a message, you need to listen on an event, as opposed to emitting on an event.
mSocket.on("new message", onNewMessage);
The above line will listen for a "new message"
event, and execute the behavior set in onNewMessage
, which is a Listener
. In your chat application, you can update a TextView
with the new message by adding the logic in your Listener
.
mTextView.setText(message);
To recap, you need to:
- Create a Socket.IO instance
- When the user clicks Send, grab the text from the
EditText
and emit it - Listen for a message and update the
TextView
Details on implementation can be found in Socket.IO’s Android tutorial. I highly recommend that you take a look at this as it is a complete, working example.
Hope this helps!
2
solved Simple sharing text and number App(Client-side) over internet [closed]