Android Volley·ÖÎö£¨¶þ£©¡ª¡ªÊµÏÖ

來源:互聯網
上載者:User

Android Volley·ÖÎö£¨¶þ£¡ª¡ªÊµÏÖ

ÔÚAndroid Volley·ÖÎö£¨Ò»£¡ª¡ª½á¹¹ÖÐÖ÷Òª·ÖÎöÁËVolleyµÄ»ù±¾×é¼þºÍ¿ò¼Ü½á¹¹£¬×é¼þÖ÷ÒªÊǶ¨ÒåµÄ½Ó¿Ú£¬Ò²¾ÍÊÇ˵ÎÒÃÇ¿ÉÒÔʵÏÖÕâнӿÚÀ´¶¨ÖÆ×Ô¼ºµÄVolley°æ±¾£¬±ÈÈçNetWork¡¢Cache¡¢RequestµÈµÈ¡£Android VolleyÔÚcom.android.volley.toolboxÏÂÒѾ×öÁËÕâй¤×÷£¬ÏÂÃæ¾Í¿´¿´ÕâоßÌåµÄʵÏÖÄÚÈÝ


ÏÈ¿´Ò»¸öVolleyʹÓõÄÀý×Ó<†·Ÿ"http://www.bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+PC9wPgo8cHJlIGNsYXNzPQ=="brush:java;">final TextView mTextView = (TextView) findViewById(R.id.text);...// Instantiate the RequestQueue.RequestQueue queue = Volley.newRequestQueue(this);String url ="http://www.google.com";// Request a string response from the provided URL.StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener() { @Override public void onResponse(String response) { // Display the first 500 characters of the response string. mTextView.setText("Response is: "+ response.substring(0,500)); }}, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mTextView.setText("That didn't work!"); }});// Add the request to the RequestQueue.queue.add(stringRequest);
ÕâÊǹٷ½volley½Ì³ÌµÄÒ»¸öÀý×Ó£¬Ê¹ÓÃVolleyµÄ²½Öè

1¡¢Volley.newRequestQueue();

2¡¢new Request();

3¡¢queue.add(request);

