Reputation: 1947
I've read a lot on this subject but I can't seem to find some answer that could help me. I've modeled my application as frontend-backend. The backend is just a server that waits for incoming connections. The problem is I start the server as soon as the app starts and I no longer communicate with it. Now I need the server to communicate with the frontend telling it someone connected. I tryed using static methods but I get an error from being unable to update de UI from a different thead. How can I proceed? EDIT:
My server class
public class Server {
public static int uniqueID;
private final int port;
private final Boolean keepWorking;
private final String username;
public Server(int port, String username) {
this.port = port;
this.username = username;
keepWorking = true;
}
public void Start() {
try {
ServerSocket serverSocket = new ServerSocket(port);
while (keepWorking) {
Socket socket = serverSocket.accept();
MainActivity.SomeoneConnected();
}
serverSocket.close();
} catch (IOException e) {
Log.d("Error", e.getMessage().toString());
}
}
}
That's everything I need. The server to tell the frontend someone connected
Upvotes: 0
Views: 82
Reputation: 1652
You should look into AsyncTasks:
http://developer.android.com/reference/android/os/AsyncTask.html
or any sort of thread/handler implementaion. -There are plenty of examples of this online
Also consider the ruOnUiThread()
method of Activity.
All of these solutions are assuming your client/server architecute is contained within the same activity.
** Based on your edit:
you should either call MainActivity.SomeoneConnected();
using an instance of your activity with instance.runOnUiThread()
or create a handler on the Ui thread and post a runnable that calls MainActivity.SomeoneConnected();
from within the run()
method using handlerInstance.post(yourRunnable)
here is an example of how to create a Runnable:
How to run a Runnable thread in Android?
Upvotes: 1
Reputation: 31
The tool of choice for communication between Threads is the Handler.
Upvotes: 0
Reputation: 4567
I highly recommend you use Google app engine and google cloud messaging to do this, it has great support for Android and means you don't have to poll your server
Read more: http://developer.android.com/google/gcm/index.html
Upvotes: 0