How to receive UDP broadcasts on an Android device

你离开我真会死。 提交于 2019-12-10 11:55:43

问题


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


回答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



来源:https://stackoverflow.com/questions/22296891/how-to-receive-udp-broadcasts-on-an-android-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!