Android ion异步网络和图像加载大大简化网络开发强烈推荐

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

特点:

异步下载:

  • Images into ImageViews or Bitmaps (animated GIFs supported too)
  • JSON (via Gson)
  • Strings
  • Files
  • Java types using Gson

易于使用地流式API

  • Automatically cancels operations 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/reuse via HTTP Connection: keep-alive
  • Uses the best/stablest connection from a server if it has multiple IP addresses
  • Cookies

View received headers
Grouping and cancellation of requests
Download progress callbacks
Supports file:/, http(s):/, and content:/ URIs
Request level logging and profiling
Support for proxy servers like Charles Proxy to do request analysis
Based on NIO and AndroidAsync
Ability to use self signed SSL certificates
示例:https://github.com/koush/ion/tree/master/ion-sample

安装:

jar方式:

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(new FutureCallback<JsonObject>() {
   @Override    public void onCompleted(Exception e, JsonObject result) {
        // do stuff with the result or error
    }});

Post JSON and read JSON

JsonObject json = new JsonObject();json.addProperty("foo", "bar"); 
Ion.with(context).load("http://example.com/post").setJsonObjectBody(json).asJsonObject().setCallback(new FutureCallback<JsonObject>() {
   @Override    public void onCompleted(Exception e, JsonObject result) {
        // do stuff with the result or error
    }});

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", new File("/sdcard/filename.zip")).asJsonObject().setCallback(...)

Download a File with a progress bar

Ion.with(context).load("http://example.com/really-big-file.zip")// have a ProgressBar get updated automatically with the percent.progressBar(progressBar)// and a ProgressDialog.progressDialog(progressDialog)// can also use a custom callback.progress(new ProgressCallback() {@Override   public void onProgress(int downloaded, int total) {
       System.out.println("" + downloaded + " / " + total);
   }}).write(new File("/sdcard/really-big-file.zip")).setCallback(new FutureCallback<File>() {
   @Override    public void onCompleted(Exception e, File file) {
        // download done...
        // do stuff with the File or error
    }});

Setting Headers

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

Load an image into an ImageView

// This is the "long" way to do build an ImageView request... it allows you to set headers, 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); // but for brevity, use the ImageView specific builder...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 via weak references so memory is managed very effeciently
  • ListView Adapter recycling support
  • Bitmap transformations via the .transform(Transform)
  • Animate loading and loaded ImageView states
  • DeepZoom for extremely large images

Futures

