如何在android上接收广播包

时间:2016-10-23 12:18:18

标签: android broadcast

我试图实现我的应用程序能够接收一些广播消息。一台设备向192.168.2.255发送消息。我可以在Wireshark上看到它的工作原理。我的应用应该收到这些消息,但它还没有工作。这是我的代码:

mariadb-server

该程序卡在dsocket.receive(数据包)行上。当其他设备发送数据包时,我的应用程序中没有任何内容到达。

我尝试过这些权限:

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);
    }

知道它为什么不起作用?进一步的权限? Android设备上的设置?

1 个答案:

答案 0 :(得分:1)

此问题与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" />