1、建立自定义类
2、建立接口
将volley封装成一个工具,使用起来更加方便。
1、
建立自定义类:
VolleyRequest.java
public class VolleyRequest {
public static StringRequest stringRequest;
public static Context context;
public static void RequestGet(
Context mcontext,String url,String tag,VolleyInterface vif){
//防止重复请求,所以先取消tag标识的请求队列
MyApplication.getHttpQueues().cancelAll(tag);
stringRequest=new StringRequest(Method.GET, url,
vif.loadingListener(),
vif.errorListener()
);
stringRequest.setTag(tag);
MyApplication.getHttpQueues().add(stringRequest);
//注意千万不要调用start来开启。这样写是不对的。
//因为在源码里,当我们调用Volley.newRequestQueue()来实例化一个请求队列的时候
//就已经使用queue.start(); 方法来开启了一个工作线程,所以我们如果多次调用
//newRequestQueue来实例化请求队列就会多次调用start方法,这样做势必增加性能的消耗
//所以我们一定要把volley的请求队列全局化(可以使用单例模式或在application初始化)。
//并且我们不应当手动调用start。
// MyApplication.getHttpQueues().start();
}
public static void RequestPost(Context context,String url,String tag,final Map<String, String>params,
VolleyInterface vif){
MyApplication.getHttpQueues().cancelAll(tag);
stringRequest = new StringRequest(url, vif.loadingListener(), vif.errorListener()){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
};
stringRequest.setTag(tag);
MyApplication.getHttpQueues().add(stringRequest);
}
}
2、建立接口:
VolleyInterface.java
package com.example.volley;
import com.android.volley.VolleyError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import android.content.Context;
public abstract class VolleyInterface {
private Context mContext;
public static Listener<String> mListener;
public static ErrorListener mErrorListener;
public VolleyInterface(Context context, Listener<String> listener, ErrorListener errorListener) {
this.mContext = context;
this.mListener = listener;
this.mErrorListener = errorListener;
}
public abstract void onMySuccess(String result);
public abstract void onMyError(VolleyError error);
public Listener<String> loadingListener() {
mListener = new Listener<String>() {
@Override
public void onResponse(String response) {
onMySuccess(response);
}
};
return mListener;
}
public ErrorListener errorListener() {
mErrorListener = new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
onMyError(error);
}
};
return mErrorListener;
}
}
3、使用方法:
private void volley_Get() {
String url = "";
VolleyRequest.RequestGet(this, url, "124", new VolleyInterface(this, VolleyInterface.mListener, VolleyInterface.mErrorListener) {
@Override
public void onMySuccess(String result) {
Toast.makeText(VolleySecond.this, result, Toast.LENGTH_SHORT).show();
}
@Override
public void onMyError(VolleyError error) {
}
});
}