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