Android - jmdns doesn't discover devices

后端 未结 2 1793
慢半拍i
慢半拍i 2020-12-23 12:22

I\'m trying to implement a class to discover services on the network. I\'ve tried working with Android\'s NSD and it does discover the services fine, but it supports only AP

2条回答
  •  一生所求
    2020-12-23 12:59

    If you are having this error in Android Oreo 8.x, this might help you.

    First, Remember to make sure you have added these permissions into your Android manifest.xml.

    
    
    
    

    Acquire a multicast lock to allow multi-cast packets.

    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    MulticastLock lock = wifi.createMulticastLock("jmdns-multicast-lock");
    lock.setReferenceCounted(true);
    lock.acquire();
    

    Now, use only this constructor JmDNS.create(InetAddress addr, String name) to create an instance of JmDNS and bind it to a specific network interface given its IP-address, like this:

    try {
        jmDNS = JmDNS.create(InetAddress.getByName(obtainIPv4Address(info)), HOST_NAME);
    } catch (IOException e) {
        LogHelper.e(TAG, "Error in JmDNS creation: " + e);
    }
    

    Finally, just make sure to call JmDNSunreisterAllServices(), and JmDNS.close() to stop JmDNS stream and releases any system resources associated with it. Also, call MulticastLock.release() to unlock the multicast lock when you're done with it.

    try {
        if (jmDNS != null) {
            jmDNS.unregisterAllServices();
            jmDNS.close();
            jmDNS = null;
        }
        if (lock != null) {
            lock.release();
            lock = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    

提交回复
热议问题