Analysis of Volley network request Framework--android Network request Framework (III)

Source: Internet
Author: User


Preface--

People come to this world, there are only two things, life and death,

One thing is over, what's the other thing?

Destined to come, not to go,

Know from the heart, see from the Nature

Do not have a false edge, unintentional inaction

Freedom, movement, freedom.

Lengnuanzizhi, it is the practice






1. Initialize a message request queue and the network Request tool class object


/** * Created by androidlongs on 16/7/1. * Network Request Access Framework */public class Vollyrequestutils {/** * Volley framework using tool class object */private static vollyrequestutils Voll    Yrequestutils;    /** * Network message request queue */private static requestqueue requestqueue;    Private Vollyrequestutils () {/** * Initialize request message Queue */Getvolleyqueyinstanse (); }/** * Get Message Tool class Request Object Entity * * @return */public static vollyrequestutils getinstance () {if (voll  Yrequestutils = = null) {synchronized (Vollyrequestutils.class) {if (vollyrequestutils = = null)                {vollyrequestutils = new vollyrequestutils ();    }}} return vollyrequestutils; /** * Get message request queue */public void Getvolleyqueyinstanse () {if (Requestqueue = = null) {Sync Hronized (Vollyrequestutils.class) {if (Requestqueue = = null) {Requestqueue = VOLLEY.N EwrequesTqueue (App.getcontext ()); }            }        }    }}


Remark Description:

In this case, a singleton design pattern, where the request message Queue Requestqueue is passed in is a Application object

public class App extends application {    Private  static context context;    @Override public    void OnCreate () {        super.oncreate ();        context = this;    }    public static  Context GetContext () {        return context;    }}

Remember to introduce in the program's manifest file


2. Get network Request returns string

    /** *     GET request     *     * @param url           network request URL     * @param nettag        network request ID     * @param iscache       Set Cache identity     * @param listener      Request Success Callback     * @param errorlistener request failed callback     *    /public void Asygetstringrequest ( String URL, String Nettag, Boolean iscache, response.listener<string> Listener, Response.errorlistener Errorlistener) {        /**         * Cancels the network that has this label in the queue before initiating the request, avoiding multiple duplicate request problems         *        /Requestqueue.cancelall (Nettag);        /**         * Gets the Request object         * and sets the relevant listener *        /stringrequest request = new Stringrequest (Request.Method.GET, URL, Listener, Errorlistener);        /**         * Set network request ID         *        /Request.settag (Nettag);        /**         * Set Network request Cache         *        /Request.setshouldcache (Iscache);        /**         * Added to the queue         *        /Requestqueue.add (request);    }

How to use:

        Final String url = "Http://172.19.1.45:8080/OkhttpAppLication/test";        Final String Nettag = "getString";                Vollyrequestutils.getinstance (). Asygetstringrequest (URL, Nettag, False, new response.listener<string> () {            @Override public            void Onresponse (string s) {                System.out.println ("Get String Success" + s);            }        , New Response.errorlistener () {            @Override public            void Onerrorresponse (Volleyerror volleyerror) {                System.out.println ("Get String onerrorresponse" + volleyerror.getmessage ());            }        );


3. The POST request submission Parameter form Key-value form request


    /** * POST request submit data in key-valeu form * * @param URL * @param nettag * @param map * @param iscache * @param listener * @param errorlistener */public void asyncpoststringquest (string url, string Nettag, fin Al Map<string, String> Map, Boolean iscache, response.listener<string> Listener, Response.errorlistener        Errorlistener) {/** * Cancels all network requests under this identity, avoiding duplicate submissions */Requestqueue.cancelall (Nettag); /** * Gets the request object and encapsulates the corresponding parameter */stringrequest request = new Stringrequest (Request.Method.POST, URL, l Istener, Errorlistener) {@Override protected map<string, string> Getparams () throws Authfailu Reerror {/** * Package request parameter */if (map! = null &&!map.is                Empty ()) {return map;                } else {return super.getparams ();        }            }        };/** * Set Cache */Request.setshouldcache (Iscache);        /** * Set Network Request ID */Request.settag (Nettag);    Requestqueue.add (Request); }
How to use:

        Final String url = "Http://172.19.1.45:8080/OkhttpAppLication/test";        Final String Nettag = "poststring";                map<string, string> map = new hashmap<> ();        Map.put ("username", "postusername");        Map.put ("Password", "Postpassword");                Vollyrequestutils.getinstance (). Asyncpoststringquest (URL, Nettag, map, False, new response.listener<string> () {            @Override public            void Onresponse (string s) {                System.out.println ("Post String Success" + s);            }        } , new Response.errorlistener () {            @Override public            void Onerrorresponse (Volleyerror volleyerror) {                System.out.println ("Post String onerrorresponse" + volleyerror.getmessage ());            }        );}    

4. The POST request submission parameter is in JSON form
    /** * Submit JSON data to server * * @param URL network request URL * @param nettag network Request ID * @param map    Network Request Submission Parameters * @param iscache cache Request ID * @param listener successfully monitored * @param errorlistener failed to monitor * * public void asynepostjsonobjrequest (string url, String nettag, Final map<string, String> Map, Boolean iscache, Re Sponse.        Listener<jsonobject> Listener, Response.errorlistener errorlistener) {requestqueue.cancelall (NETTAG);        /** * Package Parameters */Jsonobject object = new Jsonobject (); try {if (map! = null &&!map.isempty ()) {for (map.entry<string, string> Entry:                Map.entryset ()) {Object.put (Entry.getkey (), Entry.getvalue ());        }}} catch (Exception e) {e.printstacktrace (); }/** * Create requests Request */jsonobjectrequest jsonobjectrequest = new Jsonobjectrequest (RequEst.        Method.post, URL, object, Listener, Errorlistener);        /** * Set Network Request ID */Jsonobjectrequest.settag (Nettag);        /** * Set Cache */Jsonobjectrequest.setshouldcache (Iscache);    Requestqueue.add (jsonobjectrequest); }

