我正在开发一个从 Wi-Fi 摄像头接收 UDP 广播数据包的应用程序。
在我发现 Google Pixel 2 / Pixel 2 XL 接收 UDP 广播包有问题之前一直都很好。
为了找出原因,我做了2个测试应用程序:一个是UPD广播发送器(https://senatech.box.com/s/gmhr391pbl32lqai0mhkffyk6j0ckle5 https://senatech.box.com/s/gmhr391pbl32lqai0mhkffyk6j0ckle5),另一个是UDP广播接收器(https://senatech.box.com/s/abamuor47nlafocs035nfuj90d0uvx0m https://senatech.box.com/s/abamuor47nlafocs035nfuj90d0uvx0m ).
我在一些Android设备上进行了测试,发现Google Pixel 2 / Pixel 2 XL无法接收UDP广播数据包。除 Pixel 2 / Pixel 2 XL 之外的 Android 设备运行良好。 Android 8.1 上的 Nexus 也运行良好。
我尝试搜索类似的问题,发现了一些诸如
Android 8.0 上未收到 UDP 广播数据包(https://bugreports.qt.io/browse/QTBUG-64233 https://bugreports.qt.io/browse/QTBUG-64233)。
我认为这可能是由于同样的问题造成的,尽管它是用 QT 编写的。
这是UDP广播发送器的简短代码
public void sendUPDBroadcast() {
Thread thread = new Thread() {
@Override
public void run() {
DatagramSocket ds = null;
int port = 0;
String udpData = "";
try {
port = Integer.parseInt(etPort.getText().toString());
udpData = etUDPData.getText().toString();
InetAddress ia = InetAddress.getByName("192.168.255.255");
ds = new DatagramSocket(port);
DatagramPacket data = new DatagramPacket(udpData.getBytes(), udpData.getBytes().length, ia, port);
ds.send(data);
} catch(Exception e) {
} finally {
if (ds != null) {
ds.close();
ds = null;
}
}
}
};
thread.start();
}
这是UDP广播发送器的简短代码
packet = new DatagramPacket(buffer, buffer.length);
socket = new DatagramSocket(port);
socket.setBroadcast(true);
@Override
public void run() {
try {
while (alive) {
try {
packet.setLength(buffer.length);
socket.receive(packet);
String s = stringFromPacket(packet);
} catch (java.io.InterruptedIOException e) {
} catch (java.io.IOException ex) {
} catch (Exception allException) {
} finally {
if (socket != null)
socket.close();
socket = null;
}
}
}
}
}
有没有人遇到过这个问题并解决它?
提前谢谢您。