ÔÚnewRequestQueueµÄʱºò»á³õʼ»¯»ù±¾µÄ×é¼þ

    public static RequestQueue newRequestQueue(Context context, HttpStack stack) {        File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);        String userAgent = "volley/0";        try {            String packageName = context.getPackageName();            PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);            userAgent = packageName + "/" + info.versionCode;        } catch (NameNotFoundException e) {        }        if (stack == null) {            if (Build.VERSION.SDK_INT >= 9) {                stack = new HurlStack();            } else {                // Prior to Gingerbread, HttpUrlConnection was unreliable.                // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html                stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));            }        }        Network network = new BasicNetwork(stack);        RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);        queue.start();        return queue;    }

1¡¢BasicNetwork

BasicNetworkÊǶÔNetwork½Ó¿ÚµÄʵÏÖ£¬Í¬Ê±»¹½«ÁªÍø²Ù×÷²¿·ÖÌáÈ¡³öÀ´ÐγÉHttpStack£¬ÔÒòÊÇAndroid 2.3ÖÇ°ÍøÂç²Ù×÷ÍÆ¼öʹÓÃHttpClient£¬2.3ÖºóAndroid×öÁËÓÅ»¯ÍƼöʹÓÃHttpUrlConnection¡£

2¡¢DiskBasedCache

DiskBasedCacheÊǶÔCache¶ÔʵÏÖ£¬ÓÃÓÚÓ²ÅÌ»º´æ£¬Ò²¾ÍÊǽ«Êý¾Ý±£´æÎªÌض¨µÄÎļþ¡£

½áºÏLruCacheÊÔ×Å×ܽáһϻº´æµÄÒ»°ã·½·¨£º

Ó³Éä½á¹¹¡ª¡ªLinkedHashMap£¬ÄÚ²¿ÊµÏÖÁËLruµÄËã·¨ÅÅÐò£¬¿ÉÒÔÖ±½ÓʹÓÃ

put¡ª¡ª´æ´¢£¬ÈÝÁ¿¼ÆÊýÔö¼Ó£¬ÅжÏÊÇ·ñ³¬³ö×î´óÈÝÁ¿£¬³¬³öÔòɾ³ý×îÉÙʹÓõÄ

get¡ª¡ªkeyµ½entryµÄÓ³Éä

remove¡ª¡ªÉ¾³ý£¬ÈÝÁ¿¼ÆÊý¼õС

3¡¢ImageLoader

ImageLoaderÊÇÒ»¸öͼƬ¼ÓÔØÀ࣬·â×°ÁËÇëÇó£¬Ìá¹ÁËÄڴ滺´æ»úÖÆ£¬Åú´¦ÀíµÈ£¬ÈÃͼƬ¼ÓÔØ¸üÈÝÒ×ʹÓã¬ÏÂÃæ¿´Ò»ÏÂËüµÄÓ÷¨£º

        mImageLoader = new ImageLoader(mRequestQueue,                new ImageLoader.ImageCache() {            private final LruCache                    cache = new LruCache(20);            @Override            public Bitmap getBitmap(String url) {                return cache.get(url);            }            @Override            public void putBitmap(String url, Bitmap bitmap) {                cache.put(url, bitmap);            }
mImageLoader.get(IMAGE_URL, ImageLoader.getImageListener(mImageView,         R.drawable.def_image, R.drawable.err_image));

£¨Ê¾ÀýÀ´Ô´ Making a Standard Request £

Äڴ滺´æÍƼöʹÓÃLruCache£¬ÐèҪʵÏÖImageLoader.ImageCache½Ó¿Ú¡£Í¼Æ¬µÄ¼ÓÔØÍ¨¹ýimageLoader.get()·½·¨ÊµÏÖ£¬

    public ImageContainer get(String requestUrl, ImageListener imageListener,            int maxWidth, int maxHeight) {        // only fulfill requests that were initiated from the main thread.        throwIfNotOnMainThread();        final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight);        // Try to look up the request in the cache of remote images.        Bitmap cachedBitmap = mCache.getBitmap(cacheKey);        if (cachedBitmap != null) {            // Return the cached bitmap.            ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null);            imageListener.onResponse(container, true);            return container;        }        // The bitmap did not exist in the cache, fetch it!        ImageContainer imageContainer =                new ImageContainer(null, requestUrl, cacheKey, imageListener);        // Update the caller to let them know that they should use the default bitmap.        imageListener.onResponse(imageContainer, true);        // Check to see if a request is already in-flight.        BatchedImageRequest request = mInFlightRequests.get(cacheKey);        if (request != null) {            // If it is, add this request to the list of listeners.            request.addContainer(imageContainer);            return imageContainer;        }        // The request is not already in flight. Send the new request to the network and        // track it.        Request newRequest =            new ImageRequest(requestUrl, new Listener() {                @Override                public void onResponse(Bitmap response) {                    onGetImageSuccess(cacheKey, response);                }            }, maxWidth, maxHeight,            Config.RGB_565, new ErrorListener() {                @Override                public void onErrorResponse(VolleyError error) {                    onGetImageError(cacheKey, error);                }            });        mRequestQueue.add(newRequest);        mInFlightRequests.put(cacheKey,                new BatchedImageRequest(newRequest, imageContainer));        return imageContainer;    }

Ê×Ïȵõ½Ò»¸öcacheKey£¬Õâ¸öÊÇͳһµÄ¹æÔò

    private static String getCacheKey(String url, int maxWidth, int maxHeight) {        return new StringBuilder(url.length() + 12).append("#W").append(maxWidth)                .append("#H").append(maxHeight).append(url).toString();    }

È»ºóÔÚ»º´æcacheÖвéÕÒ£¬Ã»ÕÒµ½¾Í½²ÇëÇóÌí¼Óµ½Åú´¦ÀíÈÎÎñBitmapImageRequestÖУ¬ÕâÀïÓÐÁ½¸öÀ࣬ImageContainerºÍBitmapImageRequest£º

ImageContainerÊÇÒ»¸ö°ü×°À࣬ÀïÃæ°üº¬ÁËbitmap¡¢url¡¢cacheKeyºÍlistener£¬µ±µÃµ½bitmapºó»áͨ¹ýlistener½«bitmap·µ»Ø£»

BitmapImageRequestÊǽ«ÏàͬurlÇëÇó·ÅÔÚÒ»Æð£¬ÕâÑù¾Í¿ÉÒÔÖ»ÏòÍøÂçÇëÇóÒ»´Î£¬·µ»Ø½á¹ûºóÔÙ·Ö±ðÉèÖõ½Ä¿±êÉÏ£¬´Ó¶ø´ïµ½¼õÉÙÍøÂçÇëÇó¶ÔÄ¿µÄ¡£


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.