Search code examples
androidandroid-asynctaskbackground-processtimertask

Run code in background, then update UI on completion


In my app I need to fetch some json data periodically from the internet, then I want to update the UI of my app based on this data. How can I execute a background task and then update the UI on completion? Here are some problems I ran into:

  • Using a service/alarm I can't send my json back to the activity
  • Using an timer/timertask I can't update the UI because only the thread that created the views may change them
  • Using asynctask was working fine but I cannot run it periodically

I have been implementing a listener in my activity that is triggered when the json has been fetched. This seems like a straight forward thing to do, I'm sure there must be a solution!


Solution

  • Although adding a Binder between the Activity and the Service would have working, I ended up following resus's answer provided here. It uses a Handler to post a new task in the future in the method that is triggered by the AsyncTask's completion.

    This worked well for me because I had already set up a listener.