1. volley的简介

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available through the open AOSP repository.

Volley 是一个HTTP库。它使得android app的网络传输数据更简单,更快。

Volley的设计目标就是很适合去进行数据量不大,但通信频繁的网络操作,而对于大数据量的网络操作。比方说下载文件,流视频操作等。Volley的表现就会很糟糕。我一般考虑DownloadManager。

Volley源代码下载地址:

git clone https://android.googlesource.com/platform/frameworks/volley

我们把代码下载下来。參考Android working with Volley Library,我们能够生成volley.jar,我们在项目中,能够直接使用volley.jar包。

2. StringRequest

我们先从最简单的StringRequest開始。介绍一下怎样使用Volley去发起string的请求:

public class Lesson01Activity extends Activity {

    public static final String TAG = "Lesson01Activity";
private StringRequest stringRequest;
private RequestQueue mRequestQueue;
private TextView mTextView; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_01);
init();
} private void init() {
// TODO Auto-generated method stub
mTextView = (TextView) findViewById(R.id.text);
mRequestQueue = Volley.newRequestQueue(this);
String url ="http://www.baidu.com";
stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Set the tag on the request.
stringRequest.setTag(TAG);
// Add the request to the RequestQueue.
mRequestQueue.add(stringRequest);
} @Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (mRequestQueue != null) {
mRequestQueue.cancelAll(TAG);
}
}
}

最后。一定要AndroidManifest.xml中添加 INTERNET Permission:

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 

3. cache–缓存的使用

volley支持cache,以下是一个使用cache的例子:

mTextView = (TextView) findViewById(R.id.text);
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
Network network = new BasicNetwork(new HurlStack());
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
String url ="http://www.myurl.com";
// Request a string response from the provided URL.
stringRequest = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mTextView.setText("Response is: "+ response.substring(0,500));
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
stringRequest.setTag(TAG);
mRequestQueue.add(stringRequest);

4. 使用单例模式应用volley

MySingleton ——单例模式类

import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley; public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx; private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
} public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
} public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
} public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
} public ImageLoader getImageLoader() {
return mImageLoader;
}
}

使用例子:

mTextView = (TextView) findViewById(R.id.text);
mRequestQueue = MySingleton.getInstance(this.getApplicationContext()).
getRequestQueue();
String url ="http://www.baidu.com";
stringRequest = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mTextView.setText("Response is: "+ response.substring(0,500));
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
stringRequest.setTag(TAG);
MySingleton.getInstance(this).addToRequestQueue(stringRequest);

5.ImageRequest + ImageView

ImageRequest 就是Image的请求:

ImageView mImageView;
String url = "http://i.imgur.com/7spzG.png";
mImageView = (ImageView) findViewById(R.id.myImage);
... // Retrieves an image specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
mImageView.setImageBitmap(bitmap);
}
}, 0, 0, null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
mImageView.setImageResource(R.drawable.image_load_error);
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(request);

6.ImageLoader + ImageView

ImageLoader mImageLoader;
ImageView mImageView;
// The URL for the image that is being loaded.
private static final String IMAGE_URL =
"http://developer.android.com/images/training/system-ui.png";
...
mImageView = (ImageView) findViewById(R.id.regularImageView); // Get the ImageLoader through your singleton class.
mImageLoader = MySingleton.getInstance(this).getImageLoader();
mImageLoader.get(IMAGE_URL, ImageLoader.getImageListener(mImageView,
R.drawable.def_image, R.drawable.err_image));

7.ImageLoader+NetworkImageView

在ListView中。对于有效的显示多张图片,我们能够採用NetworkImageView 和 ImageLoader来处理。

xml布局文件:

<com.android.volley.toolbox.NetworkImageView
android:id="@+id/networkImageView"
android:layout_width="150dp"
android:layout_height="170dp"
android:layout_centerHorizontal="true" />

使用例子:

ImageLoader mImageLoader;
NetworkImageView mNetworkImageView;
private static final String IMAGE_URL =
"http://developer.android.com/images/training/system-ui.png";
... // Get the NetworkImageView that will display the image.
mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView); // Get the ImageLoader through your singleton class.
mImageLoader = MySingleton.getInstance(this).getImageLoader(); // Set the URL of the image that should be loaded into this view, and
// specify the ImageLoader that will be used to make the request.
mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);

8.图片显示的一个综合例子

8.1LruBitmapCache.java

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.DisplayMetrics;
import com.android.volley.toolbox.ImageLoader.ImageCache; public class LruBitmapCache extends LruCache<String, Bitmap>
implements ImageCache { public LruBitmapCache(int maxSize) {
super(maxSize);
} public LruBitmapCache(Context ctx) {
this(getCacheSize(ctx));
} @Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
} @Override
public Bitmap getBitmap(String url) {
return get(url);
} @Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
} // Returns a cache size equal to approximately three screens worth of images.
public static int getCacheSize(Context ctx) {
final DisplayMetrics displayMetrics = ctx.getResources().
getDisplayMetrics();
final int screenWidth = displayMetrics.widthPixels;
final int screenHeight = displayMetrics.heightPixels;
// 4 bytes per pixel
final int screenBytes = screenWidth * screenHeight * 4;
return screenBytes * 3;
}
}

