只是贴代码,以前写的突然忘记了.
private WifiManager.MulticastLock multicastLock; public void init(Context context){ WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); multicastLock = wifiManager.createMulticastLock("my_net"); } public byte[] fetchData(){ try { multicastLock.acquire(); MulticastSocket multicastSocket = new MulticastSocket(55551); InetAddress group = InetAddress.getByName("224.0.0.2"); multicastSocket.setSoTimeout(3000); multicastSocket.joinGroup(group); multicastSocket.setLoopbackMode(true); byte[] buffer = new byte[512]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); multicastSocket.receive(packet); return buffer; } catch (Exception e) { e.printStackTrace(); } finally { multicastLock.release();//一定要释放 } return null; }
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
原文地址:http://blog.csdn.net/birdsaction/article/details/42395191