Ollie C
Ollie C

Reputation: 28509

Android app architecture - where to put REST API call code?

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?

Upvotes: 12

Views: 3747

Answers (4)

Robby Pond
Robby Pond

Reputation: 73484

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.

Upvotes: 4

Dmitry Ryadnenko
Dmitry Ryadnenko

Reputation: 22512

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.

Upvotes: 1

bigstones
bigstones

Reputation: 15257

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)

Upvotes: 0

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43088

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.

Upvotes: 2

Related Questions