Internal error using Network Service Discovery in Android

Mazze picture Mazze · May 21, 2013 · Viewed 7.7k times · Source

During the first implementation of the NSDManager using the examples and the tutorial on the developer page , the application successfully started the discovery and found the devices.

However now it seems to be broken...

When the program is started, after some initialization, the code enters the following method and successfully run:

public void discoverServices() {
    Log.d(TAG, "Initializing discovery on NSD");
    mNsdManager.discoverServices(
            SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
} 

The log-message is received. After a good while (say approx 5 mins.) this is outputted from the program:

05-21 11:08:32.518: E/NsdCamera(12236): Discovery failed: Error code:0
05-21 11:08:32.518: W/dalvikvm(12236): threadid=12: thread exiting with uncaught exception (group=0x40c9c930)
05-21 11:08:32.518: E/AndroidRuntime(12236): FATAL EXCEPTION: NsdManager
05-21 11:08:32.518: E/AndroidRuntime(12236): java.lang.NullPointerException
05-21 11:08:32.518: E/AndroidRuntime(12236):    at android.net.nsd.NsdManager$ServiceHandler.handleMessage(NsdManager.java:338)
05-21 11:08:32.518: E/AndroidRuntime(12236):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-21 11:08:32.518: E/AndroidRuntime(12236):    at android.os.Looper.loop(Looper.java:137)
05-21 11:08:32.518: E/AndroidRuntime(12236):    at android.os.HandlerThread.run(HandlerThread.java:60)

Also from the services:

05-21 11:50:49.108: E/NativeDaemonConnector.ResponseQueue(8858): Timeout waiting for response
05-21 11:50:49.108: E/mDnsConnector(8858): timed-out waiting for response to 10 mdnssd discover 6 _http._tcp.
05-21 11:50:49.108: E/NsdService(8858): Failed to discoverServices com.android.server.NativeDaemonConnector$NativeDaemonFailureException: command '10 mdnssd discover 6 _http._tcp.' failed with 'null'

Error code "0" is described in the NSDManager class as an internal error. The major updates I did was the access to the context in the helper-class called NsdCamera. Here is some probably evil code-snippets:

Helper-class constructor:

public NsdCamera(CameraChooseActivity context) {
    mContext = context;
    updateUI =  new UpdateUI();
    mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);
    mServiceName = new Vector<NsdServiceInfo>();

Helper-class NSD initialization:

public void initializeNsd() {
    initializeDiscoveryListener();
}

public void initializeDiscoveryListener() {
    mDiscoveryListener = new NsdManager.DiscoveryListener() {

        @Override
        public void onDiscoveryStarted(String regType) {
            Log.d(TAG, "Service discovery started");
        }
        /**
         * A name check to see if the DNS discovery was correct. Checks if it contains 
         * AXIS and has the desired MAC address-space
         * @param hostname ,the inputted hostname from the discovery cycle
         * @return true if it's an Axis camera. 
         */
        public boolean nameCheck(String hostname){
            return (hostname.contains("AXIS") && hostname.contains("00408C"));

        }
        @Override
        public void onServiceFound(NsdServiceInfo service) {
            Log.d(TAG, "Service discovery success: " + service.getServiceName());
            if (!service.getServiceType().equals(SERVICE_TYPE)) {
                Log.d(TAG, "Unknown Service Type: " + service.getServiceType());
            } else if (nameCheck(service.getServiceName())){
                mServiceName.add(service);
//                  updateUI.execute(new BundleUI(mContext,service, null));
            }
        }

        @Override
        public void onServiceLost(NsdServiceInfo service) {
            Log.e(TAG, "service lost" + service);
            if(mServiceName.remove(service)){
                //TODO
                Log.e(TAG, "remove the view, service is lost");
            }
        }

        @Override
        public void onDiscoveryStopped(String serviceType) {
            Log.i(TAG, "Discovery stopped: " + serviceType);
            //Necessary??
            mServiceName.clear();
        }

        @Override
        public void onStartDiscoveryFailed(String serviceType, int errorCode) {
            Log.e(TAG, "Discovery failed: Error code:" + errorCode);
            mNsdManager.stopServiceDiscovery(this);
        }

        @Override
        public void onStopDiscoveryFailed(String serviceType, int errorCode) {
            Log.e(TAG, "Discovery failed: Error code:" + errorCode);
            mNsdManager.stopServiceDiscovery(this);
        }
    };
}

CameraChooseActivity -> onCreate is calling the helper-class

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camerachoose);

    //Setup the animation for the text in the Relativelayout
    mDescription = (TextSwitcher) findViewById(R.id.camera_add);
    mDescription.setFactory(this);
    mDescription.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
    mDescription.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
    mDescription.setText(getText(R.string.camera_add));

    //Building alert dialog
    mBuilder = new AlertDialog.Builder(this,AlertDialog.THEME_HOLO_DARK);
    mBuilder.setMessage(R.string.dialog_about).setTitle(R.string.action_about);
    mBuilder.setIcon(android.R.drawable.ic_dialog_info);

    mLayout = (RelativeLayout) findViewById(R.id.layout_camerachoose);

    //Initialize the NSD
    mNSDHelper = new NsdCamera(this);
    mNSDHelper.initializeNsd();

Answer

Zephyr picture Zephyr · Sep 26, 2013

Base on my experience, I suppose this is a listener lifetime issue.

Because you supply two listeners to the system NSD service, one is for startServiceDiscovery() and another for stopServiceDiscovery(). you need to make sure these listeners still alive when the system accesses these listeners.

One fact is that onStartDiscoveryFailed() is called 2 minutes after startServiceDiscovery() is called, it should be a long time compared to the lifetime of the listener.

So if the listener is a local object and is released after calling the startServiceDiscovery(), it maybe cause the NSD service to crash.

public void stopServiceDiscovery (NsdManager.DiscoveryListener listener)

Stop service discovery initiated with discoverServices(). An active service discovery is notified to the application with onDiscoveryStarted(String) and it stays active until the application invokes a stop service discovery. A successful stop is notified to with a call to onDiscoveryStopped(String).

Upon failure to stop service discovery, application is notified through onStopDiscoveryFailed(String, int).

Parameters listener This should be the listener object that was passed to discoverServices(String, int, NsdManager.DiscoveryListener). It identifies the discovery that should be stopped and notifies of a successful stop.

and below snippet make sure do not call any NsdManager api.

@Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
     Log.i(TAG, "onStartDiscoveryFailed : Error code:" + errorCode);
}

@Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
    Log.i(TAG, "onStopDiscoveryFailed : Error code:" + errorCode);
}

Good Luck.