Friday, June 19, 2015

Comparison between Android networking frameworks

Comparison between Android networking frameworks


Android Async vs Volley vs Retrofit performance benchmarks (milliseconds, lower value is better):


Framework
One Discussion
  Dashboard
 (7 Requests)
25 Discussions
AsyncTask
941 ms
4539 ms
13957 ms
Volley
560 ms
2202 ms
4275 ms
Retrofit + RxJava
(Using RxObservables)
312 ms
889 ms
1059 ms


Note:We can use Retrofit together with RxJava to combine and chain REST calls using rxObservables to avoid ugly callback chains (to avoid callback hell!!).
Use Retrofit if you are communicating with a Web service. Use the peer library Picasso if you are downloading images. Use OkHTTP if you need to do HTTP operations that lie outside of Retrofit/Picasso.
Volley roughly competes with Retrofit + Picasso. On the plus side, it is one library. On the minus side, it is one undocumented, unsupported, "throw the code over the wall and do an I/O presentation on it" library.
OkHttp can be used with Volley, in Retrofit it uses OkHttp by default! It has SPDY support, connection pooling, disk caching, transparent compression! Recently, it has got some support of java NIO with Okio library.
SPDY is an open networking protocol developed primarily at Google for transporting web content. SPDY manipulates HTTP traffic, with particular goals of reducing web page load latency and improving web security.

Volley overview:
Volley, on the other hand, is totally focused on handling individual, small HTTP requests. So if your HTTP request handling has some quirks, Volley probably has a hook for you. If, on the other hand, you have a quirk in your image handling, the only real hook you have is ImageCache. "It’s not nothing, but it’s not a lot!, either". but it have more other advantages like Once you define your requests, using them from within a fragment or activity is painless unlike parallel Async Tasks
Pros and Cons of Volley:
Pros of  Volley:
  • The networking part isn’t just for images. Volley is intended to be an integral part of your back end. For a fresh project based off of a simple REST service, this could be a big win.
  • NetworkImageView is more aggressive about request cleanup than Picasso, and more conservative in its GC usage patterns. NetworkImageView relies exclusively on strong memory references, and cleans up all request data as soon as a new request is made for an ImageView, or as soon as that ImageView moves offscreen.
  • Performance. This post won’t evaluate this claim, but they’ve clearly taken some care to be judicious in their memory usage patterns. Volley also makes an effort to batch callbacks to the main thread to reduce context switching.
  • Volley apparently has futures, too. Check out RequestFuture if you’re interested.
  • If you’re dealing with high-resolution compressed images, Volley is the only solution here that works well.
  • Volley can be used with Okhttp (New ver off Okhttp supports NIO for better performance )
  • Volley plays nice with the Activity life cycle.

Problems With Volley:
Since Volley is new few things are not supported yet, but it's fixed.
  1. Multipart Requests (Solution: https://github.com/vinaysshenoy/enhanced-volley)
  2. status code 201 is taken as an error, Status code from 200 to 207 are successful responses now.(Fixed: https://github.com/Vinayrraj/CustomVolley) , in latest release Google volley the 2XX Status codes bug is fixed now!
  3. It's less documented but many of the people supporting this volley in github, java like documentation can be found here http://files.evancharlton.com/volley-docs/
  4. To solve the solve/Change Redirect Policy of Volley Framework use Volley with OkHTTP.
Retrofit:
It's released by Square, This offers very easy to use REST APIs.
Pros of Retrofit:
  • Compared to Volley in this REST API code is brief and provides excellent API documentation and have good support in communities! Very easy to add into the projects.
  • We can use with any serialization library, with error handling.
Cons of Retrofit:
  • Memory error handling is not good (in older versions of Retrofit/OkHttp) not sure it's improved with the Okio with Java NIO support.
  • Minimum threading assistance can result callback hell if we use this in an improper way.
RoboSpice Vs. Volley:
  • RoboSpice(RS) is service based and more respectful of Android philosophy than Volley. Volley is thread based and this is not the way background processing should take place on Android. Ultimately, you can dig down both libs and find that they are quite similar, but our way to do background processing is more Android oriented, it allow us, for instance, to tell users that RoboSpice is actually doing something in background, which would be hard for volley (actually it doesn't at all).
  • RoboSpice and volley both offer nice features like prioritization, retry policies, request cancellation. But RoboSpice offers more : a more advanced caching and that's a big one, with cache management, request aggregation, more features like repluging to a pending request, dealing with cache expiry without relying on server headers, etc.
  • RoboSpice does more outside of UI Thread : volley will deserialize your POJOs on the main thread, which is horrible to my mind. With RoboSpice your app will be more responsive.
  • In terms of speed, we definitely need metrics. RoboSpice has gotten super fast now, but still we don't have figure to put here. Volley should theoretically be a bit faster, but RoboSpice is now massively parallel... who knows ?
  • RoboSpice offers a large compatibility range with extensions. You can use it with okhttp, retrofit, ormlite (beta), jackson, jackson2, gson, xml serializer, google http client, spring android... Quite a lot. Volley can be used with ok http and uses gson. that's it.
  • Volley offers more UI sugar that RoboSpice. Volley provides NetworkImageView, RoboSpice does provide a spicelist adapter. In terms of feature it's not so far, but I believe Volley is more advanced on this topic.
  • More than 200 bugs have been solved in RoboSpice since its initial release. It's pretty robust and used heavily in production. Volley is less mature but its user base should be growing fast (Google effect).
  • RoboSpice is available on maven central. Volley is hard to find ;)
At this point, we wanted to switch our networking library for performance reasons, but our decision had to take other criteria into consideration. If we were going to spend time refactoring a quarter of our code base, we would have to be a little bit picky. Some of the things we took into account were speed, ease of integration, code cleanup, scalability, and time required to write new API calls.

Android Volley vs Retrofit

1) Request Execution

One of the most important factors affecting the code complexity is, how a request is executed in your code. In background or in foreground? As you may know that Android OS does not allow the network interaction on main thread, it throws a NetworkOnMainThreadException. To avoid this you may need to do all the network processing in background. As a matter of fact both Android Volley and Retrofit support the background requests. Also both of them are designed in a way, that you may not have to write huge amounts of code to perform such requests. Although if you wish to do a request in foreground, even that it possible in both. As there are situations when you may want to block user from going further ahead in your app until a response is captured from web API.

2) In-Built Request Types

