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?
In android, by pressing a back button or home button. So put an event key listener for back & home button and terminate the service.
stopSelf() is used to always stop the current service. stopSelf(int startId) is also used to stop the current service, but only if startId was the ID specified the last time the service was started. stopService(Intent service) is used to stop services, but from outside the service to be stopped.
To start the service, call startService(intent) and to stop the service, call stopService(intent) .
But in order to keep a service alive like playing a song in a background. You'll need to supply a Notification to the method which is displayed in the Notifications Bar in the Ongoing section. In this way the app will keep alive in background without any interuption.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With