我目前正在使用SDK >= 16开发Android应用程序,该应用程序应该能够使用WiFi无线电在本地区域网络中发现不同的Android设备(稍后还包括iOS设备)。
我最初的想法是使用多播,但在我的三星Galaxy S2上无法正常工作:只有从同一设备发送时才能接收数据包。
我的第二个想法是使用有限的IP地址范围主动扫描网络并等待适当的响应。不幸的是,这意味着网络使用DHCP来分配IP地址。
以上两种解决方案都不是完美的解决方案。
我目前对第一个想法的解决方案是:
我最初的想法是使用多播,但在我的三星Galaxy S2上无法正常工作:只有从同一设备发送时才能接收数据包。
我的第二个想法是使用有限的IP地址范围主动扫描网络并等待适当的响应。不幸的是,这意味着网络使用DHCP来分配IP地址。
以上两种解决方案都不是完美的解决方案。
我目前对第一个想法的解决方案是:
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;
}
}
这段代码在socket.receive(recv)这一行会导致阻塞。如果我指定一个超时时间,就会抛出超时异常。