gpt4 book ai didi

android - android接收广播包的方法

转载 作者:行者123 更新时间:2023-11-29 19:30:07 27 4
gpt4 key购买 nike

我正在尝试实现我的应用能够接收一些广播消息。一台设备向 192.168.2.255 发送消息。我可以在 Wireshark 上看到这有效。我的应用程序应该会收到这些消息,但它还不能运行。这是我的代码:

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 设备上的设置?

最佳答案

此问题与 this other question. 重复显然,除非您获得多播锁,否则广播数据包都会被过滤掉。

所以你需要类似下面的代码:

WifiManager wm = null;
MulticastLock multicastLock = null;

@Override
protected void onResume() {
super.onResume();
if(wm == null)wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
if(multicastLock == null){
multicastLock = wm.createMulticastLock("stackoverflow for the win");
multicastLock.setReferenceCounted(true);
}
if(multicastLock != null && !multicastLock.isHeld()) multicastLock.acquire();
}

@Override
protected void onPause() {
super.onPause();
if(multicastLock != null && multicastLock.isHeld()) multicastLock.release();
}


<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />

关于android - android接收广播包的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40202806/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com