I am making an Android application that receives messages from an Arduino, I implemented a UDP server opening a Thread, but I can not get the value of the answer string "lastMessage", because with this value I will make a series of actions.
This is my class served_UDP:
public class Servidor_UDP {
private boolean server_activado = true;
private String lastMessage = "";
DatagramSocket socket;
private byte[] resp;
private DatagramPacket pqtResp;
Servidor_UDP()
{
resp = new byte[1024];
try {
socket = new DatagramSocket(6000);
pqtResp = new DatagramPacket(resp, resp.length);
} catch (SocketException e) {
e.printStackTrace();
}
}
public void start(){
Thread t = new Thread(new server());
t.start();
}
public class server implements Runnable {
server() { run(); }
public void run() {
String message = "";
try {
do
{
socket.receive(pqtResp);
//message = new String(resp).trim();
message = new String(pqtResp.getData(),0,pqtResp.getLength());
lastMessage = message;
} while(server_activado);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String getString()
{
return lastMessage;
}
public void setServer(boolean b)
{
server_activado = b;
}
}
This class I implemented from the onCreate of my MainActivity:
Servidor_UDP UDP_S;
UDP_S = new Servidor_UDP();
UDP_S.start();
I try to get the results of a method of the main class and show them in a TextView to make sure that the messages are arriving but it does not show me anything, just empty.
public void actualizarUI()
{
respuesta = UDP_S.getString();
txt.setText(respuesta);
}
I await your help, thanks in advance.
Your server()
constructor should not call run()
. Thread.start()
will do that. At present Thread.start()
is never executing, let alone completing, so any code that calls your start()
method will never return.