My app is essentially a background service that needs to occasionally register an NSD
service (Bonjour
service) for the purpose of enabling discovery of a socket server run by the main background service (aka run by the app).
If I am reading the Android Bonjour Service doc correctly, this is how you start the Bonjour
service (abbreviated for conciseness):
mNsdManager = Context.getSystemService(Context.NSD_SERVICE);
mDiscoveryListener = new NsdManager.DiscoveryListener()
mNsdManager.discoverServices(
SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
...and this is how you stop it:
mNsdManager.unregisterService(mRegistrationListener);
Here the part I can't wrap my head around: if the main service goes down abruptly, any Bonjour
service that was registered at the time of the crash keeps running even though it no longer has a purpose (the socket server it helps discover is no longer around).
I can't event cleanup the zombie Bonjour
services when the main service is restarted because the mRegistrationListener
the service was initially registered with is also no longer around.
I suspect I am taking the wrong approach: how do I make sure I don't leave a mess of zombie Bonjour
services behind after the main service crashed?
Non-specific to Android Bonjour, you could try to handle the crash by setting up your service as is outlined in the answer here: Can I call a method before my application go to crash
If you can't set this up to make the unregisterService call, you should be able to set it up to use ActivityManager's API killBackgroundProcesses. This requires adding the permission to your manifest:
android.permission.KILL_BACKGROUND_PROCESSES