The data returned from a web service always complicates the implementation, but thankfully now with help of these libraries almost all types of responses can be captured. Android Volley can capture four types of responses automatically through these requests:


Now when comparing Android Volley vs Retrofit, volley may have image parsing feature but it cannot convert a Json object directly into a POJO (Plain Old Java Object). On the other hand retrofit can automatically convert a JSON object into a POJO, but lacks image parsing.


3) Retry Mechanism

One of the great things about volley is that it supports retries on request timeout. While creating requests with volley, we can set a retry policy by using setRetryPolicy method. By default a volley request timeout time is set to 5 seconds. But if you wish to change the policy, it supports that too. You can specify these parameters according to your needs:


  • Timeout
  • Number Of Retries
  • Back Off Multiplier
Retrofit on the other hand does not have a retry mechanism as of now. Although I just saw their road map for 2.0 version, they might have a retry mechanism then. Therefore as of now when comparing Android Volley vs Retrofit, Retrofit loses this one.

4) Caching

Android Volley library has a very elaborate caching mechanism. This is one of the best features of volley. When a request is made through volley first it is checked in the cache. If an appropriate response is present in cache then it is parsed and returned directly to main thread, else a network request is made. This whole functionality can be customized, to support your requirements. If you wish to learn more about it please go through this document.
Retrofit on the hand, does not support caching. Although it can implement RFC 2616 caching which is the spec for HTTP caching, through the OkHttpClient. As stated in this document. Therefore when comparing caching between Android Volley and Retrofit, Volley takes this one too.

5) Loading Images

Volley library has a special type of request to get images from network called ImageRequest. When this type of request is made, response is captured as a bitmap. Also it supports the resizing of returned image in the worker thread itself, which saves a lot of coding. Volley also has a NetworkImageView class which can be used with ImageLoader class, to automatically load images, whenever the NetworkImageView appears.
As of now Retrofit does not support the loading of images, the way they are loaded in Volley. But it can be combined with OkHttpClient to support the loading of images. Hence volley takes this one too.

6) Code Complexity

Both the libraries Android Volley and Retrofit are very easy to implement. If you compare them with primitive ways of accessing a web API, both of them would come out as a winner as they can phenomenally reduce your code base. But in my opinion when you compare the Android Volley vs Retrofit, the later one- Retrofit wins this one. As there is not much to customise in Retrofit. Its a simple yet powerful library. Volley on the other hand is highly customisable and has a greater code complexity.

Conclusion:

Robospice is a service based framework, if you are working with large network operations recommend Robospice framework.If you are working with only light weight network operations and web services, recommend Android Volley or Retrofit frameworks.After thoroughly comparing the major features between Android Volley and Retrofit. In my personal opinion Volley is a better library. It may be a little complex but it offers much more features than Retrofit and it is google provided library too. Volley not only supports caching of requests but can also load images automatically.Retrofit having minimum threading assistance can result callback hell if we use Retrofit in an improper way.

AsyncTask

AsyncTask:
AsyncTask is an abstract class provided by Android which helps us to use the UI thread properly. This class allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.

