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.
source share