Search code examples
androidandroid-serviceandroid-service-binding

Performing Request After Android Service Binding


I have a two part question. Both are somewhat general.

  1. I'm creating an app that relies heavily on communication with a server. I plan to have different classes for each repository I'll need. Is an Android service the correct pattern to use here? There may be certain situations where I'll want to cache things between activities. Will a service allow me to do this?
  2. Assuming a service is what I want to use for this, how can I load content once the service is bound. When the user opens the app, I want to start loading content. However, binding a service isn't blocking, so I can't write the code that makes requests with the service in my onStart() right? Is there some helper class that will wait for the service to load then execute a function? I know I could put some code in my onServiceConnected() method but I'd like to stay away from coupling like that.

Hopefully that wasn't too abstract. Thanks in advance.


Solution

  • Yes, Service is the way to go, but a started service, not a bound one.

    You could make async request methods, and the Service can broadcast the result back to your Activity.

    • The async request in this case is a startService(intent) with an Intent containing the request parameters. The service would start a background thread for the operation, optimally you can use a networking library for this (for example Volley).
    • And the reply is a broadcast by the Service with the relevant data.

    This answers the problem of caching, because the Service can decide what to return. So in case the Service does not have the requested resource, it will download (and return) it. But if the Service has the resource, then it will just simply return the cached version.

    To start, you should get yourself familiar with these topics:

    I don't know much about your concrete needs, but it seems like you want to implement a REST client with cache. There is a really good Google IO presentation on that here. Definately worth to watch!