Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what are best practices for performing network operations in Android? [closed]

what are best practices for performing network operation in Android (without the need for storing data in a ContentProvider) ?

currently I'm using a pattern similar to the one described in http://www.youtube.com/watch?v=xHXn3Kg2IQE - a service helper wrapped in a Fragment, an IntentService and a ResultReceiver.

this is pretty complicated and dirty.

is using something like a Fragment (with setRetainInstance(true)) which starts AsyncTasks with callbacks to the Activity good enough ?

I guess that I also need to handle cases where tasks are done when the activity is paused and then resumed.

is there a better strategy than the one is propsed here ?

EDIT: The network operations I'm referring to are interactions with simple JSON web services

like image 727
Gal Ben-Haim Avatar asked Dec 21 '22 02:12

Gal Ben-Haim


1 Answers

The network operations I'm referring to are interactions with simple JSON web services

The next question is then: how much do you care about the operation?

For example, if you are calling the StackOverflow API to retrieve some questions to display to the user, you probably do not care about the results if the user navigates away from the activity while the Web service call is going on. In that case, I'd just use Retrofit (or roll your own HTTP-and-JSON-in-a-background-thread code), kick it off from your retained fragment, and call it good.

An IntentService would come into play if:

  • You're more keenly concerned about the operation happening (e.g., you are modifying data on the server, not just retrieving it), and therefore want a service to help ensure your process is likely to live long enough for the work to complete, or

  • You are doing the Web service call on a scheduled basis (e.g., AlarmManager) or driven by other events (e.g., ConnectivityManager broadcasts), such as to deal with a Tape-backed queue of calls that need to be done once the device has Internet access, or

  • The results of the Web service call could impact more than just a single piece of your UI, and so therefore you want to have the Web service calls be "owned" by a component outside of your activities

For letting your UI layer know about the results from such an IntentService, I'd just just about anything else over a ResultReceiver. I like Square's Otto, but any event bus (e.g., greenrobot's EventBus) or LocalBroadcastManager would work.

SyncManager is also another alternative, though that's on my to-do list to get into.

However, I wouldn't necessarily describe any of these as "best practices", as Android's a bit too fluid for us to be in position to declare "best practices" in this area, particularly without a very precise description of the use case. They are "not completely ridiculous" practices.

like image 58
CommonsWare Avatar answered May 16 '23 08:05

CommonsWare