在Android开发中有很多的开源框架,比如Volley,xUtils,okhttp,
afinal等开源框架,由于本人接触Android时间不长,所接触到的开源框架并不多,了解的也不深,如果有说的不对的地方你他妈来打我啊
Volley是Google官方的开源框架,是一款轻量级的开源框架
可以用他实现多种网络请求(json的下载。文件的上传)
第一步 在Application初始化请求队列
package com.longyue.customvolley2;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import android.app.Application;
public class VolleyApplication extends Application {
/** * 01. 建立 请求队列 * 02. 将 请求队列 加入到 AndroidMain.xml中 * 03. */
private static RequestQueue queue;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
queue=Volley.newRequestQueue(getApplicationContext());
}
//入口
public static RequestQueue getQueue(){
return queue;
}
}
第二步 定义三级缓存路径(内存,软引用,磁盘)
1:内存缓存工具类 采用LruCaChe算法
package com.longyue.volley;
import java.io.File;
import android.graphics.Bitmap;
import android.util.Log;
import android.util.LruCache;
import com.android.volley.toolbox.ImageLoader.ImageCache;
public class VolleyBitmapCache implements ImageCache{
private LruCache<String,Bitmap> cache;
//设置最大的 尺寸值
// 磁盘缓存对象
// 懒汉式:
private static VolleyBitmapCache mCache;
private DiskLruCache mDisk;
private VolleyBitmapCache() {
//构造方法 实现 LruCache 缓存 图片
int maxSize=10*1024*1024;
cache=new LruCache<String,Bitmap>(maxSize){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes()*value.getHeight();
}
// 从LruCache移除某个条目的方法
@Override
protected void entryRemoved(boolean evicted, String key,
Bitmap oldValue, Bitmap newValue) {
// 把LruCache中要移除的条目,放到软引用中.
if (evicted) {
ImageSoftReference.getInstance().putSoftReference(key,
oldValue);
}
super.entryRemoved(evicted, key, oldValue, newValue);
}
};
// 创建磁盘缓存大小
mDisk = DiskLruCache.openCache(new File(Constant.cachepath),Constant.MAXBYTESIZE);
}
public static VolleyBitmapCache getInstance() {
if (mCache == null) {
mCache = new VolleyBitmapCache();
}
return mCache;
}
@Override
public Bitmap getBitmap(String url) {
// 从LruCache中取
Log.e("ccccc","1111");
Bitmap bitmap = cache.get(url);
Log.e("ccccc","2222");
if (bitmap == null) {
// 从SoftReference中取
bitmap = ImageSoftReference.getInstance().getSoftReference(url);
// 如果软引用中没有.则从磁盘中取
if (bitmap == null) {
// TODO:从磁盘中取:
bitmap = mDisk.get(url);
}
}
return bitmap;
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
// 设置
cache.put(url, bitmap);
mDisk.put(url, bitmap);
}
// 擦除缓存的方法
public void evictAll() {
cache.evictAll();
mDisk.clearCache();
}
// 擦除缓存的方法
public void evictOne(String key) {
cache.remove(key);
}
}
2:软引用 工具类 可有可无 有总比没有好
package com.longyue.volley;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
import android.graphics.Bitmap;
public class ImageSoftReference {
// 新买的手机---->强引用.
// 玩了一段时间后:手机套---->手机放在套子中:软引用
// 往map中放东西.----
// SoftReference:手机套
// Bitmap:手机
// 存放软引用的集合
private Map<String, SoftReference<Bitmap>> mMap = null;
private static ImageSoftReference mSoftReference;
private ImageSoftReference() {
mMap = new HashMap<String, SoftReference<Bitmap>>();
}
public static ImageSoftReference getInstance() {
if (mSoftReference == null) {
mSoftReference = new ImageSoftReference();
}
return mSoftReference;
}
// 将Bitmap存到软引用中
public void putSoftReference(String key, Bitmap value) {
mMap.put(key, new SoftReference<Bitmap>(value));
}
// 从软引用中获取图片
public Bitmap getSoftReference(String key) {
// 得到一个"套着手机的套子"
SoftReference<Bitmap> softReference = mMap.get(key);
// 先验证"装着手机的套子还存在不"?
if (softReference != null) {
return softReference.get();
}
return null;
}
}
3 磁盘缓存 工具类
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
package com.longyue.volley;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import com.android.volley.BuildConfig;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
/** * 磁盘缓存工具类 A simple disk LRU bitmap cache to illustrate how a disk cache would * be used for bitmap caching. A much more robust and efficient disk LRU cache * solution can be found in the ICS source code * (libcore/luni/src/main/java/libcore/io/DiskLruCache.java) and is preferable * to this simple implementation. */
public class DiskLruCache {
private static final String TAG = "DiskLruCache";
private static final String CACHE_FILENAME_PREFIX = "";
private static final int MAX_REMOVALS = 4;
private static final int INITIAL_CAPACITY = 32;
private static final float LOAD_FACTOR = 0.75f;
private final File mCacheDir;
private int cacheSize = 0;
private int cacheByteSize = 0;
private final int maxCacheItemSize = 60; // 64 item default
// 默认的缓存大小
private long maxCacheByteSize = 1024 * 1024 * 5; // 5MB default
private CompressFormat mCompressFormat = CompressFormat.JPEG;
private int mCompressQuality = 70;
private final Map<String, String> mLinkedHashMap = Collections
.synchronizedMap(new LinkedHashMap<String, String>(
INITIAL_CAPACITY, LOAD_FACTOR, true));
/** * A filename filter to use to identify the cache filenames which have * CACHE_FILENAME_PREFIX prepended. */
private static final FilenameFilter cacheFileFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return filename.startsWith(CACHE_FILENAME_PREFIX);
}
};
/** * Used to fetch an instance of DiskLruCache. * * @param cacheDir * :图片要保存的目录 * @param maxByteSize * :缓存目录可存空间的最小值 * @return */
public static DiskLruCache openCache(File cacheDir, long maxByteSize) {
// 如果缓存路径不存在,就创建出来
if (!cacheDir.exists()) {
cacheDir.mkdir();
}
// Utils.getUsableSpace(cacheDir):判断指定路径上可用的空间大小
if (cacheDir.isDirectory() && cacheDir.canWrite()
&& Utils.getUsableSpace(cacheDir) > maxByteSize) {
return new DiskLruCache(cacheDir, maxByteSize);
}
return null;
}
/** * 磁盘缓存DiskLruCache的构造方法 Constructor that should not be called directly, * instead use {@link DiskLruCache#openCache(Context, File, long)} which * runs some extra checks before creating a DiskLruCache instance. * * @param cacheDir * @param maxByteSize */
private DiskLruCache(File cacheDir, long maxByteSize) {
mCacheDir = cacheDir;
maxCacheByteSize = maxByteSize;
}
/** * Add a bitmap to the disk cache. 把一个图片存到磁盘缓存中 * * @param key * :bitmap对应的唯一标示 A unique identifier for the bitmap. * @param data * :要存储的图片 The bitmap to store. */
public void put(String key, Bitmap data) {
synchronized (mLinkedHashMap) {
if (mLinkedHashMap.get(key) == null) {
try {
final String file = createFilePath(mCacheDir, key);
if (writeBitmapToFile(data, file)) {
put(key, file);
flushCache();
}
} catch (final FileNotFoundException e) {
Log.e(TAG, "Error in put: " + e.getMessage());
} catch (final IOException e) {
Log.e(TAG, "Error in put: " + e.getMessage());
}
}
}
}
private void put(String key, String file) {
mLinkedHashMap.put(key, file);
cacheSize = mLinkedHashMap.size();
cacheByteSize += new File(file).length();
}
/** * 清空磁盘中的缓存.如果磁盘缓存中缓存的文件容量超过了指定的缓存总大小,就清除最早的那个bitmap. Flush the cache, * removing oldest entries if the total size is over the specified cache * size. Note that this isn't keeping track of stale files in the cache * directory that aren't in the HashMap. If the images and keys in the disk * cache change often then they probably won't ever be removed. */
private void flushCache() {
Entry<String, String> eldestEntry;
File eldestFile;
long eldestFileSize;
int count = 0;
while (count < MAX_REMOVALS
&& (cacheSize > maxCacheItemSize || cacheByteSize > maxCacheByteSize)) {
eldestEntry = mLinkedHashMap.entrySet().iterator().next();
eldestFile = new File(eldestEntry.getValue());
eldestFileSize = eldestFile.length();
mLinkedHashMap.remove(eldestEntry.getKey());
eldestFile.delete();
cacheSize = mLinkedHashMap.size();
cacheByteSize -= eldestFileSize;
count++;
if (BuildConfig.DEBUG) {
Log.d(TAG, "flushCache - Removed cache file, " + eldestFile
+ ", " + eldestFileSize);
}
}
}
/** * Get an image from the disk cache. 从磁盘缓存中取出key对应的图片 * * @param key * The unique identifier for the bitmap * @return The bitmap or null if not found */
public Bitmap get(String key) {
synchronized (mLinkedHashMap) {
final String file = mLinkedHashMap.get(key);
if (file != null) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Disk cache hit");
}
return BitmapFactory.decodeFile(file);
} else {
final String existingFile = createFilePath(mCacheDir, key);
if (new File(existingFile).exists()) {
put(key, existingFile);
if (BuildConfig.DEBUG) {
Log.d(TAG, "Disk cache hit (existing file)");
}
return BitmapFactory.decodeFile(existingFile);
}
}
return null;
}
}
/** * Checks if a specific key exist in the cache. 判断key对应的图片是否存在 * * @param key * The unique identifier for the bitmap * @return true if found, false otherwise */
public boolean containsKey(String key) {
// See if the key is in our HashMap
if (mLinkedHashMap.containsKey(key)) {
return true;
}
// Now check if there's an actual file that exists based on the key
final String existingFile = createFilePath(mCacheDir, key);
if (new File(existingFile).exists()) {
// File found, add it to the HashMap for future use
put(key, existingFile);
return true;
}
return false;
}
/** * 清除磁盘缓存中所有的bitmap Removes all disk cache entries from this instance cache * dir */
public void clearCache() {
DiskLruCache.clearCache(mCacheDir);
}
/** * Removes all disk cache entries from the application cache directory in * the uniqueName sub-directory. 清除某个key对应的图片 * * @param context * The context to use * @param uniqueName * A unique cache directory name to append to the app cache * directory */
public static void clearCache(Context context, String uniqueName) {
File cacheDir = getDiskCacheDir(context, uniqueName);
clearCache(cacheDir);
}
/** * 清除某个文件下面的缓存内容(图片) Removes all disk cache entries from the given * directory. This should not be called directly, call * {@link DiskLruCache#clearCache(Context, String)} or * {@link DiskLruCache#clearCache()} instead. * * @param cacheDir * The directory to remove the cache files from */
private static void clearCache(File cacheDir) {
final File[] files = cacheDir.listFiles(cacheFileFilter);
for (int i = 0; i < files.length; i++) {
files[i].delete();
}
}
/** * Get a usable cache directory (external if available, internal otherwise). * 得到磁盘缓存路径 * * @param context * The context to use * @param uniqueName * A unique directory name to append to the cache dir * @return The cache dir */
public static File getDiskCacheDir(Context context, String uniqueName) {
// Check if media is mounted or storage is built-in, if so, try and use
// external cache dir
// otherwise use internal cache dir
final String cachePath = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
|| !Utils.isExternalStorageRemovable() ? Utils
.getExternalCacheDir(context).getPath() : context.getCacheDir()
.getPath();
return new File(cachePath + File.separator + uniqueName);
}
/** * 创建磁盘缓存到的文件 Creates a constant cache file path given a target cache * directory and an image key. 创建一个缓存路径 * * @param cacheDir * @param key * @return */
public static String createFilePath(File cacheDir, String key) {
try {
// Use URLEncoder to ensure we have a valid filename, a tad hacky
// but it will do for
// this example
return cacheDir.getAbsolutePath() + File.separator
+ CACHE_FILENAME_PREFIX
+ URLEncoder.encode(key.replace("*", ""), "UTF-8");
} catch (final UnsupportedEncodingException e) {
Log.e(TAG, "createFilePath - " + e);
}
return null;
}
/** * Create a constant cache file path using the current cache directory and * an image key. * * @param key * @return */
public String createFilePath(String key) {
return createFilePath(mCacheDir, key);
}
/** * 设置图片压缩的格式和质量 Sets the target compression format and quality for images * written to the disk cache. * * @param compressFormat * @param quality */
public void setCompressParams(CompressFormat compressFormat, int quality) {
mCompressFormat = compressFormat;
mCompressQuality = quality;
}
/** * 把图片存到某个指定的文件下面 Writes a bitmap to a file. Call * {@link DiskLruCache#setCompressParams(CompressFormat, int)} first to set * the target bitmap compression and format. 将图片存到某个路径下,并对图片进行了压缩处理. * * @param bitmap * @param file * @return */
private boolean writeBitmapToFile(Bitmap bitmap, String file)
throws IOException, FileNotFoundException {
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(file),
Utils.IO_BUFFER_SIZE);
// mCompressFormat:图片压缩保存的格式-->jpeg;
// mCompressQuality:压缩的质量.
return bitmap.compress(mCompressFormat, mCompressQuality, out);
} finally {
if (out != null) {
out.close();
}
}
}
}
4两个工具类和常量
//常量类
package com.longyue.volley;
import java.io.File;
import android.os.Environment;
public class Constant {
// 磁盘缓存路径
public static String cachepath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "缓存练习";
public static long MAXBYTESIZE =8*1024 * 1024;
}
//utils工具类
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
package com.longyue.volley;
import java.io.File;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
/** * Class containing some static utility methods. */
public class Utils {
public static final int IO_BUFFER_SIZE = 8 * 1024;
private Utils() {
};
/** * Workaround for bug pre-Froyo, see here for more info: * http://android-developers.blogspot.com/2011/09/androids-http-clients.html */
public static void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (hasHttpConnectionBug()) {
System.setProperty("http.keepAlive", "false");
}
}
/** * Get the size in bytes of a bitmap. * * @param bitmap * @return size in bytes */
@SuppressLint("NewApi")
public static int getBitmapSize(Bitmap bitmap) {
// 判断sdk版本是否大于蜂巢(API 12)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
return bitmap.getByteCount();
}
// Pre HC-MR1
return bitmap.getRowBytes() * bitmap.getHeight();
}
/** * Check if external storage is built-in or removable. * * @return True if external storage is removable (like an SD card), false * otherwise. */
@SuppressLint("NewApi")
public static boolean isExternalStorageRemovable() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
return Environment.isExternalStorageRemovable();
}
return true;
}
/** * Get the external app cache directory. * * @param context * The context to use * @return The external cache dir */
@SuppressLint("NewApi")
public static File getExternalCacheDir(Context context) {
if (hasExternalCacheDir()) {
return context.getExternalCacheDir();
}
// Before Froyo we need to construct the external cache dir ourselves
final String cacheDir = "/Android/data/" + context.getPackageName()
+ "/cache/";
return new File(Environment.getExternalStorageDirectory().getPath()
+ cacheDir);
}
/** * Check how much usable space is available at a given path. 计算指定目录可用空间有多大 * * @param path * The path to check * @return The space available in bytes */
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public static long getUsableSpace(File path) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
return path.getUsableSpace();
}
final StatFs stats = new StatFs(path.getPath());
return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
}
/** * Get the memory class of this device (approx. per-app memory limit) * * @param context * @return */
public static int getMemoryClass(Context context) {
return ((ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
}
/** * Check if OS version has a http URLConnection bug. See here for more * information: * http://android-developers.blogspot.com/2011/09/androids-http-clients.html * * @return */
public static boolean hasHttpConnectionBug() {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO;
}
/** * Check if OS version has built-in external cache dir method. * * @return */
public static boolean hasExternalCacheDir() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
}
/** * Check if ActionBar is available. * * @return */
public static boolean hasActionBar() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
}
第三步 二次封装Volley
1:接口回调监听
package com.longyue.volley;
import com.android.volley.Response;
import com.android.volley.VolleyError;
/** * 抽象出 成功的监听和失败的监听 * 用来回调信息 * @author yuan * * @param <T> */
public abstract class VolleyHandler<T> {
public Response.Listener<T> reqLis;
public Response.ErrorListener reqErr;
public VolleyHandler() {
// 初始化 变量
reqLis = new reqListener();
reqErr = new reqErrorListener();
}
public abstract void reqSuccess(T response);
public abstract void reqError(String error);
/** * 成功后的监听 * * @author yuan * */
public class reqListener implements Response.Listener<T> {
@Override
public void onResponse(T response) {
// 使用抽象函数 设置 回调函数 reqSuccess
reqSuccess(response);
}
}
/** * 失败后的监听 * * @author yuan * */
public class reqErrorListener implements Response.ErrorListener {
@Override
public void onErrorResponse(VolleyError error) {
// 设置回调函数 使用 抽象方法 ReqError
reqError(error.getMessage());
}
}
}
2 封装 文件上传请求队列
package com.longyue.volley;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
public class MultipartRequest extends Request<String> {
private MultipartEntity entity = new MultipartEntity();
private final Response.Listener<String> mListener;
private List<File> mFileParts;
private String mFilePartName;
private Map<String, String> mParams;
/** * 单个文件 * @param url * @param errorListener * @param listener * @param filePartName * @param file * @param params */
public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, String filePartName, File file,
Map<String, String> params) {
super(Method.POST, url, errorListener);
mFileParts = new ArrayList<File>();
if (file != null) {
mFileParts.add(file);
}
mFilePartName = filePartName;
mListener = listener;
mParams = params;
buildMultipartEntity();
}
/** * 多个文件,对应一个key * @param url * @param errorListener * @param listener * @param filePartName * @param files * @param params */
public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, String filePartName,
List<File> files, Map<String, String> params) {
super(Method.POST, url, errorListener);
mFilePartName = filePartName;
mListener = listener;
mFileParts = files;
mParams = params;
buildMultipartEntity();
}
private void buildMultipartEntity() {
if (mFileParts != null && mFileParts.size() > 0) {
for (File file : mFileParts) {
entity.addPart(mFilePartName, new FileBody(file));
}
}
try {
if (mParams != null && mParams.size() > 0) {
for (Map.Entry<String, String> entry : mParams.entrySet()) {
entity.addPart(
entry.getKey(),
new StringBody(entry.getValue(), Charset
.forName("UTF-8")));
}
}
} catch (UnsupportedEncodingException e) {
VolleyLog.e("UnsupportedEncodingException");
}
}
@Override
public String getBodyContentType() {
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
entity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
if (VolleyLog.DEBUG) {
if (response.headers != null) {
for (Map.Entry<String, String> entry : response.headers
.entrySet()) {
VolleyLog.d(entry.getKey() + "=" + entry.getValue());
}
}
}
String parsed;
try {
parsed = new String(response.data,HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed,
HttpHeaderParser.parseCacheHeaders(response));
}
/* * (non-Javadoc) * * @see com.android.volley.Request#getHeaders() */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
VolleyLog.d("getHeaders");
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
return headers;
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
}
3 请求方法封装
package com.longyue.volley;
import java.io.File;
import java.util.Map;
import org.json.JSONObject;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.longyue.customvolley2.VolleyApplication;
/** * @author xuenan * */
public class VolleyHttpRequest{
/** 1. * StringRequest GET方式 * @param url 地址 * @param volleyRequest 回调函数 */
public static void String_request(String url,VolleyHandler<String> volleyRequest){
Volley_StringRequest(Method.GET, url,null, volleyRequest);
}
/** 1. * StringRequset POST方式 * @param url 地址 * @param map 参数 * @param volleyRequest 回调函数 */
public static void String_request(String url,final Map<String,String> map,VolleyHandler<String> volleyRequest){
Volley_StringRequest(Method.POST,url,map,volleyRequest);
}
/**Volley_UploadImage_Request POST方式 * @param url 地址 * @param params 请求参数 * @param volleyRequest 回调函数 * @param fileName 文件名 * @param file 要上传的文件 */
public static void File_Upload_request(String url,final Map<String,String> params,VolleyHandler<String> volleyRequest,String fileName,File file){
Volley_UploadImage_Request(url, params, volleyRequest, fileName, file);
}
/**1. * 封装 StringRequest 数据请求 * @param method 方式 * @param url 地址 * @param params 参数 * @param volleyRequest 回调对象 */
private static void Volley_StringRequest(int method,String url,final Map<String,String> params,VolleyHandler<String> volleyRequest){
StringRequest stringrequest=new StringRequest(method, url,volleyRequest.reqLis,volleyRequest.reqErr){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
};
stringrequest.setTag("stringrequest");
VolleyApplication.getQueue().add(stringrequest);
}
/**2封装MultipartRequest 数据请求 上传图片 * @param url * @param params 参数 * @param volleyRequest 回调函数 * @param fileName 文件名 * @param file 文件 */
private static void Volley_UploadImage_Request(String url,final Map<String,String> params,VolleyHandler<String> volleyRequest,String fileName,File file){
MultipartRequest imageRequest=new MultipartRequest(url, volleyRequest.reqErr,volleyRequest.reqLis,fileName, file, params);
imageRequest.setTag("imageRequest");
VolleyApplication.getQueue().add(imageRequest);
}
/**2. * JsonObjectRequest GET 请求 * @param url 请求地址 * @param volleyRequest 回调函数对象 */
public static void JsonObject_Request(String url,VolleyHandler<JSONObject> volleyRequest){
Volley_JsonObjectRequest(Method.GET,url,null,volleyRequest);
}
/**2 * JsonObjectRequest POST 请求 * @param url 请求地址 * @param jsonObject 请求参数 * @param volleyRequest 回调函数对象 */
public static void JsonObject_Request(String url,JSONObject jsonObject,VolleyHandler<JSONObject> volleyRequest){
Volley_JsonObjectRequest(Method.POST,url,jsonObject,volleyRequest);
}
/**2. * 封装 JsonObjectRequest 请求方法 * @param method 方式 * @param url 地址 * @param jsonObject 参数 * @param volleyRequest 回调函数对象 */
private static void Volley_JsonObjectRequest(int method,String url,JSONObject jsonObject,VolleyHandler<JSONObject> volleyRequest){
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(method,url,jsonObject,volleyRequest.reqLis,volleyRequest.reqErr);
jsonObjectRequest.setTag("jsonObjectRequest");
VolleyApplication.getQueue().add(jsonObjectRequest);
}
/**3. * ImageRequest 默认大小 原图不变 * @param url 地址 * @param volleyRequest 回调函数 */
public static void Image_request(String url,VolleyHandler<Bitmap> volleyRequest){
Volley_ImageRequest(url, 0, 0, volleyRequest);
}
/**3. * ImageRequest 自定义的缩放 * @param url 地址 * @param maxWidth 最大宽度 * @param maxHeight 最大高度 * @param volleyRequest 回调函数 */
public static void Image_request(String url,int maxWidth,int maxHeight,VolleyHandler<Bitmap> volleyRequest){
Volley_ImageRequest(url, maxWidth, maxHeight, volleyRequest);
}
/**3. * 封装 ImageRequest 请求方法 * @param url 地址 * @param maxWidth 最大宽度 * @param maxHeight 最大高度 * @param volleyRequest 回调函数对象 */
private static void Volley_ImageRequest(String url,int maxWidth,int maxHeight,VolleyHandler<Bitmap> volleyRequest){
ImageRequest imageRequest=new ImageRequest(url,volleyRequest.reqLis, maxWidth, maxHeight,Config.RGB_565,volleyRequest.reqErr);
imageRequest.setTag("imageRequest");
VolleyApplication.getQueue().add(imageRequest);
}
/** * 4. * 自定义图片的宽度值 * @param url * @param imageListener * @param maxWidth * @param maxHidth */
public static void Image_Loader(String url,ImageListener imageListener,int maxWidth,int maxHidth){
Volley_ImageLoader(url, imageListener, maxWidth, maxHidth);
}
/** 4. * 默认值,原始比例 * @param url 地址 * @param imageListener 图片监听 */
public static void Image_Loader(String url,ImageListener imageListener){
Volley_ImageLoader(url,imageListener,0,0);
}
/** 4. * 封装 ImageLoader 方法 * @param url 地址 * @param imageListener 图片监听 * @param maxWidth * @param maxHidth */
private static void Volley_ImageLoader(String url,ImageListener imageListener,int maxWidth,int maxHidth){
// 设置 图片缓存 :体现 imageLoader的优势
// 使用 LruBitmap + ImageCache 实现
// 实例化对象
ImageLoader imageLoader = new ImageLoader(VolleyApplication.getQueue(),
VolleyBitmapCache.getInstance());
// 加载图片 图片监听 (默认图片,错误图片) 和 imageView
imageLoader.get(url, imageListener,maxWidth,maxHidth);
}
}
完成了这些 ,就可以愉快的享受编程的魅力了
Demo下载