EDIT: I'm specifically concerned about updating my toggle in the case where the service is killed.
I have an activity which I would like to show a toggle for users to start or stop a service. The activity should show whether the service is currently running, so the activity needs to know if the service is running.
This problem has been discussed here: How to check if a service is running on Android?
With two general strategies: 1) Use the activity manager to get a list of running services: ActivityManager.getRecentTasks(). Cons: is getRecentTasks is being deprecated and is slow.
2) Use a static field in the service class to toggle state. Cons: when the service is killed the service's onDestroy() method is not called. So the static variable cannot be updated in such a scenario and the activity could believe the service is running when it is not.
Is there a way to solve this problem that is more reliable? I could re-set the static variable to a time stamp every N seconds and if the activity sees that the static variable is too old, I'd know the service had been killed. That feels icky and would have race conditions.