If you correctly understood that the main service (the one that has the server socket) registers / unregisters the Nsd service, and the background service starts / stops the detection of the Nsd service. I think this is what you are doing, so your “approach” is correct.
Regarding the issue, I should welcome you to Android Nsd . There are many errors with the framework (among which you can find your problem) that with Android 6.0 have not been fixed, but instead, developers use other frameworks.
Returning to the problem, you can try UncaughtExceptionHandler , just keep in mind that all callbacks are called by the system asynchronously, and you can get NPE when it calls mRegistrationListener.onServiceUnregistered() , because, as you said, “this is not around” .
As for cleaning the service, this is theoretically possible, but only after the NsdManager configures the source code (you need to change the access modifier of several methods to achieve and then unregister mRegistrationListener from another process that would lead to its removal from the NsdManager listener NsdManager ). But this makes no sense if the application should be published on the market.
There is another workaround with which you can try / experiment. If I remember correctly (it may be wrong), the necessary cleaning occurs after disabling Nsd . I tried this through adb :
// Disable adb shell service call servicediscovery 2 // Enable adb shell service call servicediscovery 2 i32 1
However, note that making these calls programmatically cannot be trivial and most likely requires root, which again limits the audience of your application.
Regarding the killBackgroundProcesses() method proposed by @thril, it takes a string with the name of the application package as a parameter. But servicediscovery not an application, it is a system service. In addition, you can try to kill the process (although I don’t know which one) at runtime, but be careful, you should study what effect it brings to the system, and be sure that the service will be resumed as necessary ( automatically through the system or manually). Again, a root is needed for this.
Summing up the answer, before embarking on Nsd , I highly recommend that you search for its functionality / errors to avoid a possible waste of time and effort. Some links in addition to the link above:
PS Personally, I, after struggling with several errors in the Nsd structure, eventually wrote my own framework.