Broadcasting over Wi-Fi Direct
Shamelessly stolen from https://code.google.com/p/boxeeremote/wiki/AndroidUDP
Try getting you network connection this way:
InetAddress getBroadcastAddress() throws IOException { WifiManager wifi = mContext.getSystemService(Context.WIFI_SERVICE); DhcpInfo dhcp = wifi.getDhcpInfo(); // handle null somehow int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask; byte[] quads = new byte[4]; for (int k = 0; k < 4; k++) quads[k] = (byte) ((broadcast >> k * 8) & 0xFF); return InetAddress.getByAddress(quads);}
Then try sending a packet this way:
DatagramSocket socket = new DatagramSocket(PORT);socket.setBroadcast(true);DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(), getBroadcastAddress(), PORT);socket.send(packet);// If you want to listen for a response ...byte[] buf = new byte[1024];DatagramPacket packet = new DatagramPacket(buf, buf.length);socket.receive(packet);
Edit: From same page to read try this ...
WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);MulticastLock lock = wifi.createMulticastLock("dk.aboaya.pingpong");lock.acquire();serverSocket = new DatagramSocket(19876);serverSocket.setSoTimeout(15000); //15 sec wait for the client to connectbyte[] data = new byte[UDPBatPositionUpdater.secretWord.length()]; DatagramPacket packet = new DatagramPacket(data, data.length);serverSocket.receive(packet);lock.release();String s = new String(packet.getData());System.out.println(s);
Remember, that you need the following permission for it to work:
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>