Search code examples
androidandroid-serviceandroid-service-bindingandroid-sharedpreferencesandroid-xmlpullparser

What is the best way to handle this background process while updating UI?


My app will update a list of bus routes once every 2 weeks from the transit API in the background as a service and will store the list in sharedpreferences. When the user starts the app for the first time the app will start a service in the background which will download the XML data, parse it and store the routes in the sharedpreferences file as an ArrayList.

The launcher activity is a map, but if, while launching the app for the first time, the user navigates to the "list of all bus routes" activity, then the screen will be blank while the XML is being parsed. If they have a slow data connection then it will stay blank for some time. I was thinking of showing a spinning loader while the service is finishing up before showing the list in the UI, but I'm not sure how to sync the spinning loader to the background service. Any suggestions as to how to approach this problem would be greatly appreciated.

Thanks.


Solution

  • I would use broadcast intents for the communication. You can have a ProgressBar in your UI that is hidden by default, but you show it if the data does not yet exist. You register a BroadcaseReceiever in your bus routes list activity (and unregister it in the appropriate place) and your service can send the broadcast intent when it's finished. If nothing is registered to receive it, it just won't get handled. However, if the case you've described occurs, you get notified that the data is now ready. Hide the spinner, show the data.