12

I want to better understand how to structure an Android app where an activity fires off an API call (for example).

I'd currently implement it by putting the API call into an AsyncTask subclass, passing it a reference to the activity so it can update the UI in onPostExecute. But my gut-feel is that this is creating overly-coupled code.

I'm wondering whether instead I should put an API call like that into a service, and use a BroadcastReceiver to update the activity.

What say you, AsyncTask, or BroadcastReceiver?

Ollie C
  • 28,313
  • 34
  • 134
  • 217
  • Don't know if you've watched this already, but there is a wonderful Google IO presentation on RESTful architecture in Android: http://www.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html – danh32 Mar 04 '11 at 15:14
  • I'll post a link to a talk on a related subject from Google IO 2010 http://developer.android.com/videos/index.html#v=xHXn3Kg2IQE He seems to suggest always using a service, but I wonder if he would in a simple scenario. – Ollie C Mar 04 '11 at 16:52
  • Ha! I posted the link before seeing your note Dan, you obviously told me about this video through ESP :) Thx – Ollie C Mar 04 '11 at 16:53

4 Answers4

4

I usually follow the Local Service pattern. I have a strong suspicion that this is how the official Twitter app works and that this is the pattern most of the Google apps use. This also solves the issue of your app going away (getting killed or going into the background) before the task finishes, or if the phone switches configuration during a background task.

Community
  • 1
  • 1
Robby Pond
  • 73,164
  • 16
  • 126
  • 119
2

BroadcastReceiver and service is an overhead here. A request to web-service should not go to long. Service is appropriate in case of downloading files or something similar.

AsyncTask way is the right one here. But I would suggest you showing a progress dialog to let user know that your application isn't freezed, but doing some useful work.

See the example here.

Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
1

AsyncTask is just fine. Only thing you should worry about is referencing you Activity using WeakReference to avoid whole Activity be memory leaked. It isn't overly-coupled code imo if you using observer or events patterns.

Dmitry Ryadnenko
  • 22,222
  • 4
  • 42
  • 56
0

I would go with a service only if the call is going to take long, so that the user can leave the app while it's completing.

I'd use the AsyncTask if the task is short enough that it almost wouldn't go ANR if done in UI thread.

(disclaimer: I consider myself a beginner, and I'm expecting comments from more experienced people)

bigstones
  • 15,087
  • 7
  • 65
  • 82