Receive Broadcast Message on Android

At first - sorry for my English, I'm not a "native writer".

I am sending a broadcast message in C ++ and want to receive it on an Android device. I created the following code:

System.out.println("receiveBroadcast()"); DatagramSocket socket = new DatagramSocket(3866); socket.setBroadcast(true); System.out.println("Listen on " + socket.getLocalAddress() + " from " + socket.getInetAddress() + " port " + socket.getBroadcast()); byte[] buf = new byte[512]; DatagramPacket packet = new DatagramPacket(buf, buf.length); while (true) { System.out.println("Waiting for data"); socket.receive(packet); System.out.println(packet.getAddress()); System.out.println("Data received"); } 

It works when I compile it as a standard Java Java console application and run it on another computer connected to the network. It does not work on Android, and I have no idea why. On Android, it just waits for data, but never gets it:

 03-18 15:47:05.045: I/System.out(16651): receiveBroadcast() 03-18 15:47:05.055: I/System.out(16651): Listen on /:: from null port true 03-18 15:47:05.065: I/System.out(16651): Waiting for data 

Interestingly, when I run it as a standard Java console application on a Windows system, instead of "Listen on / :: from null port true", I get "Listen on 0.0.0.0/0.0.0.0 from null port true".

I have explicit permissions like this:

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

Please, help!

+6
source share
1 answer

I know this is an old thread, but I thought I shared it here, as it might help others in the future.

the famous code written here didn't help me in either solution 2 that I propose, as it depends on your device and os

In any case, you can try some of these solutions:

1- create a lock on your Wi-Fi so that it does not turn off after a while of inactivity

 WifiManager wifi; wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); WifiManager.MulticastLock mLock = wifi.createMulticastLock("lock"); mLock.acquire(); 

2- check this link here , as in some cases broadcast messages are blocked by the OS

0
source

All Articles