I've recently written a small android application to send and receive UDP messages over a local network.
I have a UDP receiver thread that runs to listen for UDP packets, what I want to happen is a button to become enabled on the UI when a packet is received that contains a certain string of data. I know that this has to be done with a handler, the problem being that I have a small amount of knowledge about threads and very little knowledge about handlers.
would someone be able to shed some light on how a handler could be put into my code?
thanks
code:
public void startUDPlistener() {
// Creates the listener thread
LISTEN = true;
Thread listenThread = new Thread(new Runnable() {
@Override
public void run() {
try {
Log.i(LOG, "Listener started!");
DatagramSocket socket = new DatagramSocket(BROADCASTPORT);
socket.setSoTimeout(1500);
byte[] buffer = new byte[BUFFERSIZE];
DatagramPacket packet = new DatagramPacket(buffer, BUFFERSIZE);
while(LISTEN) {
try {
Log.i(LOG, "Listening for packets");
socket.receive(packet);
String data = new String(buffer, 0, packet.getLength());
Log.i(LOG, "UDP packet received from "+ packet.getAddress() +" packet contents: " + data);
}
catch(IOException e) {
Log.e(LOG, "IOException in Listener " + e);
}
}
Log.i(LOG, "Listener ending");
socket.disconnect();
socket.close();
return;
}
catch(SocketException e) {
Log.e(LOG, "SocketException in Listener " + e);
}
}
});
listenThread.start();
}