Buongiorno, sto facendo la mia prima applicazione in android e ho un problemino...
Ho creato una app che manda sulla porta 35555 in wifi dei messaggi UDP e l'ho installata su un cellulare.
Poi ho creato una app che si mette in ascolto sempre sulla porta 35555 e quando riceve un messaggio lo stampa
sul display (di un altro cellulare)
Io vorrei che funzionasse in continuo ma ricevo e stampo a video solo la prima volta e poi se rimando un messaggio, nulla non ricevo e non stampo.
Io ho fatto così:
nell'Activity nella funzione onCreate, creo il nuovo thread così:
new Thread(new UDPService());
e il thread è:
public class UDPService extends Thread {
//Create threaded server
UDPService () {
start();
}
public void run() {
System.out.println("Starting");
int port = 35555;
try {
// Create a socket to listen on the port.
DatagramSocket dsocket = new DatagramSocket(port);
// Create a buffer to read datagrams into. If a
// packet is larger than this buffer, the
// excess will simply be discarded!
byte[] receiveData = new byte[1024];
System.out.println("loop start");
while (true) {
DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
// Wait to receive a datagram
dsocket.receive(packet);
String sentence = new String(packet.getData());
TestoRicevutodaWifi.setText(sentence);
// Reset the length of the packet before reusing it.
System.out.println("setlength");
packet.setLength(receiveData.length);
}
} catch (Exception e) {
System.err.println(e);
}
}
}
In più per visualizzare l'unico messaggio che mi arriva devo far fare il refresh al display in manuale.
Grazie
Ciao
Walter