I'm new to android development so please be gentle :p I'm having trouble sending UDP packets from my android phone to my anrdiuno (with WiFi shield). I can send and recieve packets to or from the arduino using the TCP/UDP Terminal app from the Play Store, with no problems. For an easy beginners task I would like to send just one packet to my arduino (which is on my local network at address 192.168.0.101 and listens on port 5000), when I press a button, a message is then displayed saying that data has been sent. My current android code is below:
//CALLED WHEN USER PRESSES BUTTON
public void sendMessage(View view){
runUdpClient();
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText("MESSAGE SENT");
// Set the text view as the activity layout
setContentView(textView);
}
private void runUdpClient() {
try{
String msg = "Hello";
byte[] msgBytes = (msg.getBytes());
String serverHostname1 = new String ("192.168.0.101");
InetAddress ip = InetAddress.getByName(serverHostname1);
//SEND ON PORT 5000
DatagramSocket socket = new DatagramSocket(5000);
socket.setBroadcast(true);
DatagramPacket packet = new DatagramPacket(msgBytes,msgBytes.length, ip, 5000);
//packet.setAddress(ip);
//packet.setPort(5000);
socket.send(packet);
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
I have debugged the code and found that an exception is thrown when socket.send(packet) is called, (although i do not know how to view this expection). After stepping through the send function, this exception was thrown:
IllegalArgumentException("Packet address mismatch with connected address");
Please could someone help me with this please? Thank you ever so much for any help given :)
found a solution to this problem. If anyone else gets this problem the solution is to call the udp packet send function from inside a thread as such:
Found out that most communications need to be done inside a thread. Peace.