I am to develop an Android application that receives a message from server but I can connect to server but can’t receive a message because when I clicked on Button connect blocks. I think it’s because of the cycle but do not know how to resolve this situation in another way and would appreciate your help.
In short I want to know if there’s another way to detect when I receive a message and presents it.
Update: I found the solution like this:
String IP;
String comando;
PrintWriter msgout;
BufferedReader msgin;
Socket socket;
private ConnectedThread mConnectedThread;
public void connect(){ //Function to Button connect
IP = edit.getText().toString();
try {
InetAddress serverAddr = InetAddress.getByName(IP); //TCPServer.SERVERIP
Socket socket = new Socket(serverAddr, 4444); //Porta 4444 serverAddr
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
msgout = out;
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
msgin = in;
zav.text1.setText("Connectado.");
//Wait to mensages
mConnectedThread = new ConnectedThread();
mConnectedThread.start();
} catch (Exception e) {
text1.setText("Erro! Não conectado." + e);
}
}
public void send(String message){
try {
msg.println(message);
} catch(Exception e) {
text1.setText("Erro! Comando não enviado." + e);
}
}
private class ConnectedThread extends Thread {
public void run(){
while(true){
//Read
try {
String str = msgin.readLine();
text1.setText(str);
} catch(Exception e) {
text1.setText("Error" + e);
}
}
}
}
Have you tried Push Notification? Here is a good place to start http://tokudu.com/2010/how-to-implement-push-notifications-for-android/