It seems multicast reception does not work on some Android devices. I can not receive multicast with 4 out of 13 test devices. On those 4 devices it seems the app does not send the IGMP request to join the multicast group.
The code to receive the multicast looks like so:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiManager.WifiLock wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, TAG);
WifiManager.MulticastLock multicastLock = wifiManager.createMulticastLock(TAG);
multicastLock.setReferenceCounted(true);
wifiLock.acquire();
multicastLock.acquire();
try {
MulticastSocket socket = new MulticastSocket(32123);
InetAddress group = InetAddress.getByName("224.1.2.3");
socket.joinGroup(group);
DatagramPacket packet;
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
socket.leaveGroup(group);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
multicastLock.release();
wifiLock.release();
The app has the following permissions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
To demonstrate the problem I created a little test project using the above code on GitHub: MulticastTest.
Is there a problem with my code? Do I miss a permission?
EDIT 1: This problem does not seem to relate to a specific Android version. I can reproduce the behaviour on Android 4.x, 5.x, and 6.x.
EDIT 2: There is a related question.