1.1 introduction of Volley
Volley is a Google I/O 2013 released a network framework based on the Android platform, its advantages are: 1) default Android2.3 and above based on HttpURLConnection,2.3 and below based on HttpClient; 2) Two cache mechanisms are provided: disk cache and memory cache, which conforms to the semantics of Http cache. 3) Support to specify the priority of requests; 4) Provide various cancellation mechanisms: specific task cancellation and multi-task cancellation; 5) Provide simple image loading tools (ImageRequest, ImageLoader); 6) An excellent framework.Disadvantages: Volley only applies to network operations with small data volume and frequent communication. If the data volume is large, such as audio and video transmission, it is better not to use Volley. The diagram below shows the official Velloy network framework, which is suitable for scenarios with small but frequent data volumes.
1.2 access to Volley
1) can be directly from the git clone down on Google: git clone android.googlesource.com/platform/fr… Then use the android update project -p. Ant jar command to generate a volley. jar package and add it directly to the project.
2) Or download the source code from github github.com/Fox-Legend/…
1.3 use Volley
Volley builds many tool network request tool classes, such as StringRequest, JsonArrayRequest, JsonObjectRequest, ImageRequest, etc., which are commonly used network requests. Volley provides a request queue, which is used to store users’ network requests. All requests are added to this queue and then issued concurrently according to certain algorithms. Generally, the network request queue is a global object used throughout the APP, so it is best to write to the Application,
Public class AppApplication extends Application {private static RequestQueue mQueue; public void onCreate() { super.onCreate(); this.mQueue = Volley.newRequestQueue(getApplicationContext()); } public static RequestQueue getRequestQueue(){ return mQueue; }}Copy the code
The RequestQueue start method is already called in the constructor that creates the RequestQueue queue object. The corresponding need to modify the androidmanifest.xml file, yes App corresponding Application object is AppApplication. Don’t forget to add network access:
android:name=".AppApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
Copy the code
(1) Create a JsonArrayRequest to send an Http request, add it to the RequestQueue, and return Json data:
private static final String TAG = "MainActivity"; Private final String mUrl = "http://10.8.204.173:5000/shouye/newdata/1"; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); VolleyGet(); } * Network request mode is Get, Return Json */ private void VolleyGet() {* Establish JsonArrayRequest request */ JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET,mUrl,null, new Response.Listener() { public void onResponse(JSONArray response) { Toast.makeText(MainActivity.this,"the response:" + response.toString(),Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { Log.e(TAG,error.toString()); }}); */ request.setTag("JSONArrayRequest_GET"); AppApplication.getRequestQueue().add(request); }Copy the code
Return Json data: The response: [{” star “:” 53 “, “date” : “06-18”, “title” : “hair picture long hair”,” Urls “:” http:\/\/t1.du114.com \ / uploads \ / tu \ \ 201606 / changfa250 \ / 2008111233241866 _2. JPG “]}] Method == request.method. POST (method== request.method. POST) params. The corresponding constructor argument list of JsonArrayRequest is:
*/ public JsonArrayRequest(String url, Listener listener, ErrorListener errorListener) { ... } * Creates a new request. * @param method * @param URL Url to fetch the JSON from: * @param jsonRequest A {@link JSONArray} to post with the request. Null is allowed and * Indicates no parameters Will be posted along with request * @param listener Listener to receive the JSON response: Listener * @param errorListener Error listener, or NULL to ignore errors: Public JsonArrayRequest(int method, String URL, JSONArray jsonRequest, Listener Listener, ErrorListener errorListener) { ... }Copy the code
Create a RequestQueue object. Create a JsonArrayRequest object; C. Add the JsonArrayRequest object to the RequestQueue.
Also provides other Request in the Volley, such as StringRequest/JsonObjectRequest etc, and can also custom Request. The use method is basically the same as above.
(2) In addition to some basic character data network requests,Volley can also load image data, there are two types of requests: ImageLoader and ImageRequest ImageRequest are used in the same way as the previous request, which is added to the RequestQueue after the object is created.
*/ Private void VolleyImageRequest(final ImageView ImageView) {int maxHeight = 480; int maxWidth = 640; String mPicUrl = "http://t1.du114.com/uploads/tu/201510/fengjing/rgj5thjkwlf.jpg"; ImageRequest imgRequest = new ImageRequest(mPicUrl, new Response.Listener() { public void onResponse(Bitmap response) { imageView.setImageBitmap(response); } }, maxWidth, maxHeight,ImageView.ScaleType.CENTER, Bitmap.Config.RGB_565, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { Log.e(TAG,error.toString()); }}); imgRequest.setTag("ImageRequest_TAG"); AppApplication.getRequestQueue().add(imgRequest); }Copy the code
As you can see, ImageRequest’s constructor takes seven arguments (the original six-argument method also ends up calling this method), the first of which is the URL of the image. The third and fourth parameters specify the maximum width and height of the image to be allowed. If the specified width or height of the network image is greater than this maximum, the image will be compressed. Specifying a value of 0 means that no matter how big the image is, it will not be compressed. The fifth parameter, ScaleType, specifies how to scale the image fill space, and the sixth parameter, specifies the image color attribute. Several constants in bitmap. Config are available here, including ARGB_8888, which shows the best color attribute. RGB_565 means that each image pixel occupies two bytes. The seventh parameter is the callback for the failed image request, where we can display a default image in the ImageView if the request fails. ImageLoader ImageLoader can also be used to load web images and is internally implemented using ImageRequest, but ImageLoader is more efficient than ImageRequest because it not only caches images but also filters out duplicate links to avoid duplicate requests.
@param mImgView */ private void VolletImageLoader(final ImageView mImgView) {int maxHeight = 480; int maxWidth = 640; String mPicUrl = "http://t1.du114.com/uploads/tu/201510/fengjing/rgj5thjkwlf.jpg"; ImageLoader imgLoader = new ImageLoader(AppApplication.getRequestQueue(),new BitmapCache()); ImageLoader.ImageListener listener = ImageLoader.getImageListener(mImgView,android.R.drawable.ic_menu_rotate,android.R.drawable.ic_delete); imgLoader.get(mPicUrl,listener,maxWidth,maxHeight); } * BitmapCache */ public class BitmapCache implements ImageLoader.ImageCache { private LruCache mCache; public BitmapCache(){ int maxSize = 10 * 1024 * 1024; mCache = new LruCache(maxSize){ protected int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight(); }}; } public Bitmap getBitmap(String url) { return mCache.get(url); } public void putBitmap(String url, Bitmap bitmap) { mCache.put(url,bitmap); }}Copy the code
As you can see, the ImageLoader constructor takes two arguments. The first argument is a RequestQueue object and the second argument is an ImageCache object. The getImageListener() method takes three parameters. The first parameter specifies the ImageView control used to display the image. The second parameter specifies the image to be displayed during the image loading process, and the third parameter specifies the image to be displayed if the image loading fails. Finally, the get() method of ImageLoader is called to load the image.
Volley also provides the NetworkImageView control (inherited from ImageView) specifically for loading network images, which encapsulates the above separate ImageView Settings for loading images and failed images.
private void VolleyImageLoader(NetworkImageView mNetworkView) {
String mPicUrl = "http://t1.du114.com/uploads/tu/201510/fengjing/rgj5thjkwlf.jpg";
ImageLoader imgLoader = new ImageLoader(AppApplication.getRequestQueue(),new BitmapCache());
this.mNetworkView.setDefaultImageResId(android.R.drawable.ic_menu_rotate);
this.mNetworkView.setErrorImageResId(android.R.drawable.ic_delete);
this.mNetworkView.setImageUrl(mPicUrl,imgLoader);
}
Copy the code
1.4 Customizing Request
Volley allows users to define specific requests as they wish, so how does that work? All requests in Volley inherit from the abstract Request class: StringRequest:
* A canned request for retrieving the response body at a given URL as a String. */ public class StringRequest extends Request { private Listener mListener; public StringRequest(int method, String url, Listener listener, ErrorListener errorListener) { super(method, url, errorListener); mListener = listener; } protected void onFinish() { super.onFinish(); mListener = null; } protected void deliverResponse(String response) { if (mListener ! = null) { mListener.onResponse(response); }} */ protected Response parseNetworkResponse(NetworkResponse Response) {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)); }}Copy the code
If we want to customize an XmlRequest for an XML file, we use XmlPullParserFactory and XmlPullParser to parse the returned XML data:
/** * XmlRequest */ public class XmlRequest extends Request { private final Response.Listener mListener; public XmlRequest(int method, String url, Response.Listener listener, Response.ErrorListener errorListener) { super(method, url, errorListener); mListener = listener; } public XmlRequest(String url, Response.Listener listener, Response.ErrorListener errorListener) { this(Method.GET, url, listener, errorListener); } @Override protected Response parseNetworkResponse(NetworkResponse response) { try { String xmlString = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xmlPullParser = factory.newPullParser(); xmlPullParser.setInput(new StringReader(xmlString)); return Response.success(xmlPullParser, HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (XmlPullParserException e) { return Response.error(new ParseError(e)); } } @Override protected void deliverResponse(XmlPullParser response) { mListener.onResponse(response); }}Copy the code
XmlRequest is used in much the same way as Volley’s built-in Request.
1.4 Canceling a Request Request
When the Activity is destroyed, you may need to cancel requests based on the Tag that was added to the Request when it was created. Fill in the onDestroy() method with the following code:
*/ request.setTag("JSONArrayRequest_GET"); @Override protected void onDestroy() { super.onDestroy(); AppApplication.getRequestQueue().cancelAll("JSONArrayRequest_GET"); }Copy the code
Or if you want to cancel all requests that belong to the Activity, you can add the same Tag to all requests that belong to the Activity. There is another way to override RequestQueue#cancelAll, which can pass in a RequestFilter and specify a filtering policy of its own.