Repeating JmDNS device search

716 views Asked by At

I want to scan for Bonjour devices (_http._tcp.local.) every 5 seconds and get a arraylist with the found devices (the names, so strings). I need to do it in a service (and in a background thread).

Now I'm making every 5 seconds a new instance of JmDNS (JmDNS.create()) and that leaks memory ;). I think there must be a better way to do it, but I don't know it... Who can help me?

 try {
      final JmDNS jm;
      ArrayList<String> foundDevices = new ArrayList<String>();
      jm = JmDNS.create();
      jm.addServiceListener("_http._tcp.local.", listener = new ServiceListener() {
      @Override
      public void serviceAdded(ServiceEvent event) {
            jm.requestServiceInfo(event.getType(), event.getName(), 1);
      }

      @Override
             public void serviceRemoved(ServiceEvent event) {
      }

      @Override
      public void serviceResolved(ServiceEvent event) {
             JSONObject obj = null;
             ServiceInfo info = event.getInfo();
             //Log.e("TCLogging", "RAW: " + info);

             String Name = info.getName();
             foundDevices.add(Name);

             } catch (Exception e) {
                 Log.e("TCLogging", "Error");
             }
         }
      });
      ServiceInfo serviceInfo = ServiceInfo.create("_http._tcp.", "TC_" + android.os.Build.MODEL, 0, "AndroidApp");
      jm.registerService(serviceInfo);


      } catch (Exception e) {
          Log.e("TCLogging", e.toString());
      }
2

There are 2 answers

1
radical On BEST ANSWER

You could just call JmDNS.list(String type) every N seconds, which would return the ServiceInfo for the services it found. This first call will take time (you can control that via an overload of list(String type, long timeout)), default seems to be 6secs.

0
matthijs2704 On

Something I didn't know about JmDNS was that you get notified when a device is discovered or disappears in the network. I wanted to scan every N seconds to see what devices are in the network. But it's much easier (and less resource intensive) to just wait until you get notified of any device changes.

The accepted answer did work for me to achieve the scan every N seconds, but it's not the most ideal way to do it!