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. 【已解决】php本地环境超级慢

    打开 C:\Windows\System32\drivers\etc去掉 #127.0.0.1 localhost 前面的#保留 #::1 localhost 前面的#

  2. 读书笔记(javascript 高级程序设计)

    一. 数据类型: 1. undefined: 未声明和未初始化的变量,typeof 操作符返回的结果都是 undefined:(建议未初始化的变量进行显式赋值,这样当 typeof 返回 undefi ...

  3. Codeforces Round #165 (Div. 1) Greenhouse Effect(DP)

    Greenhouse Effect time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...

  4. jvm 哪些是不会被gc回收的

    韩梦飞沙 yue31313 韩亚飞 han_meng_fei_sha 313134555@qq.com

  5. Codeforces Round #196 (Div. 1) 题解

    (CF唯一不好的地方就是时差……不过还好没去考,考的话就等着滚回Div. 2了……) A - Quiz 裸的贪心,不过要用矩阵乘法优化或者直接推通式然后快速幂.不过本傻叉做的时候脑子一片混乱,导致WA ...

  6. Gym 101128F Sheldon Numbers(网络流)

    [题目链接] http://codeforces.com/gym/101128/attachments [题目大意] 给出一张地图,分为高地和低地,高低地的交界线上划有红线, 现在要开小车跨过每条红线 ...

  7. 20162318 2016-2017-2《Java程序设计》课堂实践项目

    20162318 2016-2017-2<Java程序设计>课堂实践项目 String类的使用 在String类中有一种split的方法.它可以把字符串分割为好几个小的字符串. 实践内容: ...

  8. (原创)Stanford Machine Learning (by Andrew NG) --- (week 5) Neural Networks Learning

    本栏目内容来自Andrew NG老师的公开课:https://class.coursera.org/ml/class/index 一般而言, 人工神经网络与经典计算方法相比并非优越, 只有当常规方法解 ...

  9. 关于abstract class 和 interface

    1.abstract class 在 Java 语言中表示的是一种继承关系,一个类只能使用一次继承关系.但是,一个类却可以实现多个interface. 2.在abstract class 中可以有自己 ...

  10. Hiho : 欧拉路径

    欧拉路径 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 在上一回中小Hi和小Ho控制着主角收集了分散在各个木桥上的道具,这些道具其实是一块一块骨牌. 主角继续往前走,面 ...