Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 411
Ollie C Avatar asked Mar 04 '11 14:03

Ollie C


People also ask

Can we use REST API for mobile app?

Pragmatic REST is perfect for both mobile and web applications. The majority of developers will be familiar with this, but it could be difficult to adapt this architecture as time passes. Web service is not suitable for mobile apps, so it's not something you should be considering right now.

Can we use REST API in Android?

We can easily create a restful web service application in android to authenticate or save information into the external database such as oracle, mysql, postgre sql, sql server using other application developed in java, .


3 Answers

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.

like image 56
Robby Pond Avatar answered Oct 07 '22 15:10

Robby Pond


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.

like image 45
Vladimir Ivanov Avatar answered Oct 07 '22 13:10

Vladimir Ivanov


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.

like image 38
Dmitry Ryadnenko Avatar answered Oct 07 '22 13:10

Dmitry Ryadnenko