8.2 activity_main_04.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Lesson01Activity" > <TextView
android:id="@+id/tv01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ImageView"
/> <ImageView
android:id="@+id/myImage"
android:layout_below="@id/tv01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> <TextView
android:id="@+id/tv02"
android:layout_below="@id/myImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NetworkImageView"
/> <com.android.volley.toolbox.NetworkImageView
android:id="@+id/networkImageView"
android:layout_below="@id/tv02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_launcher" /> </RelativeLayout>

8.3 使用例子

public class Lesson04Activity extends Activity {

    public static final String TAG = "Lesson04Activity";
private static final String IMAGE_URL = "http://developer.android.com/images/training/system-ui.png";
private String url = "http://i.imgur.com/7spzG.png";
private ImageRequest request;
private RequestQueue mRequestQueue;
private ImageView myImage;
private NetworkImageView networkImageView;
private ImageLoader imageLoader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_04);
init();
}
private void init() {
// TODO Auto-generated method stub
mRequestQueue = MySingleton.getInstance(this.getApplicationContext()).
getRequestQueue();
networkImageView = (NetworkImageView) findViewById(R.id.networkImageView);
networkImageView.setImageResource(R.drawable.ic_launcher);
//imageLoader = MySingleton.getInstance(this).getImageLoader();
imageLoader = new ImageLoader(mRequestQueue, new LruBitmapCache(
LruBitmapCache.getCacheSize(this)));
//imageLoader.get(url, ImageLoader.getImageListener(networkImageView,
// R.drawable.ic_launcher, R.drawable.ic_launcher));
//networkImageView.setImageUrl(IMAGE_URL, imageLoader);
networkImageView.setImageUrl(url, imageLoader); myImage = (ImageView) findViewById(R.id.myImage);
myImage.setImageResource(R.drawable.ic_launcher);
request = new ImageRequest(url,
new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
// TODO Auto-generated method stub
myImage.setImageBitmap(bitmap);
}
}, 0, 0, null,
new Response.ErrorListener() { @Override
public void onErrorResponse(VolleyError arg0) {
// TODO Auto-generated method stub
myImage.setImageResource(R.drawable.ic_launcher);
}
});
request.setTag(TAG);
MySingleton.getInstance(this).addToRequestQueue(request);
} @Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (mRequestQueue != null) {
mRequestQueue.cancelAll(TAG);
}
}
}

效果图:

9.JSON requests

Volley provides the following classes for JSON requests:

JsonArrayRequest—A request for retrieving a JSONArray response body at a given URL.

JsonObjectRequest—A request for retrieving a JSONObject response body at a given URL, allowing for an optional JSONObject to be passed in as part of the request body.

Both classes are based on the common base class JsonRequest.

使用例子:

mTextView = (TextView) findViewById(R.id.text);
mRequestQueue = Volley.newRequestQueue(this);
//String url = "http://my-json-feed";
String url = "http://api.androidhive.info/volley/person_object.json";
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stub
mTextView.setText("Response: " + response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError response) {
// TODO Auto-generated method stub
mTextView.setText("Response: " + response.toString());
}
});
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);

.10 自己定义Response

For cases where you do need to implement a custom request, this is all you need to do:

1.Extend the Request class, where represents the type of parsed response the request expects. So if your parsed response is a string, for example, create your custom request by extending Request. See the Volley toolbox classes StringRequest and ImageRequest for examples of extending Request.

2.Implement the abstract methods parseNetworkResponse() and deliverResponse(), described in more detail below.

一个例子:

public class GsonRequest<T> extends Request<T> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Listener<T> listener; /**
* Make a GET request and return a parsed object from JSON.
*
* @param url URL of the request to make
* @param clazz Relevant class object, for Gson's reflection
* @param headers Map of request headers
*/
public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
Listener<T> listener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
} @Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
} @Override
protected void deliverResponse(T response) {
listener.onResponse(response);
} @Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(
gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}

源代码下载地址

http://download.csdn.net/detail/hfreeman2008/8917631

參考资料

  1. https://developer.android.com/intl/zh-cn/training/volley/index.html

    Transmitting Network Data Using Volley

    2.http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

    Android working with Volley Library

