Prefacio
De hecho, tengo mucha suerte. Recientemente, he estado ocupado con la oportunidad de resumir.
principio
Los principios de carga de imágenes en ListView o GridView son básicamente los mismos:
Obtenga el caché de memoria y devuélvalo.
El diagrama de flujo es el siguiente:
Al mismo tiempo, preste atención al número de hilos. En general, cargando imágenes en ListView, todos abren nuevos hilos para cargar, pero cuando se desliza rápidamente, es fácil causar OOM, por lo que debe controlarse la cantidad de hilos. Podemos controlar el número de hilos a través del grupo de subprocesos.
El método para establecer un grupo de subprocesos es el siguiente:
EjecutorService EjecutorService = Ejecutors.netFixedThreadPool (5);
Clase de caché de archivo
Import java.io.file; OS.environment.getExternalStoraGestate (). ) {Cachedir.mkders ();}} Public File getFile (String Url) {// Identifica imágenes por el código hash de URL string filename = string.valueOf (url.hashcode ()); ; Clase de caché de memoria
Aquí hay una referencia suave, MAP <String, Softreference <Map>> Cache, puede buscar en Google un mecanismo de referencia suave.
Import java.lang.ref.softreference; Colecciones. Ref.get ();} public void put (ID de cadena, mapas de bitmap) {cache.put (id, new Softreference <bit map> (bitmap);} public void clear () {cache.clear ();}}Clase de carga de imágenes
Importar java.io.file; Util.Collections; .BitMapFactory; Cache * / MemoryCache MemoryCache = nuevo MemoryCache (); SynchronizedMap (New WeakHashMap <ImageView, String, String> ()); {fileCache = new FileCache (contexto); Imagen de memoria cache imageView.setImageBitMap (bitmap);} else {// muestra desde cache de archivo o red queuephoto (url, imageV iwew);}} private void queuephoto (URL de cadena, imageView ImageView) {Phototoload Phototoload = newTotoload (URL (url , ImageView); {Return bmp;} // desde la red {bitmap bitmap = null; (Verdadero); {if (exstanceOf outOfMemoryError) {clearCache ();} private void copystream (InputStream es, OutputStream OS) {int buffer_size = 1024; .Read (bytes, 0, buffer_size); F) {try {// toDo: compresa de imagen fileInputStream = new FileInputStream (f); {MemoryCache.CLEAR (); URL, ImageView ImageView) {this.url = url; ) {This.photOtoload = Phototoload;} Private Boolean ImageViewReused (Phototoload Photoload) {String Tag = ImageView.get (Phototoload.im.im.im.im.im.im.im.im edadView); ||! bitmap bitmap = getBitMap (Phototoload.url); Bitmapdisplayer (Bitmap, PhotoToload); Handler.post (BD);} Class Bitmapdisplayer IMPLEMENTS Runnable {BI TMAP BITMAP; PhotoToload PhotoToload; Public Bitmapdisplayer (bitmap bitmap, Photoload PhotoLoad) {this.bitmap = bitmap; this. PhotoLoad = PHOTOTOLOAD;} @Override public void run () {if (imageViewReused (Phototoload)) {return;} if (bitmap! = Null) oad.imageView.setImageBitMap (bitmap);} else {Phototoload.imageView.SetimageResource (predeterminado_bg);}}}} }}Método de llamadas
ImageLoader imageLoader = new ImageLoader (contexto);