android - android接收广播包的方法

标签 android broadcast

我正在尝试实现我的应用能够接收一些广播消息。一台设备向 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/

相关文章:

android - 透明小部件背景?

android - 媒体播放器-NuPlayerRenderer : possible video time jump of x ms

python - Numpy,通过迭代替换广播

android - 在 CMake 中使用外部 C++ 库时出错

android - 转到 API <= 10 中的新 Activity 时如何清除后台堆栈

android - Flex 4.5.1 和 iOS、Android 开发

c - UDP 发送者和接收者同时 C

android - 使用广播接收器android关闭应用程序

c# - 如何广播HTTP请求?

request - 手机在捕获 Wi-Fi 探测请求时不会发送所有存储的 ssid