您的位置:首页 > 其它

Volley的学习笔记

2016-05-02 15:15 267 查看

Volley

回忆xutils:
快速开发型框架
,DbUtils(orm),ViewUtils(ioc),HttpUtils,BitmapUtils

其他的快速开发型框架:andBase,thinkandroid,loonandroid,dhroid

orm:对象关系型映射

db:create table t_table(_id integer primary key autoincret…);

insert–>save(obj)

ioc:控制反转

Obj obj = new Obj();

对象的实例化,不用new关键字就可以了吧.

为什么要讲volley?

因为它是google出的,google 在2013 i/o大会上提出来的.

而且在几个项目里面已经看到了它的身影

google公司为什么会去搞一个volley框架?

用户开启一个activity,然后加载网络,这个时候.如果用户点击了finish按钮.activity被销毁了–>网络请求和activity的生命周期是应该联动起来的.

listview加载图片的情况比较多.如果用户快速的去滑动listview–>getView->快速的加载图片,用户停止操作的时候.其实真正现实的图片最多就几张—>图片应该缓存起来(内存 +本地 )

如果用户打开了一个activity,用户旋转了一下屏幕.activity会旋转–>生命周期重走了–>网络请求缓存

之前我们的网络请求,httpurlconnection,httpclient,asynctask(api)–>android sdk–>封装性不够好.1000个开发者就有1000种使用方式–>不够统一

理念很容易理解,是开源的.

volley是啥?

是一种
通信框架
,和xutils中的HttpUtils,BitmapUtils

Volley两个核心类

Request:一个请求

StringRequest:请求的时候直接回来一个String

JsonObjectRequest:请求的时候直接回来一个JsonObject

JsonArrayRequest:请求的时候直接回来一个JsonArray

ImageRequest:请求的时候直接回来一个Bitmap

自定义请求:一会我们会结合gson

ImageLoader:图片的加载器

NetWorkImageView:继承了imageView,对ImageView进行了拓展

RequestQueue:请求队列.

一步一步学习

JsonObject取值

String origin = response.getString(“origin”);// 方式一

这个如果没有对应的key会抛异常.需要异常处理

String origin = response.optString(“origin”);// 方式二

这个如果没有对应的key不会抛异常.会返回一个默认值

optString:默认值”“

optInt:默认值 0

比如有的实体bean属性很多.我们不喜欢去建议对应的XXX.class的时候.可以使用JsonObject里面的这个方法;

图片

大图片的处理:

大图片处理的核心

核心类:BitmapFactory.Options

核心方法:

decodeOptions.inJustDecodeBounds = true;–>得到图片的宽度以及高度,不需要把图片加载到内存 10M

decodeOptions.inJustDecodeBounds = false;–>真正去加载图片

decodeOptions.inSampleSize–>采样率–>不同的框架有不同的核心算法

特点:2 4 8 –>取值最好使用2的指数

网络请求的取消

volley:多级别取消

取消某一个请求:

取消请求的队列:

//2. 创建RequestQueue
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
//3. 发起请求
queue.add(stringRequest);
//取消单个请求
stringRequest.cancel();//取消一个请求
//取消所有请求
queue.cancelAll(null);//取消请求队列里面所有的方法
//取消置顶tag的请求
queue.cancelAll("tag1");//取消tag为tag1的一个请求
//请求添加tag-->tag的目的就是为了反查
stringRequest.setTag("tag1");
//两个不同的请求可以设置同一个tag
stringRequest.setTag("tag1");
//  stringRequest1.setTag("tag1");


实例Demo:

* 注意:需要自行关联Volley库,在清单文件中加入联网权限


MainActivity:

package com.lqr.myvolleydemo;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

/**
* @author CSDN_LQR
* @工程 MyVolleyDemo
* @包名 com.lqr.myvolleydemo
* @TODO 学习使用Volley
*/
public class MainActivity extends Activity {

private ImageView mIv;
private NetworkImageView mNiv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mIv = (ImageView) findViewById(R.id.iv);
mNiv = (NetworkImageView) findViewById(R.id.niv);

// StringRequest的学习
initStringRequest();

// JsonObjectRequest的学习
initJsonObjectRequest();

// JsonArrayRequest的学习
initJsonArrayRequest();

// ImageRequest的学习
initImageRequest();

// NetworkImageView的学习
// initNetworkImageView();

// ImageLoader的学习
initImageLoader();

// 自定义请求的学习
initGsonRequest();

// 取消请求的学习
initCancelRequest();

}

