1
私のアプリがブロードキャストメッセージを受信できるように実装しようとしています。 1つのデバイスが192.168.2.255にメッセージを送信します。私はWiresharkでこれがうまくいくのを見ることができます。私のアプリはこれらのメッセージを受け取るべきですが、まだ動作しません。これは私のコードです:androidでブロードキャストパケットを受信する方法
int port = 3123;
// Create a socket to listen on the port.
DatagramSocket dsocket = new DatagramSocket(port);
dsocket.setBroadcast(true);
// Create a buffer to read datagrams into. If a
// packet is larger than this buffer, the
// excess will simply be discarded!
byte[] buffer = new byte[1024];
// Create a packet to receive data into the buffer
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
// Now loop forever, waiting to receive packets and printing them.
while (true) {
// Wait to receive a datagram
dsocket.receive(packet);
// Convert the contents to a string, and display them
String msg = new String(buffer, 0, packet.getLength());
System.out.println(packet.getAddress().getHostName() + ": " + msg);
// Reset the length of the packet before reusing it.
packet.setLength(buffer.length);
res = msg;
Log.d("mainGate_bc", res);
}
} catch (Exception e) {
System.err.println(e);
}
プログラムはdsocket.receive(packet)という行にスタックされています。他のデバイスがパケットを送信している間は、アプリには何も着信しません。
これらの権限は、私が試した:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
任意のアイデアなぜそれが動作しませんか?さらなる権限? Android搭載端末の設定
おかげではなく、同じ結果:
は、だから、次のコードのようなものを必要としています。 – user3137385
コードは 'receive()'へのブロッキング呼び出しを克服していますか?そうでない場合は、定期的な割り込みを行うために[ここ](http://stackoverflow.com/questions/40055175/how-to-interrupt-a-blocking-call-to-udp-sockets-receive/40055466#40055466)を見てくださいブロッキングコールで – Onik
それはありません。しかし私はまた、受信を中断したくない。私は自分のアプリに到着していないような既存のメッセージを受け取りたい。 – user3137385