0

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!

beenjaminnn
  • 752
  • 1
  • 11
  • 23
  • why can't your service/alarm send JSON back to the activity? have a look at [ResultReceivers](http://developer.android.com/reference/android/os/ResultReceiver.html) – panini Mar 13 '14 at 01:59
  • Pretty much all your bullets are wrong- you can return data from a service/alarm. You can always update the UI from another thread by just posting to a handler that does the actual UI changes. You can run an AsyncTask periodically. And you can always just make a Thread as well. Which is the best way to do it depends on frequency of updates, whether you want to do this while your app isn't in foreground, etc. – Gabe Sechan Mar 13 '14 at 02:02
  • My mistake, I want to update fairly frequently but only while my app is in the foreground; do you know which method would be best for this? – beenjaminnn Mar 13 '14 at 02:05

2 Answers2

0

Using a service/alarm I can't send my json back to the activity, use binder to create connection between Service and Activity, or broadcast to transfer data to trigger ui update

zjywill
  • 1,458
  • 2
  • 10
  • 14
0

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.

Community
  • 1
  • 1
beenjaminnn
  • 752
  • 1
  • 11
  • 23