/**
* 取消请求的学习
*/
private void initCancelRequest() {
findViewById(R.id.btnCancelRequest).setOnClickListener(
new OnClickListener() {

@Override
public void onClick(View v) {
String url = "http://www.baidu.com";
StringRequest stringRequest = new StringRequest(url,
new Listener<String>() {

@Override
public void onResponse(String response) {
System.out.println(response);
}
}, new ErrorListener() {

@Override
public void onErrorResponse(
VolleyError error) {
System.out.println(error.getMessage());
}
});

RequestQueue queue = VolleyTools.getInstance(
MainActivity.this).getQueue();
queue.add(stringRequest);

/* ========== 取消请求 begin =========== */

// 单个取消
stringRequest.cancel();

// 多个取消
queue.cancelAll(null);// 如果tag为null,则取消请求队列中所有的请求

stringRequest.setTag("TAG");
queue.cancelAll("TAG");// 如果tag有指定,则取消请求队列中所有Tag为TAG的请求

/* ========== 取消请求 end =========== */
}
});

}

/**
* 自定义请求的学习
*/
private void initGsonRequest() {
findViewById(R.id.btnGsonRequest).setOnClickListener(
new OnClickListener() {

@Override
public void onClick(View v) {

// 1.创建自定义的GsonRequest对象
String url = "http://192.168.1.100:8080/jsonArray.json";
GsonRequest<IP> gsonRequest = new GsonRequest<IP>(
Request.Method.GET, url, new ErrorListener() {

@Override
public void onErrorResponse(
VolleyError error) {
System.out.println(error.getMessage());
}
}, new Listener<IP>() {

@Override
public void onResponse(IP response) {
System.out.println(response.origin);
}
}, IP.class);

// 创建请求队列RequestQueue
RequestQueue requestQueue = Volley
.newRequestQueue(MainActivity.this);
// 把GsonRequest添加到RequestQueue去执行
requestQueue.add(gsonRequest);
}
});

}

/**
* ImageLoader的学习
*/
private void initImageLoader() {
findViewById(R.id.btnImageLoader).setOnClickListener(
new OnClickListener() {

@Override
public void onClick(View v) {
// RequestQueue queue = Volley
// .newRequestQueue(MainActivity.this);
// ImageCache imageCache = new MyImageCache();
// // 创建imageLoader对象
// ImageLoader imageLoader = new ImageLoader(queue,
// imageCache);

ImageLoader imageLoader = VolleyTools.getInstance(
MainActivity.this).getImageLoader();

String url = "http://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=http%3A%2F%2Fimg3.redocn.com%2Ftupian%2F20150411%2Fshouhuixiantiaopingguoshiliang_4042458.jpg&thumburl=http%3A%2F%2Fimg4.imgtn.bdimg.com%2Fit%2Fu%3D1301259139%2C2025033435%26fm%3D21%26gp%3D0.jpg";

// 调用imageLoader的get方法
imageLoader.get(url, new ImageListener() {

@Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getMessage());
}

@Override
public void onResponse(ImageContainer response,
boolean isImmediate) {
Bitmap bitmap = response.getBitmap();
mIv.setImageBitmap(bitmap);
}
});
}
});
}

/**
* NetworkImageView的学习
*/
private void initNetworkImageView() {
mNiv.setDefaultImageResId(R.drawable.ic_launcher);// 默认图片
mNiv.setErrorImageResId(R.drawable.ic_launcher);// 出错时显示的图片
String url = "http://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=http%3A%2F%2Fimg3.redocn.com%2Ftupian%2F20150411%2Fshouhuixiantiaopingguoshiliang_4042458.jpg&thumburl=http%3A%2F%2Fimg4.imgtn.bdimg.com%2Fit%2Fu%3D1301259139%2C2025033435%26fm%3D21%26gp%3D0.jpg";
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
ImageCache imageCache = new MyImageCache();
// ImageLoader imageLoader = new ImageLoader(请求队列, 自定义缓存);
ImageLoader imageLoader = new ImageLoader(queue, imageCache);
mNiv.setImageUrl(url, imageLoader);
}

