Understand that Volley listView of the android network library loads a large number of images,

Source: Internet
Author: User

Understand that Volley listView of the android network library loads a large number of images,

I. attach an image

 

Volley uses ImageRequest to retrieve images on the network. It specifies a URL and returns a bitmap with an encoded number. Of course, it also provides other convenient features, such as adjusting the image size. The main advantage of using volume is that Volley's scheduled thread ensures that expensive operations such as segment encoding and size adjustment are automatically completed in a worker thread, without causing too much trouble and interference to the main thread.

 

A cannedrequest for getting an image at a given URL and calling back with a decodedbitmap. it also provides convenience features like specifying a size to resizeto. its main benefit is that Volley's thread scheduling ensures that expensiveimage operations (decoding, resizing) automatically happen on a worker thread.


(1) initialize a request queue. It is best to write it in application (remember to modify application in manifest) so that it starts from the very beginning.

public class VolleyApplication extends Application {@Overridepublic void onCreate() { super.onCreate();RequestManager.initVolley(this);}}

Here, RequestManager is a custom request management class dedicated to managing requests. There is a request queue, which is then instantiated in the initialization method.

private static RequestQueue mRequestQueue;public RequestManager() {// TODO Auto-generated constructor stub} public static void initVolley(Context context){mRequestQueue = Volley.newRequestQueue(context);}

(2) then write the image request

//Retrieves an image specified by the URL, displays it in the UI. request = new ImageRequest(url, new Response.Listener<Bitmap>() {             @Override             public void onResponse(Bitmap response) {                     singleImageView.setImageBitmap(response);             }         }, 0, 0, null,    new Response.ErrorListener() {        public void onErrorResponse(VolleyError error) {            Toast.makeText(ImageActivity.this, "download image error", Toast.LENGTH_LONG).show();        }    })

(3) execute the image loading request:

RequestManager.addRequest(request);

(4) Add the network access permission to manifest.

 <uses-permission android:name="android.permission.INTERNET" />

When you click to download a large image, the following insufficient memory warning is immediately printed.


Therefore, you cannot repeat the previous operation multiple times after downloading multiple images. You must use ImageLoader. Second point


Ii. Download multiple images

By instantiating an ImageRequest, you can download an image. The problem is, what if there are multiple images? Are you sure you want to do this? As you can see, memory is insufficient for one piece, and OOM is inevitable for multiple pieces. Volley provides ImageLoader and NetworkImageView to download a large number of images, such as listview.

 

(1) Create a memory cache,AndroidProvides a memory cache class library,LruCacheNote that there is another class that provides LruCache, but what we need isAndroid. support. v4.util.LruCache

Create a class that inherits from the LruCache class and implement the ImageCache interface.

import android.graphics.Bitmap;import android.support.v4.util.LruCache;import com.android.volley.toolbox.ImageLoader;public class BitmapLruCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache{public BitmapLruCache(int maxSize) {super(maxSize);} @Overrideprotected int sizeOf(String key, Bitmap bitmap) {return bitmap.getRowBytes() * bitmap.getHeight();} @Overridepublic Bitmap getBitmap(String url) {return get(url);} @Overridepublic void putBitmap(String url, Bitmap bitmap) {put(url, bitmap);}}

(2) InstantiationImageLoader

The memory size allocated to each application by the android system is different. Use Runtime. getRuntime (). maxMemory () or

(ActivityManager) context. getSystemService (Context. ACTIVITY_SERVICE ))

. GetMemoryClass ();

You can obtain the allocated maximum memory. Note that the two units are different.

      private static ImageLoader mImageLoader;               //get the app's available memory  given by system,note that its unit is MB int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass(); //or you can get the memory value by this//memClass = (int) Runtime.getRuntime().maxMemory() ;// Use 1/8th of the available memory for this memory cache.int cacheSize = 1024 * 1024 * memClass /4;mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(cacheSize)); /** * get imageLoader */public static ImageLoader getImageLoader(){if(mImageLoader != null){return mImageLoader;}else{throw new IllegalStateException("the ImageLoader is null and not be initialized! ");}}

(3) InAdapterPassedNetworkImageViewOfSetImageUrlMethod LoadingImageLoaderDownloadURLThe specified image.

holder.showImage.setImageUrl(imageArrayList.get(position), imageLoader);


Note that the ImageLoader method is not used in normal imageview. Therefore, NetworkImageView, a subclass inherited from ImageView developed by Volley, must be used.


As follows:




Test Demo download



Related Article

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.