单例类。
public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private VolleySingleton() {
mRequestQueue = getRequestQueue();
}
public static synchronized VolleySingleton getInstance() {
if (mInstance == null) {
mInstance = new VolleySingleton();
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(UpApplication.getInstance().getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
添加请求。
public class UpRequests {
public static void getItemDetails(String path, String sort,int pageNum, final ItemCallback callback) {
//TODO: find a way to integrate pageNum parameter into the query parameters of the request
// whenever pagination is supported
Uri.Builder uriBuilder = new Uri.Builder()
.scheme("http").authority("materialup.com")
.appendPath("posts")
.appendPath("c")
.appendPath(path)
.appendQueryParameter("page",String.valueOf(pageNum));
if (!StringUtils.isEmpty(sort)) {
uriBuilder.appendQueryParameter("sort", sort);
Log.e("url---->",uriBuilder.toString());
}
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.GET, uriBuilder.toString(),
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
ItemResponse itemsResponse = ParseUtils.parseItems(response);
callback.onItemSuccess(itemsResponse);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
callback.onItemError(new ItemException(UpApplication.getInstance().getString(R.string.error_connection)));
}
});
VolleySingleton.getInstance().addToRequestQueue(stringRequest);
}
}