Moto G dosent receive UDP packets over WIFI Networ

2019-01-20 06:43发布

问题:

My receiver don't receive any UDP packet in Moto G but it works for other devices well.

Over WiFi network I have send UDP packets successfully from other devices. But in Moto E and Moto G it is not working.

Can anyone help figure out why it's not working for Moto G/E?

My problem was that i was not Receiving any UDP Packets over WiFi Network.

回答1:

Try this code. It's work for me.

 public void run() {
        Looper.prepare();
        try {
          WifiManager.MulticastLock lock;
          WifiManager wifi;

          wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
          if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
          if (lock == null)
          lock = wifi.createMulticastLock("WiFi_Lock");
          lock.setReferenceCounted(true);
          lock.acquire();
         }
      }
      catch(Exception e)
      {
        Log.d("Wifi Exception",""+e.getMessage().toString());
      }
    }


回答2:

I ran into the exact same problem! UDP packets would work on every phone except the Moto E. Then I found some very interesting information on the interwebz.

The problem was that the Moto E (and presumably the Moto G) requires the app to acquire WifiManager.MulticastLock. From the android documentation -

Allows an application to receive Wifi Multicast packets. Normally the Wifi stack filters out packets not explicitly addressed to this device. Acquring a MulticastLock will cause the stack to receive packets addressed to multicast addresses. Processing these extra packets can cause a noticable battery drain and should be disabled when not needed.

You need to add the following permission to your app -

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

And then in your code acquire a lock like so -

WifiManager wifi = (WifiManager)getSystemService( Context.WIFI_SERVICE );
if(wifi != null){
    WifiManager.MulticastLock lock = wifi.createMulticastLock("Log_Tag");
    lock.acquire();
}


标签: android udp