/**
* ImageRequest的学习
*/
private void initImageRequest() {
findViewById(R.id.btnImageRequest).setOnClickListener(
new OnClickListener() {

@Override
public void onClick(View v) {
// 1.创建ImageRequest
String url = "http://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=http%3A%2F%2Fimg3.redocn.com%2Ftupian%2F20150411%2Fshouhuixiantiaopingguoshiliang_4042458.jpg&thumburl=http%3A%2F%2Fimg4.imgtn.bdimg.com%2Fit%2Fu%3D1301259139%2C2025033435%26fm%3D21%26gp%3D0.jpg";
int maxWidth = 0;// 期望的宽,0是原样输出
int maxHeight = 0;
ImageRequest imageRequest = new ImageRequest(url,
new Listener<Bitmap>() {

@Override
public void onResponse(Bitmap response) {
mIv.setImageBitmap(response);
}
}, maxWidth, maxHeight,
Bitmap.Config.ARGB_4444, new ErrorListener() {

@Override
public void onErrorResponse(
VolleyError error) {
System.out.println(error.getMessage());
}
});
// 2.创建RequestQueue
RequestQueue requestQueue = Volley
.newRequestQueue(MainActivity.this);
// 3.把ImageRequest添加到RequestQueue
requestQueue.add(imageRequest);
}
});
}

/**
* JsonArrayRequest的学习
*/
private void initJsonArrayRequest() {
findViewById(R.id.btnJsonArrayRequest).setOnClickListener(
new OnClickListener() {

@Override
public void onClick(View v) {
// 1.创建JsonArrayRequest对象
String url = "http://192.168.1.100:8080/jsonArray.json";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
url, new Listener<JSONArray>() {

@Override
public void onResponse(JSONArray response) {
System.out.println("success:"
+ response.length());
}
}, new ErrorListener() {

@Override
public void onErrorResponse(
VolleyError error) {
System.out.println(error.getMessage());
}
});

// 2.创建RequestQueue对象
RequestQueue requestQueue = Volley
.newRequestQueue(MainActivity.this);
// 3.把JsonArrayRequest添加到RequestQueue
requestQueue.add(jsonArrayRequest);
}
});
}

/**
* JsonObjectRequest的学习
*/
private void initJsonObjectRequest() {
findViewById(R.id.btnJsonObjectRequest).setOnClickListener(
new OnClickListener() {

@Override
public void onClick(View v) {
// 1.创建JsonObjectRequest对象
String url = "http://192.168.1.100:8080/ip.json";
JSONObject jsonRequest = null;// 请求参数可以用jsonObject的方式发送
// key-value
// jsonString --> jsonObject
// JsonObject jsonObject = new JsonObject(jsonString)
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
url, jsonRequest, new Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
String ip = response
.optString("origin");
System.out.println("success:" + ip);
}
}, new ErrorListener() {

@Override
public void onErrorResponse(
VolleyError error) {
System.out.println(error.getMessage());
}
});
// 2.创建RequestQueue对象
RequestQueue requestQueue = Volley
.newRequestQueue(MainActivity.this);
// 3.把JsonObjectRequest添加到RequestQueue
requestQueue.add(jsonObjectRequest);
}
});
}

/**
* StringRequest的学习
*/
private void initStringRequest() {
findViewById(R.id.btnStringRequest).setOnClickListener(
new OnClickListener() {

@Override
public void onClick(View v) {
// 1.创建StringRequest对象
String url = "http://www.baidu.com";
StringRequest stringRequest = new StringRequest(url,
new Listener<String>() {

@Override
public void onResponse(String response) {
System.out.println(response);
}
}, new ErrorListener() {

@Override
public void onErrorResponse(
VolleyError error) {
System.out.println(error.getMessage());
}
});

// 2.创建RequestQueue
RequestQueue requestQueue = Volley
.newRequestQueue(MainActivity.this);

// 3.把StringRequest添加到RequestQueue
requestQueue.add(stringRequest);
}
});

}

}


MyImageCache:

package com.lqr.myvolleydemo;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader.ImageCache;

