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(""));

byte[] recvBuf = new byte[255];
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
try {
} catch (IOException ex) {
Log.d("D", String.format("No broadcast message: %s", ex.getMessage()));
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");
//the receive code listed above
// at the end of this code

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

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

2 Responses to Android: UDP broadcast message is not received

  1. zhangzida says:

    it save my time,thanks

  2. serge says:

    Many thanks! For a long time I searched a decision for this problem.

Leave a Reply

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

You are commenting using your 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: