Import Java.io.bufferedinputstream;import Java.io.bytearrayoutputstream;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.url;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.handler;import Android.os.message;import Android.support.v4.util.lrucache;import Android.util.Log; Import android.widget.imageview;/* * Use Android's new LRUCache cache image to load images asynchronously based on the thread pool. * Basic ideas: Create a thread pool to download network images, while creating a LRUCache as an Android memory cache for mixed images. * The upper application passes over a URL asking to download a picture from that URL, first check if there is a cached picture in LRUCache that is indexed with that URL, * If so, read it directly from the cache and return it to the upper application; if not, then thread the download, This bitmap is buried in the cache when the download is complete. * Note: The URL of the image is used as the LRUCache Key when the image is cached. * LRUCache in-memory cache model for <K,V>. */public class Asyncimageloader {private Executorservice pool;private Handler handler;private Imageloadedlistener Listener;private final int what = 0xe001;//default thread pool capacity private int default_task_number = 10;//Network Time-out: 30 seconds private static int T imeout = * 1000;private LRUCACHe<string, bitmap> mmemorycache;//4MB cache size private final int cache_size = 4 * 1024x768 * 1024;public asyncimageloader (int Asynctasknumber) {initialization (asynctasknumber);} Public Asyncimageloader () {///default constructor initializes the thread pool capacity to: Task_numberinitialization (Default_task_number);} Initialize private void initialization (int asynctasknumber) {Mmemorycache = new lrucache<string, bitmap> (cache_size) {@ overrideprotected int sizeOf (String key, Bitmap value) {return value.getrowbytes () * Value.getheight ();}};/ /Create a thread pool with a capacity of asynctasknumber. Pool = Executors.newfixedthreadpool (asynctasknumber), handler = new handler () {@Overridepublic void Handlemessage ( Message message) {switch (message.what) {case WHAT:listener.imageLoaded ((Bitmap) message.obj);}};} Asynchronously sets a Imagview bitmap (the bitmap of the ImageView is loaded from the network)//The method is public, as the external calling interface of the tool class. public void Asyncsetimagebitmap (String URL, final ImageView view) {Download (URL, new Imageloadedlistener () {@ overridepublic void imageloaded (Bitmap Bitmap) {view.setimagebitmap (BITMAP);}});} Asynchronously downloads a bitmap from a URL. After the download succeeds, the callback imageloaded (Bitmap Bitmap, String URL);//The method is public, as the external calling interface of the tool class. public void download (String URL, Imageloadedlistener listener) {This.listener = listener;//first checks from the cache for the existence of a URL-key bitmap. If it does, it is read directly from the cache and is no longer used to load repeatedly. Bitmap bmp = Mmemorycache.get (URL), if (BMP! = null) {LOG.D ("read cache", URL + "already cached, no need to repeat download!") "); Sendresult (BMP); return;} Thread t = new Downloadthread (URL);p ool.execute (t);} Open a download thread private class Downloadthread extends thread {private string url;public downloadthread (String url) {this.url = u RL;} @Overridepublic void Run () {Bitmap bmp = Loadbitmapfromurl (URL);//embed the new Bitmap in the cache mmemorycache.put (URL, BMP); Sendresult ( BMP);}} Send Message notification: Bitmap has been downloaded to completion. private void Sendresult (Bitmap Bitmap) {Message message = Handler.obtainmessage (); message.what = What;message.obj = Bitma P;handler.sendmessage (message);} callback function public interface Imageloadedlistener {public void imageloaded (Bitmap Bitmap);} Given a URL, download bitmappublic static Bitmap loadbitmapfromurl from this URL (strinG URL) {if (!url.contains ("http://")) {URL = "/http" + URL;} LOG.D ("Thread:" + thread.currentthread (). GetId (), "Start download:" + URL); Bitmap bmp = null;try {byte[] imagebytes = loadrawdatafromurl (URL); bmp = Bitmapfactory.decodebytearray (imagebytes, 0, Imagebytes.length);} catch (Exception e) {e.printstacktrace ();} return bmp;} Given a URL, download the original data block from this URL. public static byte[] Loadrawdatafromurl (String u) throws Exception {URL url = new URL (u); HttpURLConnection conn = (httpurlconnection) url.openconnection ();//Configure the underlying network link parameter conn.setconnecttimeout (TIMEOUT); Conn.setreadtimeout (TIMEOUT); InputStream is = Conn.getinputstream (); Bufferedinputstream bis = new Bufferedinputstream (IS); Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); final int buffer_size = 1024x768 * 5;final int EOF = -1;int c;byte[] BUF = new Byte[buffer_size];while (true) {c = Bis.read (BUF); if (c = = EOF) break;baos.write (buf, 0, c);} Conn.disconnect (); Is.close (); byte[] data = Baos.tobytearray (); Baos.flush (); return data;}}
Use Android's new LRUCache cache image to load images asynchronously based on the thread pool