I found code to send message on UDP protocol which works as below.
public class SendUDP extends AsyncTask<Void, Void, String> {
String message;
public SendUDP(String message) {
this.message = message;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Void[] params) {
try {
DatagramSocket socket = new DatagramSocket(13001);
byte[] senddata = new byte[message.length()];
senddata = message.getBytes();
InetSocketAddress server_addr;
DatagramPacket packet;
server_addr = new InetSocketAddress(getBroadcastAddress(getApplicationContext()).getHostAddress(), 13001);
packet = new DatagramPacket(senddata, senddata.length, server_addr);
socket.setReuseAddress(true);
socket.setBroadcast(true);
socket.send(packet);
Log.e("Packet", "Sent");
socket.disconnect();
socket.close();
} catch (SocketException s) {
Log.e("Exception", "->" + s.getLocalizedMessage());
} catch (IOException e) {
Log.e("Exception", "->" + e.getLocalizedMessage());
}
return null;
}
@Override
protected void onPostExecute(String text) {
super.onPostExecute(text);
}
}
and below function for fetching broadcast IP address of device connected in the LAN network through which all other devices in the LAN will receive this message.
public static InetAddress getBroadcastAddress(Context context) throws IOException {
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
// handle null somehow
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) (broadcast >> (k * 8));
return InetAddress.getByAddress(quads);
}
and this will send UDP message after executing this as
new SendUDP("Hello All Device").execute();
It works like a charm!