Android: Set up a multicasting socket

By on in with No Comments

Android: Set up a multicasting socket

Multicasting on Android can be quite the headache. Firstly, there’s the fact that for some obscure reason, certain devices doesnt even support multicasting, and secondly you need permissions and smart code to make it work at all. 

This example will only look at the receiving end. But sending data isnt that much different, really.

In your activity, we will create a new class that we will run in a separate thread (dont mess with the GUI thread, you hear me?!) that will handle the multicasting socket stuff.

public class MultiCastThread implements Runnable{
String text;
@Override
public void run() {
try {
multicast_address = InetAddress.getByName("239.224.224.1");
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// TODO Auto-generated method stub
try{
try {
socket_multicast = new MulticastSocket(1234);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket_multicast.joinGroup(multicast_address);
} catch (IOException e) {
e.printStackTrace();
}
byte[] bmessage = new byte[1500];
DatagramPacket p = new DatagramPacket(bmessage, bmessage.length);
socket_multicast.receive(p);
//Get the message
for (int i=0; i < bmessage.length; i++) {
text += Integer.toString( ( bmessage[i] & 0xff ) + 0x100, 16).substring( 1 );
}
socket_multicast.close();
 
handler.post(new Runnable() {
@Override
public void run() {
//Do your stuff here
}
});
} catch (Exception e) {
 
}
}
}

Hopefully this code is pretty much straight forward, though feel free to ask questions in the comments below if you’re stuck.

Now that our class is done, all we need to do is to run it..

Thread fst = new Thread(new MultiCastThread());
fst.start();

Lastly, you need to add the following permission to your manifest (I think).

<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"></uses-permission>
« »