I have built an application which implements a number of broadcast receivers and registers them within a service based on user settings. The service is bound to an activity which calls some of its methods. When a broadcast receiver is called it starts the service (or calls onstart of the service if it is already running) and passes it a string telling the service what to do. My problem is when the activity is destroyed (back button) the service is also destroyed which in turn kills the broadcast receivers.
I know I can register the receivers in the manifest which would mean doing a check when they are called to see if the user has selected that option. However one of the receivers critical to the application is 'android.intent.action.HEADSET_PLUG' which can only be registered programatically.
So I guess my question is, is there a way to keep this broadcast receiver active when the service is destroyed? If not can anyone see a workaround for this issue?
Thanks, Rob
If by "killed" you mean the user terminated your app with a task killer or "Force Stop" in the Settings app, then "killed" is the appropriate verb. However, your whole process is "killed" -- it does not follow the chain of events that you describe here.
If by "killed" you mean the user exited your activity via the BACK button, that is because you elected to bind to the service, rather than start it. If you want the service to continue executing past the lifetime of the activity, you must use
startService()
, and ensure that there is some path by which the user can indicate that they no longer want this service, so you know when to callstopService()
.No.
Start your service, instead of (or possibly in addition to) binding to the service.