对Volley进行封装
public class VolleyManager {
/**
* 请求队列
*/
private static RequestQueue mRequestQueue;
/**
* 图片加载工具类
*/
private static ImageLoader mImageLoader;
private VolleyManager() {
}
/**
* 使用Volley请求网络和图片是首先调用该方法
* 建议在Application 的onCreater中调用
* @param context
*/
public static void init(Context context) {
mRequestQueue = Volley.newRequestQueue(context);
int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
.getMemoryClass();
int cacheSize = 1024 * 1024 * memClass / 8;
mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(cacheSize));
}
/**
* 得到消息队列
* @return
*/
public static RequestQueue getRequestQueue() {
if (mRequestQueue != null) {
return mRequestQueue;
} else {
throw new IllegalStateException("RequestQueue not initialized");
}
}
/**
* 把请求添加到队列中
* @param request
* @param tag
*/
public static void addRequest(Request<?> request, Object tag) {
if (tag != null) {
request.setTag(tag);
}
mRequestQueue.add(request);
}
/**
* 请求的取消
* @param tag
*/
public static void cancelAll(Object tag) {
mRequestQueue.cancelAll(tag);
}
/**
* Returns instance of ImageLoader initialized with {@see FakeImageCache}
* which effectively means that no memory caching is used. This is useful
* for images that you know that will be show only once.
*
* @return
*/
public static ImageLoader getImageLoader() {
if (mImageLoader != null) {
return mImageLoader;
} else {
throw new IllegalStateException("ImageLoader not initialized");
}
}
}
使用Volley
private void getDataFromNetByVolley() {
StringRequest request = new StringRequest(Request.Method.GET, Constants.PHOTOSDETAIL_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String result) {
processData(result);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
LogUtil.e("volley新闻中心联网失败=" + volleyError.getMessage());
}
}){
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
String parsed=new String(response.data,"UTF-8");
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return super.parseNetworkResponse(response);
}
};
VolleyManager.addRequest(request,"PhotoDetail");
}
在Application中初始化volley
public class BeijingNewsApplication extends Application{
@Override
public void onCreate() {
super.onCreate();
x.Ext.init(this);
x.Ext.setDebug(true);
VolleyManager.init(this);
ShareSDK.initSDK(this);
}
}