首先,在配置文件里添加权限
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
1、可先在Application的onCreate()或者Server(onCreate)方法里面实例化一个WifiManager.MulticastLock 对象lock,具体实现如下:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
SerialHandler.getInstance().ScanGatewayInfo(wifiManager);
2、在调用广播发送、接收报文之前先调用lock.acquire()方法,之后及时调用lock.release()释放资源;
3、用完之后及时调用lock.release()释放资源,否决多次调用lock.acquire()方法,程序可能会崩,详情请见
4、写一个UDP帮助类,这个类主要用于发送和接收数据
注:如果在一个APP里面有两个socket并且使用同一个端口,则要设置地址重用
socket.setReuseAddress(true);public class UDPHelper implements Runnable { private static final String TAG = "UDPHelper"; private Context context; private WifiManager.MulticastLock lock; private DatagramSocket socket = null;public UDPHelper(Context context, WifiManager wifiManager) { this.context = context; this.lock = wifiManager.createMulticastLock("localWifi"); //获取本地IP地址 WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); Constants.APP_IP_ADDRESS = TransformUtils.intToIp(ipAddress); TransformUtils.SplitToIp(Constants.APP_IP_ADDRESS); } @Override public void run() { StartListen(); } public void StartListen() { // 接收的字节大小,客户端发送的数据不能超过这个大小 byte[] message = new byte[1024]; int num = 0; try { // 建立Socket连接 if (socket == null) { socket = new DatagramSocket(null); socket.setReuseAddress(true); socket.bind(new InetSocketAddress(Constants.UDP_PORT)); }while (num < 10) {//接收10次 num++; Thread.sleep(1000); // 准备接收数据 lock.acquire(); DatagramPacket packet = new DatagramPacket(message, message.length); try { socket.receive(packet);//接收数据 } catch (InterruptedIOException e) { System.out.println("continue...................."); continue; //非阻塞循环Operation not permitted } String str_message = new String(packet.getData()).trim(); String ip_address = packet.getAddress().getHostAddress().toString(); int port_int = packet.getPort(); } } catch (Exception e) { e.printStackTrace(); } finally { Log.e(TAG, "Exception"); lock.release(); killThread(); } } public void killThread() { try { if (socket.isConnected() & socket != null) { socket.close(); } } catch (Exception e) { e.printStackTrace(); } }