Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Android Networking Without the Pain

No description
by

Colin Lee

on 15 May 2014

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Android Networking Without the Pain

Networking
Minus the Pain
Who is this guy?
Lead Mobile Dev @ thisCLICKS in St Paul (
We're hiring engineers!
)
Organizer, HackForMN (
Join us this summer!
)
Cray-1
Charles Babbage
In the Beginning
Few Options:
AsyncTask
Spring Android
As of Summer 2013
Volley
OkHTTP
Retrofit
Robospice
Picasso
ION
Spring
Volley
Introduced by Ficus Kirkpatrick at Google I/O 2013
Thrown over the wall by Google, not added to Android API
Seems well designed for custom games, but lacks docs and polish
Volley Advantages
Good:
Volley Negatives
Bad:
Volley Example
RequestQueue queue = Volley.newRequestQueue(this);

JsonObjectRequest jr = new JsonObjectRequest(
Request.Method.GET, APIHelper.getURL(), null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
entries = APIHelper.deserializePosts(response);
setListAdapter(new JSONArrayAdapter(MyActivity.this, entries, R.layout.listview_row, jsonFields, uiFields));
}
},new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MyActivity.this, "Please check your connection and try again.", Toast.LENGTH_LONG).show();
}
});
mRequestQueue.add(jr);
(Google)
(Square)
(Square)
(Octo)
(Square)
(Clockworkmod)
(Pivotal)
Volley: Cancel
To cancel all requests:
requestQueue.cancelAll(this);
To cancel requests by tag:
request.setTag("My Tag");
requestQueue.cancelAll("My Tag");
Volley: Retry
To retry a request automatically:

request.setRetryPolicy(
new DefaultRetryPolicy(
20 * 1000, 1, 1.0f
)
); // 20 seconds, 1 retry
OkHTTP
Released by Square last summer
Speeds requests in many ways
Supported by many libraries
OkHTTP Advantages
Good:
OkHTTP Negatives
Huh?

It's better than HttpClient in every way!

Just use it with any library.
Retrofit
Released by Square early last year
Offers very easy-to-use REST API solution
Loaders in Honeycomb
Retrofit Advantages
Good:
Retrofit Negatives
Bad:

Retrofit Interface
public interface GitHubService {

@GET("/users/{user}/repos")
List<Repo> listRepos(
@Path("user") String user,
);
}

// provide one function per REST call
// pass null for optional arguments
Retrofit Example
RestAdapter restAdapter = new
RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.build();

GitHubService service =
restAdapter.create(GitHubService.class);

List<Repo> repos = service.listRepos("octocat");

* Synchronous example, pass callback for async
Robospice
Library for long-running background tasks using multiple threads.
Has helpful code for network requests, but works with any task.
Robospice Advantages
Request cancellation
Request caching
Request aggregation
Request prioritization
Request retry with exponential falloff
Handles multi-threading
Robospice Disadvantages
It's another library
and not a simple one.
Robospice Easy Stuff
public abstract class BaseActivity extends Activity {
private SpiceManager spiceManager = new SpiceManager(JacksonGoogleHttpClientSpiceService.class);

@Override
protected void onStart() {
spiceManager.start(this);
super.onStart();
}

@Override
protected void onStop() {
spiceManager.shouldStop();
super.onStop();
}

protected SpiceManager getSpiceManager() {
return spiceManager;
}
}
Robospice Network Calls
getSpiceManager().execute(
weatherRequest, "json", DurationInMillis.ONE_MINUTE,
new WeatherRequestListener()
);

Listeners simply implement a success and a failure callback.

Requests implement loadDataFromNetwork() and a constructor.
Picasso
Super easy-to-use
image loading,
caching,
and manipulation library.
Picasso Advantages
It's difficult to find a simpler library
Recycles ImageViews and cancels downloads automatically
Handles multi-tier memory and disk caching
Uses standard ImageViews, unlike Volley's NetworkImageView
Handles memory errors well
Good asychronous performance
Easy to extend
Thread handling
JSON and image handling
Easy cancellation and retry
Transparent disk caching
Caching on URL flubs response body
Futures may silently deadlock
Uses threads
Advanced HTTP features need custom code
Serialization needs custom code
A pain to add to projects
Lacks documentation
Disk caching
Transparent compression
Connection pooling
SPDY support
Trivial to add to projects
Good error handling
Uses any serialization library
REST API code is brief and provides excellent API documentation
Minimal threading assistance can result in "callback hell" if used improperly
Memory error handling worse than Volley
To learn why to use Robospice, download "Robospice Motivations" from
Picasso Disadvantages
Volley has better memory error handling
Images fade from white by default
Does not respect "scaletype" attribute
Need to know size of image before request
Picasso Example
Picasso
.with(context)
.load("http://i.imgur.com/DvpvklR.png")
.into(imageView);
Ion and Spring Android
Find out and let us know.
Questions?
Networking Stack
HTTP: OkHTTP, Spring, Picasso, Ion
REST: Retrofit, Volley, Spring, Ion
Images: Picasso, Volley, Ion
Threading: Robospice, Picasso, Volley, Ion
Issues to Think About
Synchronization
Thread Safety
Deserializing Complex Objects
Cache Keys
Persisting Objects Twice?
Robospice is Different
Everything gets cached
Most exceptions are double-wrapped
Functions return POJOs
Robospice Example on GitHub
https://github.com/colintheshots/robospice-minnebar-example
More Interesting Robospice Example
BitBeaker is an Open Source Bitbucket App
https://bitbucket.org/saibotd/bitbeaker
Reactive Programming
Solves "callback hell" with principles from functional programming languages.
RxJava (Reactive eXtensions) works natively with Retrofit.
RxJava for Android
Retrofit provides Observable type for network responses.
Reduces need to save application state to chain requests.
Downside is possible memory leaks.
Is it worth it?
Requires new ways of thinking about threading code.
Upside is fewer threading bugs.
Full transcript