What is causing multicast messages not to flow immediately after wifi restart

Viewed 462

I have an Android app that creates a MulticastSocket, joins a MC group and receives messages from another machine on the local wifi network.

MulticastSocket socket = new MulticastSocket(null); // Create an unbound socket.
socket.setSoTimeout(LISTEN_TIMEOUT_MILLIS);
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(listenPort)); // Bind to the configured multicast port

final WifiManager.MulticastLock lock = wifiManager.createMulticastLock("my_lock");
lock.acquire();

socket.setNetworkInterface(networkInterface);
socket.joinGroup(multicastGroup);
while (true) {
    socket.receive(packet);
    // Do something with the packet
    // Handle timeout etc.
    // Handle change of network interface by leaving group, setting netIntf and joining group again.
}
socket.leaveGroup(multicastGroup);
socket.close();

lock.release();

Works well on most Android devices (Huawei, Samsung), but on some (Pixel3), if the WiFi on the device is switched off and then back on again, while the app sees the Wifi connection come live, it can take up to 14 mins (it is extremely variable) before the MC messages start being received again.

Even throwing away the Socket and creating a fresh MCSocket doesn't alleviate the delay.

But it has to be some state that is held within the JVM, because a restart of the app causes it to connect immediately.

It feels like there is some lease that is being held for the MC connection that is only being renewed on a clock cycle.

So my questions are:

  1. What is causing the MC messages to not flow immediately after the WiFi connection comes back up and a new MCSocket is created to listen to it.
  2. What can I do to ensure timely resumption of the message flow?
1 Answers

I notice you've updated your question to include WifiManager.MulticastLock

I wonder if you are you reacquiring the lock when the Wifi connection comes back, some posts here on SO imply this is necessary.

I note the comment on the following post:

Re: https://stackoverflow.com/a/4002084/1015289

it turns out that your multicast lock is destroyed when the connectivity goes away (the long delay was me rewriting my code three times before I figured this out). So, you have to reacquire the lock every time the connection comes back

Related