PS: at the same time you see this topic, you will think, volley and glide how to get a piece to say, although they are not a framework, but have the same function, that is the picture processing. First we look at what volley, and what is glide.
volley is Google's official set of small and ingenious asynchronous request library, the framework package is very extensible, support Okhttp,volley inside also encapsulated Imageloader, itself as a picture loading framework, However, this feature does not have some special picture loading framework is powerful, for the simple requirements can be used, for a slightly more complex point of demand or need to use a special picture loading framework. Volley also has flaws, such as not supporting post big data, so it is not suitable for uploading files. However, the original intention of volley design itself is to frequent, small data volume of the network request to live!
Personal advice:
If the requested data is relatively small, it is recommended to use volley, because it has a small amount of code, the effect is high, but if you are downloading large files (video), then do not use it.
GlideIs the Google recommended image loading library, it can support from ur, files, support the loading of GIF images, as well as various pictures before the display of bitmap processing (such as: Fillet picture, circular picture, Gaussian blur, rotation, grayscale, etc.), cache processing, request priority processing, animation processing, thumbnail processing, Picture size customization and so on. They are all Google, then why out of the volley also want out of glide, in fact, they just have intersection, not two choose one, but complementary. We want to understand them, we must first learn how to use them, the following is written about volley. The following are divided into small sections. First of all, the introduction of volley three methods in Androidstudio
1:stringrequest
Warm up first, pass in a Baidu link, return some data.
1.1 Simply request a network address and return data to create a queue
Requestqueue queue=volley.newrequestqueue (context);
1.2 Create the stringrequest where needed (parameters: )
- Get/post
- URL address
- Response Monitoring
- Error monitoring
String url = "Http://www.baidu.com"; Stringrequest request = new Stringrequest (Request.Method.GET,url,new Response.listener <String> () {@Overridepublic void Onresponse (String response) {
result = Securitutil.aesbase64decode (response); }
,new Errorlistener
public void Onerrorresponse (Volleyerror error) {
} }});
1.3 Final processing to join in the queue
Queue.add (Request);
I go, this can be, I am nervous, remember before with Httpconnect time, write really is more, also want to configure a lot of things, even retrofit have to write annotations or something. Retrofit I have some previous articles, not how to use the comrades can go to see. Well, the data is out, I do not, we understand that this is not a simple biography, but if you want to pass the value of it, then the Post method Bai.
2:post with parameter request
Before creating the Stringrequest method, let's take a look at the source method, 4 parameters.
/*** Creates a new request with the given method. * * @parammethod The request {@linkMethod} to use *@paramURL URL to fetch the string at *@paramListener listener to receive the String response *@paramErrorlistener Error Listener, or null to ignore errors*/ PublicStringrequest (intmethod, String URL, listener<string>Listener, Errorlistener Errorlistener) { Super(method, URL, errorlistener); Mlistener=Listener; }2.1: Still the same write create a stringrequest, look at the notes
Stringrequest request =NewStringrequest (Request.Method.POST, URL,NewResponse.listener<string>() {@Override Public voidOnresponse (String response) {//succeeded}},NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {//Failed}}) {//value method write location @OverrideprotectedMap<string, string> getparams ()throwsAuthfailureerror {HashMap<string, string> map =NewHashmap<>(); Map.put ("Name", "Liu"); Map.put ("id", "123456789"); returnmap; } };
It is important to note that the Getparams () method is written in Stringrequest (inside), and the parentheses are marked red. 2.2 Finally put the object in the queue
Queue.add (Request);
This is done, the value of the direct write on the OK, are key-value pairs of the form. To this estimate some people think this is a common value, if I pass the JSON, there is, there is.
3:json format parameters and accept data
This JSON value is also divided into the Get and Psot method, get is not generally transmitted value, directly fill in "". Post is a special class jsonobjectrequest, if you don't feel like it can also be used
Jsonarrayrequest. The usual is to look at the source code first
/*** Creates a new request. * @parammethod The HTTP method to use *@paramURL URL to fetch the JSON from *@paramrequestbody A {@linkString} to post with the request. Null is allowed and * indicates no parameters would be a posted along with request. * @paramListener listener to receive the JSON response *@paramErrorlistener Error Listener, or null to ignore errors. */ PublicJsonobjectrequest (intmethod, string url, String requestbody, Listener<JSONObject>Listener, Errorlistener Errorlistener) { Super(method, URL, requestbody, Listener, Errorlistener); }
3.1: Request mode get, no parameters passed in
Jsonobjectrequest json=New jsonobjectrequest (Request.Method.GET, URL, "", new Response.listener<jsonobject>() { @Override publicvoid onresponse ( Jsonobject response) { } }, new Response.errorlistener () { @Override Public void onerrorresponse (volleyerror error) { } });
3.2: Request mode post
Jsonobject jsono=NewJsonobject (); Try{jsono.put ("Name", "" "); Jsono.put ("ID", "" "); } Catch(jsonexception e) {e.printstacktrace (); }//creating Jsonobject Objects Jsonobjectrequest JSON=Newjsonobjectrequest (Request.Method.POST, URL, Jsono,NewResponse.listener<jsonobject>() {@Override Public voidOnresponse (jsonobject response) {//ok}},NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {//error}});3.3: Finally put the object in the queue
Queue.add (Request);
Here volley how to use to access the network data is done, and has not yet said that his picture processing, but this framework is really good, so it is a bit more written. Let's take a look at his picture processing.
4:imagerequest, picture loadingSource: Image URL, Response callback interface, maximum picture width, maximum picture height, picture configuration RGB mode, error callback interface max picture width (height) If not write can write 0,
/*** Creates a new image request, decoding to a maximum specified width and * height. If both width and height are zero, the image is decoded to * its natural size. If one of the nonzero, that dimension would be * clamped and the other one would be set to preserve the image ' s a SPECT * ratio. If both width and height are nonzero, the image would be decoded to * is fit in the rectangle of dimensions width x hei Ght while keeping its * aspect ratio. * * @paramURL URL of the image *@paramListener listener to receive the decoded bitmap *@parammaxWidth Maximum width to decode the bitmap to, or zero for none *@parammaxheight Maximum height to decode the bitmap to, or zero for * none *@paramScaleType the imageviews scaletype used to calculate the needed image size. * @paramDecodeconfig Format to decode the bitmap to *@paramErrorlistener Error Listener, or null to ignore errors*/ PublicImagerequest (String URL, response.listener<bitmap> Listener,intMaxWidth,intMaxHeight, ScaleType scaletype, Config decodeconfig, Response.errorlistener Errorlistener) { Super(method.get, URL, errorlistener); Setretrypolicy (NewDefaultretrypolicy (Image_timeout_ms, Image_max_retries, Image_backoff_mult)); Mlistener=Listener; Mdecodeconfig=Decodeconfig; Mmaxwidth=MaxWidth; Mmaxheight=MaxHeight; Mscaletype=ScaleType; }
Usage: Each parameter is what I write on the above, the first few parameters is what, there are source for everyone to refer to. URL is a picture address
Imagerequest request =new imagerequest (url,response.listener<bitmap>() {@Override publicvoid onresponse (Bitmap s) { log.i ("AA", "POST request succeeded" + s); } },0,0,Bitmap.config.RGB_565,new Response.errorlistener () { @Override Public void onerrorresponse (Volleyerror volleyerror) {
LOG.I ("AA", "POST request Failed" + s);
});
5:imageloader picture caching mechanism (recommended)
In the normal version itself is called its own cache class, which we can not control, If you want to control the need to write their own class to implement Imageloader.imagecache, which is equivalent to our custom view, or custom adapter, we can better control the results we want, for example, we want it to cache the maximum amount is 10M, more than this value will be issued an alarm and so on.
Here's a simple usage
Imageloader Imageloader =NewImageloader (Requestqueue,NewImageloader.imagecache () {@Override PublicBitmap getbitmap (String url) {//specific operations, mainly for the size of the cache data, how to cache. return NULL; } @Override Public voidputbitmap (String URL, Bitmap Bitmap) {}});//Imgshow is a ImageView control. The following parameter classification is the picture that appears when the failure and procedure occurImageloader.imagelistener listener =Imageloader.getimagelistener (Imgshow, R.mipmap.ic_launcher, r.drawable.btn_add_true); Imageloader.get (URL, listener,200, 200);
The above can be processed on the image, but there is a definition interface, there are two methods, one is to take, the focus is red
Public classImagecacheImplementsimageloader.imagecache{//LruCache is a class that is dedicated to caching, string can be the name of the cache, and bitmap is a bitmap. Public LruCache<String,Bitmap>LruCache; Public intMAXCACHE=10 * 1024 *1024;//Maximum cache size 10M PublicImagecache () {LruCache=NewLrucache<>(MaxCache);//instantiation of Creation} @Override PublicBitmap getbitmap (String URL) {//Get bitmapreturnlrucache.get (URL); } @Override Public voidputbitmap (String URL, Bitmap Bitmap) {//Deposit bitmap Lrucache.put (URL,BITMAP); }}6:networkimageview Auto-fit picture (control)
netimg = (Networkimageview) Findviewbyid (r.id.id_net_img); Netimg.seterrorimageresid (r.mipmap.ic_launcher); // error after netimg.setdefaultimageresid (r.drawable.btn_add_true); // load in default // here New Imagecache () is the class Netimg.setimageurl (URL,new imageloader (queue,new Imagecache ( )));
To here volley basic usage is enough, originally wanted to write some glide usage, there is contrast, this article wrote a lot. We can digest the next article I write glide simple usage, then volley contrast glide.
Summary: Volley is a lightweight network request framework, if the requested data is relatively small, it is recommended to use volley, because it has a small code size, high effect, but if you are downloading large files (video), then do not use it.
But if there is a ListView, such as the GridView load picture, you can use volley, especially the last Networkimageview, can automatically adapt to the size of the picture, and then unified to determine exactly how big to better present to the user. Each frame is some people's efforts, is certainly the advantages of bursting, for programmers to tell a good tool for future development is how important, a function omitted some code, function more code is not honest and objective, and the introduction of norms. Thank you for your support.
Android Frame Volley and Glide