Android: UDP broadcast message is not received

Recently, I ran into an interesting trouble: I created an application that can send UDP broadcast messages and an Android application that can receive them.
As easy as pie I thought, then I realized that the broadcast message is received on a few devices but not received on other devices…
First of all, the message was sent to the correct broadcast address, and the android code was also fine:

...
try {
DatagramSocket brsocket = new DatagramSocket(port, InetAddress.getByName("0.0.0.0"));
brsocket.setBroadcast(true);
brsocket.setSoTimeout(10000);

byte[] recvBuf = new byte[255];
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
try {
brsocket.receive(packet);
} catch (IOException ex) {
brsocket.close();
Log.d("D", String.format("No broadcast message: %s", ex.getMessage()));
return;
}
Log.d("D", String.format("Message received from: %s", packet.getAddress().getHostAddress()));
...

Using my Asus tablet or Sony mobile phone it worked properly, the broadcast message was received. Using my HTC Desire, there was no broadcast message at all.

And what is the solution? You should create a MulticastLock before reading from the socket. I don’t know why it needs for a few type of devices and why not for others, but this solves the problem.

So here is what you should do:

WifiManager wifi;
wifi = (WifiManager) parentContext.getSystemService(Context.WIFI_SERVICE);
MulticastLock mLock = wifi.createMulticastLock("lock");
mLock.acquire();
//the receive code listed above
...
// at the end of this code
mLock.release();

And of course, don’t forget to add the proper permission to the manifest:

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

One Response to Android: UDP broadcast message is not received

  1. zhangzida says:

    it save my time,thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: