1

How can I make my Android phone receive UDP broadcasts?

At the moment i am testing my app using a tablet and a phone. The problem is that only the tablet can work as a server, not the phone.

The scenario of my app where the problem is: - Client is sending broadcast in a local network - Server is receiving this broadcast and sending a response to the client directly

I am pretty sure I think I know what's wrong as the app only works when the server is running on the tablet and that is that the phone can't receive broadcasts by standard.. So how do I get around this?

I have tried implementing the following code for the server to make it receive broadcasts:

WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        if (wifi != null){
            Toast.makeText(getApplicationContext(), "WifiLock create!", Toast.LENGTH_LONG).show();
            WifiManager.WifiLock lock = wifi.createWifiLock("mylock");
            lock.acquire();
        }

Also, I have the following permissions in my app:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<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.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />

Does anyone know how this can be solved? Thanks in advance

Langkiller
  • 3,377
  • 13
  • 43
  • 72

1 Answers1

1

By default Android Block all broadcast wifi messages to save power. You must create a wifilock object and the aquire the lock to allow the broadcast messages. See here for more info: WIFILOCKS

Ricky
  • 258
  • 2
  • 11
  • Thanks for your answer. But I am already trying to do that with the code in my question. Is something wrong with my WifiLock? WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE); if (wifi != null){ WifiManager.MulticastLock lock = wifi.createMulticastLock("mylock"); lock.acquire(); } – Langkiller Mar 11 '14 at 08:28
  • For some reason it wouldn't work on my own android phone. Seems that it blocked the broadcast no matter what. Tried it on another phone (With API 10) and it worked perfectly.. Thanks for your answer. I'll accept it, as it still is the solution to the problem. – Langkiller Mar 13 '14 at 11:21