//Volley 缓存StringRequest,JsonObjectRequest两级缓存(网络--->磁盘)
//ImageLoader(三级缓存 网络--->内存缓存---->磁盘)
//从缓存中获取数据(缓存失效时间失效)--->hit获取直接展示数据
//没有获取数据,走网络,响应头,判断是否进行缓存
//首先展示的是volley的工具类 封装到一个类中统一使用
/**
* Created by softpo on 2017/4/24.
* Email: [email protected]
*/
public class VolleyUtils {
//线程安全--->恶汉式
private static VolleyUtils ourInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
public RequestQueue getRequestQueue() {
return mRequestQueue;
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
//公有访问方法
public static VolleyUtils getInstance(Context context) {
if(ourInstance ==null){//线程不安全的问题
synchronized (VolleyUtils.class){
if(ourInstance ==null){
ourInstance = new VolleyUtils(context);
}
}
}
return ourInstance;
}
//私有的构造方法
private VolleyUtils(Context context) {
//创建RequestQueue,ImageLoader
File cacheDir = context.getCacheDir();//data/data/包名/cache/XXX
//sd卡下的Android/包名/files/images
File rootDirectory = context.getExternalFilesDir("images");
Cache cache = new DiskBasedCache(rootDirectory,100<<20);//100M 1024 = 2的十次方
Network network = getNetwork();
mRequestQueue = new RequestQueue(cache,network,4);
mRequestQueue.start();//必须调用,不然没有网络请求
//ImageLoader
mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {
LruCache mLruCache =
new LruCache((int) (Runtime.getRuntime().maxMemory()/8)){
//该方法,不重写,15×1024×1024
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};
@Override
public Bitmap getBitmap(String url) {
return mLruCache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
mLruCache.put(url,bitmap);
}
});
}
private Network getNetwork() {
Network network = null;
if(Build.VERSION.SDK_INT>=9){
network = new BasicNetwork(new HurlStack());//HttpUrlConnection,标准的网络请求
}else {
//如果api小于9,使用httpClient进行网络请求
network = new BasicNetwork(new HttpClientStack(new DefaultHttpClient()));
}
return network;
}
}
//在activity中使用volley的具体事例
//1、Volley进行网络请求统一管理,RequestQueue
//2、发起请求,StringRequest,ImageRequest,JSONObjectRequest
//3、将请求添加到请求队列
public class MainActivity extends AppCompatActivity {
private ImageView mImageView;
private RequestQueue mRequestQueue;//请求队列
private Handler mHandler = new Handler() {//重写它的方法
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
private String mStringPostUrl;
private String mImageUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
mStringPostUrl = "http://app.vmoiver.com/apiv3/post/getPostInCate";
// mImageUrl = "http://pic4.nipic.com/20091121/3764872_215617048242_2.jpg";
// mImageUrl = "http://10.0.174.102:8080/AndroidProjectServer/PostServlet";
// mImageUrl = "http://img15.3lian.com/2015/f2/50/d/71.jpg";
// mImageUrl = "http://img17.3lian.com/d/file/201701/23/22caec632f605230b882959614369660.jpg";
// mImageUrl = "http://img1.3lian.com/2015/w7/85/d/21.jpg";
//在断网的情况下,能否获取数据取决于cache-control
// mImageUrl = "http://img.pconline.com.cn/images/upload/upc/tx/photoblog/1204/03/c13/11135431_11135431_1333465711453.jpg";
mImageUrl = "http://scimg.jb51.net/allimg/151228/14-15122Q60431W4.jpg";
//1、实例化请求队列
mRequestQueue = Volley.newRequestQueue(this);
}
private void initView() {
mImageView = (ImageView) findViewById(R.id.image);
}
//2、创建请求
public void volley(View view) {
Request request = null;
switch (view.getId()) {
case R.id.btnGetString:
String stringUrl = "http://www.baidu.com";
request = new StringRequest(
Request.Method.GET,//请求方式
stringUrl,//地址
new Response.Listener
() {//请求成功回调
@Override
public void onResponse(String response) {
//对数据进行解析,刷新适配器,展示数据
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
Log.d("flag", "----------------->onResponse: Get请求获取的数据: " + response);
}
},
new Response.ErrorListener() {//请求失败的回调
@Override
public void onErrorResponse(VolleyError error) {
//网络不好,提示用户,从缓存中获取数据
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
Log.d("flag", "----------------->onErrorResponse: Get请求失败: " + error.getMessage());
}
});
break;
case R.id.btnPostString://请求参数不是明文展示,保护参数
/**
* http://app.vmoiver.com/apiv3/post/getPostInCate
参数:cateid = 0//分类
p = 1//页数
*/
request = new StringRequest(Request.Method.POST,
mStringPostUrl,
new Response.Listener() {
@Override
public void onResponse(String response) {
try {
JSONObject result = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
Log.d("flag", "----------------->onResponse: POST请求获取数据: " + response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
Log.d("flag", "----------------->onErrorResponse: POST请求失败:" + error.getMessage());
//断网的情况下获取数据 String类型数据(Json)
//从缓存中获取数据
Cache cache = mRequestQueue.getCache();
if (cache != null) {
Cache.Entry entry = cache.get(mStringPostUrl);
if (entry != null) {
byte[] data = entry.data;
String result = new String(data);
//TODO JSON解析,刷新适配器,ListView展示数据
Log.d("flag", "----------------->onErrorResponse: 断网下获取的缓存数据: " +result);
}
}
}
}) {//重写StringRequest的方法
//Ctrl+O
//params---->参数,请求参数:cateid=0;p = 1;
@Override
protected Map getParams() throws AuthFailureError {
Map map = new HashMap<>();
map.put("catied", "0");
map.put("p", "1");
return map;
}
};
//2.1向stringPost请求中添加(add/set)参数
break;
case R.id.btnImage:
request = new ImageRequest(mImageUrl,
new Response.Listener() {
@Override
public void onResponse(Bitmap response) {
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
mImageView.setImageBitmap(response);
Log.d("flag", "----------------->onResponse: 图片的尺寸, width: "
+ response.getWidth() + ",height: " + response.getHeight());
}
},
//图片的缩放,压缩
300,//宽度的最大值,0,不进行缩放
400, //高度的最大值,0,不进行缩放
ImageView.ScaleType.FIT_XY,
Bitmap.Config.RGB_565, //Bitmap生成的配置格式
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
mImageView.setImageResource(R.mipmap.ic_launcher);
Log.d("flag", "----------------->onErrorResponse: 图片获取失败 " + error.getMessage());
}
}){
// @Override
// protected Map getParams() throws AuthFailureError {
// Map map = new HashMap<>();
//
// map.put("name","jack");
// map.put("age","35");
// map.put("tel","110");
//
// return map;
// }
//
// @Override
// public int getMethod() {
// return Method.POST;
// }
};
break;
case R.id.btnCache://获取PostString
//1、通过请求队列获取缓存
Cache cache = mRequestQueue.getCache();
if (cache != null) {
Cache.Entry entry = cache.get(mImageUrl);
if (entry != null) {
//获取entry中数据
byte[] data = entry.data;
// String result = new String(data);
// result = data.toString();内存地址
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
// Log.d("flag", "----------------->volley: 缓存中数据: " + result);
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
mImageView.setImageBitmap(bitmap);
} else {
Toast.makeText(this, "具体的网址没有缓存数据", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "没有缓存对象", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btnJson:
/**
POST请求
http://api.m.mtime.cn/PageSubArea/HotPlayMovies.api
参数:locationId = 290
*/
String jsonUrl = "http://api.m.mtime.cn/PageSubArea/HotPlayMovies.api";
JSONObject params = new JSONObject();
try {
params.put("locationId","290");
} catch (JSONException e) {
e.printStackTrace();
}
request = new JsonObjectRequest(Request.Method.POST,
jsonUrl,
params,//如果是GET请求,null
new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
//TODO 直接进行解析,方便操作
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
Log.d("flag", "----------------->onResponse: 获取的JSON数据是: " +response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("flag", "----------------->onErrorResponse: " +error.getMessage());
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
}
});
break;
case R.id.btnImageLoader:
//参数二,内存缓存 运行内存
ImageLoader imageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
//内存缓存LruCache链表
LruCache lruCache =
new LruCache((int) (Runtime.getRuntime().maxMemory()/8)){
@Override
protected int sizeOf(String key, Bitmap value) {
// value.getRowBytes()*value.getHeight();
return value.getByteCount();//
}
};
@Override
public Bitmap getBitmap(String url) {
return lruCache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
lruCache.put(url,bitmap);
}
});
imageLoader.get(mImageUrl, new ImageLoader.ImageListener() {
@Override
public void onResponse(ImageLoader.ImageContainer response,
boolean isImmediate) {
Bitmap bitmap = response.getBitmap();
mImageView.setImageBitmap(bitmap);
}
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "请求图片失败", Toast.LENGTH_SHORT).show();
}
},256,360, ImageView.ScaleType.CENTER_CROP);
break;
default:
break;
}
//3队列中添加该请求
if (request != null) {
mRequestQueue.add(request);
}
}
}
下面是使用volley的iamgglodaer加载图片的实例
public class VolleyActivity extends AppCompatActivity {
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_volley);
mRequestQueue = VolleyUtils.getInstance(this).getRequestQueue();
mImageLoader = VolleyUtils.getInstance(this).getImageLoader();
mImageView = (ImageView) findViewById(R.id.image);
}
public void volley(View view) {
String url = "http://www.qq.com";
final StringRequest request = new StringRequest(url, new Response.Listener() {
@Override
public void onResponse(String response) {
Log.d("flag", "----------------->onResponse: 自定义的RequestQueue获取数据" + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("flag", "----------------->onErrorResponse: 失败" + error.getMessage());
}
});
mRequestQueue.add(request);
String imageUrl = "http://img01.taopic.com/150305/318754-15030510213437.jpg";
mImageLoader.get(imageUrl, new ImageLoader.ImageListener() {
@Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
mImageView.setImageBitmap(response.getBitmap());
}
@Override
public void onErrorResponse(VolleyError error) {
mImageView.setImageResource(R.mipmap.ic_launcher);
}
});
}
}