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. [水煮 ASP.NET Web API2 方法论](1-8)添加 Session 状态

    问题 ASP.NET Web API 构建 Web 应用程序时,要求使用 Session 在服务器存储一些用户特定的信息 解决方案 ASP.NET Web API 不支持 Session,因为 API ...

  2. 洛谷P4587 [FJOI2016]神秘数(主席树)

    题面 洛谷 题解 考虑暴力,对于询问中的一段区间\([l,r]\),我们先将其中的数升序排序,假设当前可以表示出\([1,k]\)目前处理\(a_i\),假如\(a_i>k+1\),则答案就是\ ...

  3. win10安装mysql8.0.15

    1:下载mysql8.0.15 https://www.mysql.com/downloads/ 2:下载完解压,增加my.ini配置文件 [mysqld] # 设置3306端口 port= # 设置 ...

  4. Linux命令之killall

    killall [选项] [-signal(信号)] [name] killall发送一条信号给所有允许任意指定命令的进程.如果没有指定信号名,则发送SIGTERM.信号可以是名字或数字,只有信号0( ...

  5. sql 常见错误

    notFound = 1403L; .dupKey = -1L; openCloseErr = -2117L; cursorNotOpenErr = -1002L; .nullCursor = -14 ...

  6. 内存分哪些区 C++,ios,java

    韩梦飞沙 yue31313 韩亚飞 han_meng_fei_sha 313134555@qq.com C/C++编译的程序占用的内存分为以下几个部分 1.栈区(stack)—由编译器自动分配释放,存 ...

  7. BZOJ2462[Beijing2011]矩阵模板(二维Hash)

    二维矩阵匹配问题,至今不知道Q的范围是多少,反正是要求做到读入复杂度. 二维Hash:就是一维的等效拓展,注意两维的Base不能相同. 其余就是一维Hash和二维前缀和的结合,可以自然溢出,据说概率很 ...

  8. [Nescafé41]编码病毒(循环卷积)

    题意看起来好麻烦实际上很简单,首先4s可以先bitset暴力一下,听说卡卡就能过:$O(2^{22}+n^2/32)$ #include<cstdio> #include<bitse ...

  9. 【SAM】codevs3160-最长公共子串

    [题目大意] 求两个字符串的最长公共子串. [思路] 对第一个字符串建立后缀自动机,第二个字符串去匹配.cnt记录当前最长公共子串的长度,而ret记录答案. p代表位置指针,初始在rt位置. 对于第二 ...

  10. bzoj 4195: [Noi2015]程序自动分析

    4195: [Noi2015]程序自动分析 Description 在实现程序自动分析的过程中,常常需要判定一些约束条件是否能被同时满足. 考虑一个约束满足问题的简化版本:假设x1,x2,x3,…代表 ...