How to use:

        Final String url = "Http://172.19.1.45:8080/OkhttpAppLication/test";        Final String Nettag = "poststring";                map<string, string> map = new hashmap<> ();        Map.put ("username", "postusername---");        Map.put ("Password", "Postpassword---");                Vollyrequestutils.getinstance (). Asynepostjsonobjrequest (Url,nettag,map,false,new Response.Listener< Jsonobject> () {            @Override public            void Onresponse (Jsonobject jsonobject) {                Jsonobject j = jsonobject;            }        },new Response.errorlistener () {            @Override public            void Onerrorresponse (Volleyerror volleyerror) {            }        });



5. Loading picture Request

 /** * Load Picture request * @param url to load picture URL * @param nettag load image network Request ID * @param imagemaxwidth     Load the maximum width of the picture * @param imagemaxheight load the maximum height of the picture * @param listener load successfully monitoring * @param errorlistener Load Failure monitoring */public void asypostimagerequest (string url, string nettag, int imagemaxwidth, int imagemaxheight, Response.listener        <Bitmap> Listener, Response.errorlistener errorlistener) {requestqueue.cancelall (Nettag); /** * Create GET request * and set related listening and parameters */imagerequest request = new Imagerequest (URL, listener, I        Magemaxwidth, Imagemaxheight, ImageView.ScaleType.MATRIX, Bitmap.Config.ARGB_8888, Errorlistener);        /** * Set Load Cache */Request.setshouldcache (TRUE);        /** * Set Network Request ID */Request.settag (Nettag);        /** * Set Request Timeout time */request.setretrypolicy (new Defaultretrypolicy (15000,3000,3000));    Requestqueue.add (Request); }


How to use

