I'm trying to work out if bound service is appropriate for doing background work in my app. The requirements are that various application components can make web requests through it of varying priority. (Thus the service must maintain some sort of queue and be able to cancel it's ongoing requests for others of higher priority). I'd like the service to be relatively unobtrusive to the user such that they don't find it running after they are done with the application - if I want to do something more important that continues while the application is closed I can use startForeground() to push a notification during the process.
Solution the first: bind from the activity
So, for a given application component it should be able to bind to the service to get work done. But there seems to be a well known problem that if an activity is doing the binding, the binding will be lost during configuration change (rotation) as the activity will be closed.
So, I was thinking I could use another context that I create (new Context()
) and bind from that to the service, then use a non-UI fragment to maintain this context across config changes until I deem that I am finished with it. I could do this only during the configuration change or as a permanent alternative to binding from the activity. (I should probably point out that this is a standard and recommended way to maintain instances across config changes)
Solution numero 2:
The main alternative I see is that I can use the application context to do the binding - but could this persist too long? and/or could there be some cyclic relationship between the app context and the service thus preventing the service and the app context being destroyed?
Questions:
So the question I'm trying to answer to myself is: should I use the first method (activities with temporary contexts)? Or the second (just bind service to the app context)?
Am I right in thinking the app context can bind to the service multiple times and then unbind from it the same number of times? (I.e. that you can have multiple valid bindings PER context)?
Could using my own context (new Context()
) in the first solution cause any issues?
Edit
Found some more information: https://groups.google.com/forum/#!topic/android-developers/Nb58dOQ8Xfw
It also seems that it will difficult to 'create' a context arbitrarily so a combination of solution 1 and 2 seems appropriate where the service connection is maintained across the configurations change but the binding is to the app context. I am still concerned about the possibility of unbinding twice from the app context. Keeping count of the bindings myself seems unnecessary - can anyone confirm/deny that bindings are per connection and not per context?