- you cannot send udp packets to the ui stream, so you need to create a new separate stream.
Just a quick fix ...
create the udpOutputData line:
String udpOutputData;
create a new thread in your code:
//-----UDP send thread Thread udpSendThread = new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(100); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (sendUdp == true) { try { // get server name InetAddress serverAddr = InetAddress.getByName(outputIP); Log.d("UDP", "C: Connecting..."); // create new UDP socket DatagramSocket socket = new DatagramSocket(); // prepare data to be sent byte[] buf = udpOutputData.getBytes(); // create a UDP packet with data and its destination ip & port DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, broadcastPort); Log.d("UDP", "C: Sending: '" + new String(buf) + "'"); // send the UDP packet socket.send(packet); socket.close(); Log.d("UDP", "C: Sent."); Log.d("UDP", "C: Done."); } catch (Exception e) { Log.e("UDP", "C: Error", e); } try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } sendUdp = false; } } } });
create a method to call every time you want to send some udp data:
public void sendUdp(String udpMsg) { udpOutputData = udpMsg; sendUdp = true; }
call the method and pass a line for the output every time you want to send the udp packet:
String s = "hello from app"; sendUdp(s);
source share