Final String url = "Http://e.hiphotos.baidu.com/image/pic/item/14ce36d3d539b600be63e95eed50352ac75cb7ae.jpg";        Final String Nettag = "Imagerequest";                Vollyrequestutils.getinstance (). Asypostimagerequest (URL, Nettag, SCREEWIDHT, Screeheight, new Response.Listener< Bitmap> () {            @Override public            void Onresponse (Bitmap Bitmap) {                System.out.println ("Image request Success ");                if (bitmap! = null) {                    imageview.setimagebitmap (bitmap);}}        , New Response.errorlistener () {            @ Override public            void Onerrorresponse (Volleyerror volleyerror) {                System.out.println ("Image request Faile");            }        });



6. Load images with volley built-in Imageloader


    /** * Load multiple pictures * * @param URL * @param imageView * @param imagemaxwidth * @param imagemaxheight */public void asyvolleyimageloaderrequest (String url, ImageView ImageView, int imagemaxwidth, int imagemaxheight)        {Imageloader imageloaderinstance = getimageloaderinstance ();        Getimagelistener (ImageView control object, default picture address, failed image address); Imageloader.imagelistener listener = Imageloader.getimagelistener (ImageView, Android. R.drawable.ic_menu_rotate, Android.        R.drawable.ic_delete); Get (image address, listener, wide, high); Automatically help you handle the picture of the wide height no longer afraid of the big picture of Oom imageloaderinstance.get (URL, Listener, imagemaxwidth, Imagemaxhei    Ght, ImageView.ScaleType.MATRIX);    } private static Imageloader Imageloader; /** * Get Imageloader Object * @return * */Private Imageloader getimageloaderinstance () {if (Imageloader                    = = null) {synchronized (Vollyrequestutils.class) {if (Imageloader = = null) { Imageloader = new ImAgeloader (Requestqueue, New Bitmaplrucache ());    }}} return imageloader; }

How to use

        Final String url = "Http://e.hiphotos.baidu.com/image/pic/item/14ce36d3d539b600be63e95eed50352ac75cb7ae.jpg";        Final String Nettag = "poststring";                Vollyrequestutils.getinstance (). Asyvolleyimageloaderrequest (URL, ImageView, SCREEWIDHT, screeheight);

A cache object class is used here

public class Bitmaplrucache extends Lrucache<string, bitmap> implements Imageloader.imagecache {/** * Lruca      Che principle: The cache holds a strong reference to limit the amount of content, and the item is moved to the head of the queue whenever the item is accessed.     * When a new item is added when the cache is full, item at the end of the queue is recycled. * Explanation: Remove the least recently used image memory when exceeding the specified memory value */public static int getdefaultlrucachesize () {//Get maximum memory final int MaxMem        Ory = (int) (Runtime.getruntime (). MaxMemory ()/1024);        Get one-eighth of the memory to do the picture memory cache final int cacheSize = MAXMEMORY/8;    return cacheSize;    } public Bitmaplrucache () {This (getdefaultlrucachesize ());    } public Bitmaplrucache (int sizeinkilobytes) {super (sizeinkilobytes);  } @Override protected int sizeOf (String key, Bitmap value) {return value.getrowbytes () * Value.getheight ()/    1024;    } @Override Public Bitmap getbitmap (String URL) {return get (URL);    } @Override public void Putbitmap (String url, Bitmap Bitmap) {put (URL, Bitmap); }}


7. Load images with networkimageview provided by Volley


How to use XML in Layout files

<com.android.volley.toolbox.networkimageview        android:layout_margintop= "10DP"        android:id= "@+id/ Network_image_view "        android:layout_width=" 100DP "        android:layout_height=" 100DP "/>    

Operations in Java code

/**     * This control automatically cancels the network request when it is detach from the parent control, that is, without worrying about the lifecycle of the associated network request. And Networkimageview will automatically compress the image according to the width and heigh you set for the picture will not produce much memory, and Networkimageview in the list will not use the picture error     *     @param IV     * @param URL     *    /private void Networkimageviewuse (Networkimageview IV, String URL) {        imageloader Imloader = new Imageloader (Volley.newrequestqueue (App.getcontext ()), New Bitmaplrucache ());        Iv.setdefaultimageresid (Android. R.drawable.ic_menu_rotate);        Iv.seterrorimageresid (Android. R.drawable.ic_delete);        Iv.setimageurl (URL, imloader);    }


8. Custom Request Requests




Analysis of Volley network request Framework--android Network request Framework (III)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.