advantages of using AsyncTasks:
  1. Easy to learn and implement.
  2. It is having good process control.

Disadvantages of using AsyncTasks:
  1. No orientation-change support.
  2. No ability to cancel network calls.
  3. As well as no easy way to make API calls in parallel.
  4. With the exception of Froyo and Gingerbread, Async Tasks (by default) run in a serialised fashion.
  5. In a practical sense, this means that only one AsyncTask is running at any given time.
  6. Views that require multiple API calls (the DashBoard currently has 7) run extremely slow, sometimes taking multiple seconds to load.
For this reasons we should use third-party libraries for network operations Like Volley,Retrofit,Robospice..etc.

Android HTTP clients

Android HTTP clients:
Most network-connected Android apps use HTTP to send and receive data. Android includes two HTTP clients HttpURLConnection and Apache HttpClient.


1.Apache HTTPClient:
DefaultHttpClient and its sibling AndroidHttpClient are extensible HTTP clients suitable for web browsers. They have large and flexible APIs. Their implementation is stable and they have few bugs.
But the large size of this API makes it difficult for us to improve it without breaking compatibility. The Android team is not actively working on Apache HTTP Client.
2.HttpURLConnection:
HttpURLConnection is a general-purpose, lightweight HTTP client suitable for most applications. This class has humble beginnings, but it's focused API has made it easy for us to improve steadily.
Prior to Froyo, HttpURLConnection had some frustrating bugs. In particular, calling close() on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling.

Perform Network Operations on a Separate Thread:
Network operations can involve unpredictable delays. To prevent this from causing a poor user experience, always perform network operations on a separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. So android clients should use AsyncTask for network operations.

Service V/s Thread

Service V/s Thread :


A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need.


If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask or Handler Thread, instead of the traditional Thread class.


Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.

Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.

Android Robospice Framework

Robospice Framework
Introduction:
RoboSpice is a modular android library that makes writing asynchronous long running tasks and network requests easily. It is specialized in network requests, supports caching and offers REST requests out-of-the box using extension modules.One of the libraries to correctly implement the service-based API pattern is RoboSpice.
There are 5 different types of extensions in Robospice.
  1. Spring Android module
  2. Google Http Java Client module
  3. Retrofit module
  4. ORMLite module
  5. UI SpiceList module

For Android we are using Spring Android module.

Spring Android module:
Spring Android module is a library that makes it easy to perform REST requests and communicate with web services using POJOs.
The RoboSpice Spring Android module provides support for
  • All supported network data format of Spring Android : JSON (via Gson/Jackson) and XML
  • Persistence of the results of SpiceRequest in these formats
  • Pre-setup SpiceService subclasses
Using RoboSpice is done in 4 easy steps:
  1. Define the Service, you can use pre-existing SpiceService definitions or create your own.
  2. Create a base activity class which adds a SpiceManager instance to communicate to the service. You will now have to inherit from this activity when creating new ones.
  3. Create a SpiceRequest object that deals with running the asynchronous work, i.e. connect to the server and parse the content.
  4. Create a RequestListener private class in your activity that will receive the response from the SpiceRequest. The service will always trigger the activity if it is in the resumed state, whether or not the response has succeeded.
The beauty of this library is that you can combine it with libraries such as RetroFit and Jackson or GSON. For example, how you parse your response content or build up your SpiceRequest depends on which addons you use.
Robospice framework architecture and request flow:


Background processing is implemented using a dedicated Android service that seamlessly binds to a started activity and reliably unlinks from it when it gets destroyed, continuing to work behind the scenes, caching and serving the results as soon as the activity is bound back again.





Advantages of using Robospice:

  • Supports Android starting from SDK version 8 (Froyo / 2.2.x).
  • Executes network requests asynchronously (in a background Android Service).
  • Supports REST out of the box (using Spring Android or Google Http Client or Retrofit).
  • Is strongly typed ! You query web services using POJOs as parameters and you get POJOs as request results.
  • Enforces no constraints neither on POJOs used for requests nor on Activity classes you use in your projects.
  • Caches results in Json with both Jackson or Jackson2 or Gson, or Xml, or flat text files, or binary files, even using ORMLite (still in beta).
  • Notifies your activities (or any other context) of the result of the network request with respect to their lifecycles.
  • Notifies your activities (or any other context) on the UI Thread.
  • No memory leaks at all, like Android Loaders, unlike Android AsyncTasks.
  • Uses a simple but robust exception handling model.
  • Supports multi-threading of request executions.
  • Is stable, efficient and designed to respect Android philosophy.
  • Supports request cancellation, request prioritization and requests aggregation.
  • Supports aggregation of different web services.
  • Is a full featured replacement for long running Async Tasks even if they are not related to networking.
  • It is open source.
  • And tested (more than 200 tests).