Discovery of devices in the local network

I am currently developing an Android application using SDK> = 16, which should be able to detect various Android devices (later also iOS devices) on the local network using WiFi radio.

My first assumption was to use multicast, which turned out to be invalid on my Samsung Galaxy S2: packets are only accepted when sending from the same device.

My second guess is to actively scan the network using a limited range of IP addresses and wait for a response. Unfortunately, this means that the network uses DHCP for the IP address.

None of the above solutions seem to be the ideal solution.

My current solution for my first guess:

public class MulticastReceiver extends AsyncTask<Activity, Integer, String> { private static final String host = "224.1.1.1"; private static final int port = 5007; private static final String TAG = "MulticastReceiver"; protected String doInBackground(Activity... activities) { WifiManager wm = (WifiManager)activities[0].getSystemService(Context.WIFI_SERVICE); WifiManager.MulticastLock multicastLock = wm.createMulticastLock("mydebuginfo"); multicastLock.acquire(); String message = "Nothing"; if (multicastLock.isHeld()) { Log.i(TAG, "held multicast lock"); } try { InetAddress addr = InetAddress.getByName(host); MulticastSocket socket = new MulticastSocket(port); socket.setTimeToLive(4); socket.setReuseAddress(true); socket.joinGroup(addr); byte[] buf = new byte[5]; DatagramPacket recv = new DatagramPacket(buf, buf.length, addr, port); socket.receive(recv); message = new String(recv.getData()); socket.leaveGroup(addr); socket.close(); } catch (Exception e) { message = "ERROR " + e.toString(); } multicastLock.release(); return message; } } 

This code blocks the line socket.receive (recv); If I specify a timeout, I get a timeout exception.

+6
source share
2 answers

Check out http://developer.android.com/training/connect-devices-wirelessly/index.html It mentions two ways to find local services: NSD and wifi direct.

+2
source

Check my answer in a very close question Android Network Discovery Service (ish) prior to API 14

I don’t believe multicasting doesn’t work on Galaxy S2, some time ago, when I encoded some kind of network application, I did some tests on many devices, some of which were older than G1, but also on S2, S3 and Galaxy Tab ten.

But in order to be able to use multicast, you must enable it programmatically.

Did you use this piece of code?

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

All Articles