All operations return a custom Future that allows you to specify a callback that 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(new File("/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 a Future.get() method that waits for the result of the request, by blocking if necessary.

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

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

public static class Tweet {
    public String id;
    public String text;
    public String photo;} public void getTweets() throws Exception {
    Ion.with(context)
    .load("http://example.com/api/tweets")
    .as(new TypeToken<List<Tweet>>(){})
    .setCallback(new FutureCallback<List<Tweet>>() {
       @Override        public void onCompleted(Exception e, List<Tweet> tweets) {
          // chirp chirp
        }
    });}

Logging

Wondering why your app is slow? Ion lets you do both 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 the cancelAll(Activity) call, all requests still pending can be easily cancelled:

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... in [email protected] void onStop() {
    super.onStop();
    Ion.getDefault(activity).cancelAll(activity);}

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

Object jsonGroup = new Object();Object imageGroup = new Object(); 
Future<JsonObject> json1 = Ion.with(activity).load("http://example.com/test.json")// tag in a custom group.group(jsonGroup).asJsonObject(); 
Future<JsonObject> json2 = Ion.with(activity).load("http://example.com/test2.json")// use the same custom group as the other json request.group(jsonGroup).asJsonObject(); 
Future<Bitmap> image1 = Ion.with(activity).load("http://example.com/test.png")// for this image request, use a different group for images.group(imageGroup).intoImageView(imageView1); 
Future<Bitmap> image2 = Ion.with(activity).load("http://example.com/test2.png")// same imageGroup as before.group(imageGroup).intoImageView(imageView2); // later... to cancel only image downloads:Ion.getDefault(activity).cancelAll(imageGroup);

Proxy Servers (like Charles Proxy)

// proxy all requestsIon.getDefault(context).configure().proxy("mycomputer", 8888); // or... to proxy specific requestsIon.with(context).load("http://example.com/proxied.html").proxy("mycomputer", 8888).getString();

Viewing Received Headers

Ion operations return a ResponseFuture, which grant access to response properties via 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(new FutureCallback<Response<String>>() {
    @Override    public void onCompleted(Exception e, Response<String> result) {
        // print the response code, ie, 200
        System.out.println(result.getHeaders().code());
        // print the String that was downloaded
        System.out.println(result.getResult());
    }});
时间: 2024-08-09 19:46:11

Android ion异步网络和图像加载大大简化网络开发强烈推荐的相关文章

[Android学习系列16]Android把php输出的json加载到listview

首先写个php脚本输出json,注意,还要输出回车,方便android的bufferreader读取一行 <?php class Book { public $bookid; public $bookname; public $bookinfo; function __construct($id,$name,$info ){ $this->bookid = $id; $this->bookname = $name; $this->bookinfo = $info; } } $boo

Android之Socket通信、List加载更多、Spinner下拉列表

Android与服务器的通信方式主要有两种,一是Http通信,一是Socket通信.两者的最大差异在于,http连接使用的是“请求—响应方式”,即在请求时建立连接通道,当客户端向服务器发送请求后,服务器端才能向客户端返回数据.而Socket通信则是在双方建立起连接后就可以直接进行数据的传输,在连接时可实现信息的主动推送,而不需要每次由客户端想服务器发送请求. 那么,什么是socket?Socket又称套接字,在程序内部提供了与外界通信的端口,即端口通信.通过建立socket连接,可为通信双方的数

Android插件化(三)加载插件apk中的Resource资源

Android加载插件apk中的Resource资源 简介 如何加载未安装apk中的资源文件呢?我们从android.content.res.AssetManager.java的源码中发现,它有一个私有方法addAssetPath,只需要将apk的路径作为参数传入,我们就可以获得对应的AssetsManager对象,然后我们就可以使用AssetsManager对象,创建一个Resources对象,然后就可以从Resource对象中访问apk中的资源了.总结如下: 1.新建一个AssetManag

Android 下拉刷新上拉加载 多种应用场景 超级大放送(上)

转载请标明原文地址:http://blog.csdn.net/yalinfendou/article/details/47707017 关于Android下拉刷新上拉加载,网上的Demo太多太多了,这里不是介绍怎么去实现下拉刷新上拉加载,而是针对下拉刷新上拉加载常用的一些应用场景就行了一些总结,包含了下拉刷新上拉加载过程中遇到的一些手势冲突问题的解决方法(只能算是抛砖引玉). 去年9月的时候,那时自己正在独立做Android项目.记得刚刚写完那个ListView列表页面(木有下拉刷新,上拉加载)

as3.0加载本地或网络上的图片

加载本地或网络上的图片,我们一般只用Loader及URLRequest这两个类就可以完成,URLRequest即可以加载本地的,也可以加载网络的.代码如下 import flash.display.Loader; import flash.net.URLRequest; var loader:Loader = new Loader(); var request:URLRequest = new URLRequest('img/123.png'); loader.y = 200; loader.l

Android App 启动时显示正在加载图片(源码)

微信.QQ.天天动听等程序,在打开时显示了一张图片,然后跳转到相关界面.本文实现这个功能,其实很简单.... 新建两个Activity,LoadingActivity,MainActivity,将LoadingActivity设置为android.intent.action.MAIN.使用TimerTesk,或者Thread将LoadingActivity显示几秒后跳转到MainActivity界面. LoadingActivity: new Timer().schedule(new Timer

android 下拉刷新上拉加载更多,高仿ios左滑动删除item,解决了众多手势问题

一.前言 老规矩,别的不说,这demo是找了很相关知识集合而成的,可以说对我这种小白来说是绞尽脑汁!程序员讲的是无图无真相!现在大家一睹为快! 二.比较关键的还是scroller这个类的 package com.icq.slideview.view; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; i

Android 下拉刷新上拉加载效果功能,使用开源项目android-pulltorefresh实现

应用场景: 在App开发中,对于信息的获取与演示,不可能全部将其获取与演示,为了在用户使用中,给予用户以友好.方便的用户体验,以滑动.下拉的效果动态加载数据的要求就会出现.为此,该效果功能就需要应用到所需要的展示页面中. 知识点介绍: 本文主要根据开源项目android-pulltorefresh展开介绍. android-pulltorefresh [一个强大的拉动刷新开源项目,支持各种控件下拉刷新 ListView.ViewPager.WevView.ExpandableListView.G

vue使用ECharts时的异步更新与数据加载

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 24.0px "Helvetica Neue"; color: #404040 } p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px "Helvetica Neue"; color: #737373 } p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Monaco