android开发笔记之Volley (1)的更多相关文章

  1. Android开发笔记——以Volley图片加载、缓存、请求及展示为例理解Volley架构设计

    Volley是由Google开源的.用于Android平台上的网络通信库.Volley通过优化Android的网络请求流程,形成了以Request-RequestQueue-Response为主线的网 ...

  2. Android开发笔记:打包数据库

    对于数据比较多的控制一般会加入SQLite数据库进行数据存储,在打包时这些数据库是不自动打包到apk中的,如何创建数据库呢 方法1:将创建数据库的sql语句在SQLiteHelper继承类中实现,在第 ...

  3. Android开发笔记--hello world 和目录结构

    原文:Android开发笔记--hello world 和目录结构 每接触一个新东西 都有一个hello world的例子. 1.新建项目 2.配置AVD AVD 没有要新建个,如果不能创建 运行SD ...

  4. 【转】Android开发笔记(序)写在前面的目录

    原文:http://blog.csdn.net/aqi00/article/details/50012511 知识点分类 一方面写写自己走过的弯路掉进去的坑,避免以后再犯:另一方面希望通过分享自己的经 ...

  5. [APP] Android 开发笔记 003-使用Ant Release 打包与keystore加密说明

    接上节 [APP] Android 开发笔记 002 5. 使用ant release 打包 1)制作 密钥文件 release.keystore (*.keystore) keytool -genk ...

  6. [APP] Android 开发笔记 002-命令行创建默认项目结构说明

    接上节:[APP] Android 开发笔记 001 4. 默认项目结构说明: 这里我使用Sublime Text 进行加载.

  7. Android开发笔记(一百三十四)协调布局CoordinatorLayout

    协调布局CoordinatorLayout Android自5.0之后对UI做了较大的提升.一个重大的改进是推出了MaterialDesign库,而该库的基础即为协调布局CoordinatorLayo ...

  8. 【转】Android开发笔记——圆角和边框们

    原文地址:http://blog.xianqu.org/2012/04/android-borders-and-radius-corners/ Android开发笔记——圆角和边框们 在做Androi ...

  9. 《ArcGIS Runtime SDK for Android开发笔记》

    开发笔记之基础教程 ArcGIS Runtime SDK for Android 各版本下载地址 <ArcGIS Runtime SDK for Android开发笔记>——(1).And ...

随机推荐

  1. 7.spark Streaming 技术内幕 : 从DSteam到RDD全过程解析

    原创文章,转载请注明:转载自 听风居士博客(http://www.cnblogs.com/zhouyf/)   上篇博客讨论了Spark Streaming 程序动态生成Job的过程,并留下一个疑问: ...

  2. EL表达式无法显示Model中的数据

    后台程序通过Debug都能正常返回数据并封装到Model中.而在前台通过EL表达式取值时却是原样输出,如${cart.num}... ///展现我的购物车 @RequestMapping(" ...

  3. Druid数据迁移小计

    Druid数据迁移小计 Druid 官方网站上讲了相关的 Dump Segment 和 Insert Segment 相关的功能,但是经过测试这些功能都不好用,报 Guice 的依赖错误,懒得找具体原 ...

  4. PHP 边执行边输出

    <?php for ($i = 1; $i <= 5; $i++) { print "#$i 完毕<hr>"; sleep(1); print str_pa ...

  5. 第八届山东省ACM大学生程序设计竞赛个人总结

    因为省赛,从开学紧张到5月7号.心思也几乎全放在ACM的训练上.因为我还是校台球协会的会长,所以台协还有一些事情需要忙,但是我都给延迟了.老会长一直在催我办校赛,但我一直说 等等吧,因为校赛只能在周六 ...

  6. 使用phonegap开发安卓HLS播放软件解决方案

    目前使用phonegap开发的手机应用,很少涉及视频播放的功能,究其原因,主要是phonegap提供的API里面对视频播放功能支持度不够,当然播放音频一般情况下还是能够实现的,由于工作需要,自己研究了 ...

  7. 配置无线AP 采用POE供电模块怎么配置无线AP没有POE交换机

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha 采用POE供电模块怎么配置无线AP没有POE交换机 IP-com f130ap http ...

  8. 【20181019T1】加密【逆元+位运算】

    题面 [错解] 可能要逆推 <<就是乘法,好做 但^是什么东西? 欸暴力map70分,索性妥协 [正解] 注意^是自己异或上自己右移,前i位就是t的前i位 往后推就好 代码

  9. 【哈希表】Ural Championship April 30, 2017 Problem H. Hamburgers

    题意:有n群人,每个人有喜欢的汉堡配方:有m家店,给出每家店的每个汉堡的配方,如果存在某个汉堡,其配料表包含某个人喜欢的配方,则这个人喜欢这个汉堡所在的店家.问你对每群人,输出被喜欢的人数最多的店面是 ...

  10. 【动态规划】POJ2385-Apple Catching

    [题目大意] 有两棵树1和2,奶牛Bessie位于树1下,每个单位时间会有一个苹果从其中一棵树掉下来,同时Bessie也可以移动一次,但是Bessie不希望移动超过W次,问T时间内Bessie最多得到 ...