Search code examples
androidmultithreadingjmdns

Implementing JmDNS on Android/Multithreading


I am trying to get JmDNS to work in my android program. I am able to get it to discover the devices I want, but I do not fully understand how to get the information from JmDNS to the object that started the JmDNS task. Here is my code.

 protected void browse() {       
      try {
        jmdns = (JmDNSImpl) JmDNS.create();

        jmdns.addServiceListener(type, listener = new ServiceListener() {
            public void serviceResolved(ServiceEvent ev) {

            }
            public void serviceRemoved(ServiceEvent ev) {                   

            }
            public void serviceAdded(ServiceEvent event) {    
                DNSEntry addressEntry = jmdns.getCache().getDNSEntry(name, DNSRecordType.TYPE_A, DNSRecordClass.CLASS_ANY);
                if (addressEntry instanceof DNSRecord) {
                    ServiceInfo cachedAddressInfo = ((DNSRecord) addressEntry).getServiceInfo(true);
                    if (cachedAddressInfo != null) {
                        for (Inet4Address address : cachedAddressInfo.getInet4Addresses()) {
                          //I need to get the address that is here back out of this listener to the main thread
                        }
                    }
                }
            }

        });
    } catch (IOException e) {
        e.printStackTrace();
    }

The problem I am running into is that I have a service manager object that has a instance of a browser object that has the browse method in it. I am unable to get the service manager object access to the address variable. Because JmDNS spawns its own thread when it is created to run its tasks I have tried to use a handler and runnable to send messages with the variable in it but I cant seem to get it right. Can anyone help?


Solution

  • I think you want to just use the ServiceEvent event object passed into the service added method. It has all the info you need.

    See this example from our open source application

    http://code.google.com/p/tunesremote-plus/source/browse/trunk/src/org/tunesremote/LibraryActivity.java