/**
* @author CSDN_LQR
* @工程 MyVolleyDemo
* @包名 com.lqr.myvolleydemo
* @TODO 使用LruCache自定义的缓存类
*/
public class MyImageCache implements ImageCache {
LruCache<String, Bitmap> mLruCache;

// 存储结构/容器/集合缓存的最大值
// 1.告知缓存的具体大小
// private int maxSize = 5 ;// 5m
private int maxSize = 5 * 1024 * 1024;// 5242880byte

public MyImageCache() {
mLruCache = new LruCache<String, Bitmap>(maxSize) {
// 2.覆写sizeOf方法(用于计算每张图片的大小)
@Override
protected int sizeOf(String key, Bitmap value) {
// return super.sizeOf(key, value);//默认返回1

// 返回每一个entry对应的大小
// 具体大小需要和我们定义的maxSize单位统一
// return value.getByteCount()/1024/1024;//对应maxSize = 5m
return value.getByteCount();// 对应maxSize = 5242880byte
}
};
}

@Override
public Bitmap getBitmap(String url) {// 取图片
// TODO
return mLruCache.get(url);
}

@Override
public void putBitmap(String url, Bitmap bitmap) {// 取图片
// TODO
mLruCache.put(url, bitmap);
}
}


GsonRequest:

package com.lqr.myvolleydemo;

import java.io.UnsupportedEncodingException;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

/**
* @author CSDN_LQR
* @工程 MyVolleyDemo
* @包名 com.lqr.myvolleydemo
* @TODO 自定义一个Request,使用gson来解析json
*/
public class GsonRequest<T> extends Request<T> {

private final Listener<T> mListener;
Class<T> clazz;

public GsonRequest(int method, String url, ErrorListener listener,
Listener<T> mListener, Class<T> clazz) {
super(method, url, listener);
this.mListener = mListener;
this.clazz = clazz;
}

/**
* 处理响应结果
*/
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
String jsonString;
try {
jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
jsonString = new String(response.data);
}

T obj;
try {
Gson gson = new Gson();
obj = gson.fromJson(jsonString, clazz);
// 返回结果
return Response.success(obj,
HttpHeaderParser.parseCacheHeaders(response));
} catch (JsonSyntaxException e) {
// 返回结果
e.printStackTrace();
return Response.error(new ParseError());
}

}

/*
* 传递响应结果
*/
@Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}

}


IP:

package com.lqr.myvolleydemo;

/**
* @author CSDN_LQR
* @工程 MyVolleyDemo
* @包名 com.lqr.myvolleydemo
* @TODO ip.json对应的bean
*
*       ip.json的内容:{"origin":"10.0.0.1"}
*/
public class IP {

public String origin;
}


VolleyTools:

package com.lqr.myvolleydemo;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.android.volley.toolbox.ImageLoader.ImageCache;

import android.content.Context;

/**
* @author CSDN_LQR
* @工程 MyVolleyDemo
* @包名 com.lqr.myvolleydemo
* @TODO Volley的单例化
*/
public class VolleyTools {

/* ========== Volley单例化变量 begin =========== */

private static VolleyTools instance;
private RequestQueue mQueue;
private ImageCache mImageCache;
private ImageLoader mImageLoader;

public RequestQueue getQueue() {
return mQueue;
}

public ImageCache getImageCache() {
return mImageCache;
}

public ImageLoader getImageLoader() {
return mImageLoader;
}

/* ========== Volley单例化变量 end =========== */

private VolleyTools(Context context) {
mQueue = Volley.newRequestQueue(context);
mImageCache = new MyImageCache();
mImageLoader = new ImageLoader(mQueue, mImageCache);
}

public static VolleyTools getInstance(Context context) {
if (instance == null) {
synchronized (VolleyTools.class) {
if (instance == null) {
instance = new VolleyTools(context);
}
}
}

return instance;
}
}


布局文件:

<LinearLayout 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:orientation="vertical"
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=".MainActivity" >

<Button
android:id="@+id/btnStringRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="StringRequest" />

<Button
android:id="@+id/btnJsonObjectRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="JsonObject" />

<Button
android:id="@+id/btnJsonArrayRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="JsonArrayRequest" />

<Button
android:id="@+id/btnImageRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ImageRequest" />

<Button
android:id="@+id/btnImageLoader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ImageLoader" />

<Button
android:id="@+id/btnGsonRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自定义请求" />

<Button
android:id="@+id/btnCancelRequest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="取消请求" />

<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<com.android.volley.toolbox.NetworkImageView
android:id="@+id/niv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: