Ion是一个Android异步网络和图像加载库,优雅得API大大简化了网络操作。
地址:https://github.com/koush/ion

特点:

异步下载:

  • Images into ImageViews or Bitmaps (animated GIFs supported too)

  • JSON (viaGson)

  • Strings

  • Files

  • Java types using Gson

易于使用地流式API

  • Automaticallycancelsoperations when the calling Activity finishes

  • Manages invocation back onto the UI thread

  • All operations return a Future and can be cancelled

HTTP POST/PUT:

  • text/plain

  • application/json -both JsonObject and POJO

  • application/x-www-form-urlencoded

  • multipart/form-data

Transparent usage of HTTP features and optimizations:

  • SPDY and HTTP/2

  • Caching

  • Gzip/Deflate Compression

  • Connection pooling/reusevia HTTP Connection: keep-alive

  • Uses the best/stablest connection from a server if it has multiple IP addresses

  • Cookies

Viewreceivedheaders
Grouping and cancellation of requests
Download progress callbacks

Supports file:/, http(s):/, and content:/ URIs
Request levelloggingand profiling
Support forproxyservers like Charles Proxy to do request analysis
Based on NIO and AndroidAsync
Ability to use self signedSSLcertificates
示例:https://github.com/koush/ion/tree/master/ion-sample

安装:

jar方式:

  • 本身jar:ion.jar

  • Gson:gson.jar

  • AndroidAsync:https://github.com/koush/AndroidAsync

Maven:

<dependency><groupId>com.koushikdutta.ion</groupId><artifactId>ion</artifactId><version>2,</version></dependency>

Gradle:

dependencies{compile'com.koushikdutta.ion:ion:2.+'}

使用:

Get JSON

Ion.with(context).load("http://example.com/thing.json").asJsonObject().setCallback(newFutureCallback<JsonObject>(){@OverridepublicvoidonCompleted(Exceptione,JsonObjectresult){//dostuffwiththeresultorerror}});

Post JSON and read JSON

JsonObjectjson=newJsonObject();json.addProperty("foo","bar");Ion.with(context).load("http://example.com/post").setJsonObjectBody(json).asJsonObject().setCallback(newFutureCallback<JsonObject>(){@OverridepublicvoidonCompleted(Exceptione,JsonObjectresult){//dostuffwiththeresultorerror}});

Post application/x-www-form-urlencoded and read a String

Ion.with(getContext()).load("https://koush.clockworkmod.com/test/echo").setBodyParameter("goop","noop").setBodyParameter("foo","bar").asString().setCallback(...)

Post multipart/form-data and read JSON with an upload progress bar

Ion.with(getContext()).load("https://koush.clockworkmod.com/test/echo").uploadProgressBar(uploadProgressBar).setMultipartParameter("goop","noop").setMultipartFile("filename.zip",newFile("/sdcard/filename.zip")).asJsonObject().setCallback(...)

Download a File with a progress bar

Ion.with(context).load("http://example.com/really-big-file.zip")//haveaProgressBargetupdatedautomaticallywiththepercent.progressBar(progressBar)//andaProgressDialog.progressDialog(progressDialog)//canalsouseacustomcallback.progress(newProgressCallback(){@OverridepublicvoidonProgress(intdownloaded,inttotal){System.out.println(""+downloaded+"/"+total);}}).write(newFile("/sdcard/really-big-file.zip")).setCallback(newFutureCallback<File>(){@OverridepublicvoidonCompleted(Exceptione,Filefile){//downloaddone...//dostuffwiththeFileorerror}});

Setting Headers

Ion.with(context).load("http://example.com/test.txt")//settheheader.setHeader("foo","bar").asString().setCallback(...)

Load an image into an ImageView

//Thisisthe"long"waytodobuildanImageViewrequest...itallowsyoutosetheaders,etc.Ion.with(context).load("http://example.com/image.png").withBitmap().placeholder(R.drawable.placeholder_image).error(R.drawable.error_image).animateLoad(spinAnimation).animateIn(fadeInAnimation).intoImageView(imageView);//butforbrevity,usetheImageViewspecificbuilder...Ion.with(imageView).placeholder(R.drawable.placeholder_image).error(R.drawable.error_image).animateLoad(spinAnimation).animateIn(fadeInAnimation).load("http://example.com/image.png");

Ion图像加载API特点

  • Disk and memory caching

  • Bitmaps are held viaweak referencesso memory is managed very effeciently

  • ListView Adapterrecyclingsupport

  • Bitmaptransformationsvia the .transform(Transform)

  • Animateloading and loaded ImageViewstates

  • DeepZoomfor extremely large images

Futures

All operations return a custom Future that allows you to specify acallbackthat runs on completion.

Future<String>string=Ion.with(context).load("http://example.com/string.txt").asString();Future<JsonObject>json=Ion.with(context).load("http://example.com/json.json").asJsonObject();Future<File>file=Ion.with(context).load("http://example.com/file.zip").write(newFile("/sdcard/file.zip"));Future<Bitmap>bitmap=Ion.with(context).load("http://example.com/image.png").intoImageView(imageView);

Cancelling Requests

Futures can be cancelled by calling .cancel():

bitmap.cancel();json.cancel();

Blocking on Requests

All Futures have aFuture.get()method that waits for the result of the request, by blocking if necessary.

JsonObjectjson=Ion.with(context).load("http://example.com/thing.json").asJsonObject().get();

Seamlessly use your own Java classes with Gson(利用Gson无缝使用POJO):

publicstaticclassTweet{publicStringid;publicStringtext;publicStringphoto;}publicvoidgetTweets()throwsException{Ion.with(context).load("http://example.com/api/tweets").as(newTypeToken<List<Tweet>>(){}).setCallback(newFutureCallback<List<Tweet>>(){@OverridepublicvoidonCompleted(Exceptione,List<Tweet>tweets){//chirpchirp}});}

Logging

Wondering why your app is slow? Ion lets you doboth global and request level logging.
To enable it globally:

Ion.getDefault(getContext()).configure().setLogging("MyLogs",Log.DEBUG);

Or to enable it on just a single request:

Ion.with(context).load("http://example.com/thing.json").setLogging("MyLogs",Log.DEBUG).asJsonObject();

Request Groups请求组合

By default, Ion automatically places all requests into a group with all the other requests created by that Activity or Service. Using thecancelAll(Activity)call, all requests still pending can be easilycancelled:

Future<JsonObject>json1=Ion.with(activity,"http://example.com/test.json").asJsonObject();Future<JsonObject>json2=Ion.with(activity,"http://example.com/test2.json").asJsonObject();//later...inactivity.onStop@OverrideprotectedvoidonStop(){super.onStop();Ion.getDefault(activity).cancelAll(activity);}

Ion also lets you tag your requests intogroupsto allow for easy cancellation of requests in that group later:
自定义Group便于管理:

ObjectjsonGroup=newObject();ObjectimageGroup=newObject();Future<JsonObject>json1=Ion.with(activity).load("http://example.com/test.json")//taginacustomgroup.group(jsonGroup).asJsonObject();Future<JsonObject>json2=Ion.with(activity).load("http://example.com/test2.json")//usethesamecustomgroupastheotherjsonrequest.group(jsonGroup).asJsonObject();Future<Bitmap>image1=Ion.with(activity).load("http://example.com/test.png")//forthisimagerequest,useadifferentgroupforimages.group(imageGroup).intoImageView(imageView1);Future<Bitmap>image2=Ion.with(activity).load("http://example.com/test2.png")//sameimageGroupasbefore.group(imageGroup).intoImageView(imageView2);//later...tocancelonlyimagedownloads:Ion.getDefault(activity).cancelAll(imageGroup);

Proxy Servers (like Charles Proxy)

//proxyallrequestsIon.getDefault(context).configure().proxy("mycomputer",8888);//or...toproxyspecificrequestsIon.with(context).load("http://example.com/proxied.html").proxy("mycomputer",8888).getString();

Viewing Received Headers

Ion operations return aResponseFuture, which grantaccess to response propertiesvia the Response object.The Response object contains the headers, as well as the result:ResponseFuture同时包含头部和请求结果

Ion.with(getContext()).load("http://example.com/test.txt").asString().withResponse().setCallback(newFutureCallback<Response<String>>(){@OverridepublicvoidonCompleted(Exceptione,Response<String>result){//printtheresponsecode,ie,200System.out.println(result.getHeaders().code());//printtheStringthatwasdownloadedSystem.out.println(result.getResult());}});


更多相关文章

  1. Nginx系列教程(六)| 手把手教你搭建 LNMP 架构并部署天空网络电影
  2. android:如何开启webview的LBS功能
  3. [Android面试题-3] Activity的四种加载模式
  4. Picasso网络图片加载 (毕加索)
  5. Android(安卓)加载本地图片 和 服务器图片
  6. Android(安卓)Setting网络配置界面,删除已隐藏UI的快速搜索
  7. [ANDROID]APP加载界面完毕时回调,onWindowFocusChanged的使用
  8. Android(安卓)APK JNI sample (JAVA JNI)
  9. Android(安卓)集成Crosswalk替换成X5WebView

随机推荐

  1. android 2048游戏实现
  2. Android类装载机制
  3. 如果让我重新设计一款Android App
  4. Android Studio中使用com.android.suppor
  5. Android应用程序启动Binder线程源码分析
  6. Android WebView 用法
  7. 【Android开机启动Activity或者Service方
  8. 定制自己的 Android(安卓)Dialog 信息提
  9. Android常用开源库(模块部分)
  10. 10.Android之测试代码实现步骤