Use LRUCache and disklrucache to download images

Source: Internet
Author: User

LRUCache is a very useful image caching tool:

The main practice is: Slide the picture when the Bitmap cache in Lrucache<string, bitmap>, after exiting the program to cache the picture into the file. Used Disklrucache Mdisklrucache


So we have to set the address of a picture cache:

public void Setimagecache () {String strpath = null; if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {File Sdfile =    Environment.getexternalstoragedirectory ();    strpath = Sdfile.getabsolutepath () + "/pic/";        File Cachefile = new file (strpath);        if (!cachefile.exists ()) {Cachefile.mkdir ();    }} else{String Strcachedir = This.getcachedir (). GetAbsolutePath ();    strpath = Strcachedir + "/pic/";    } setcachepath (strpath); }private void Setcachepath (String strpiccachepath) {if (Textutils.isempty (Strpiccachepath)) {return;} M_strpiccachepath = Strpiccachepath;        File Cachefile = new file (Strpiccachepath);        if (!cachefile.exists ()) {Cachefile.mkdir (); }}public string Getcachebmppath (string strurl) {if (Textutils.isempty (M_strpiccachepath) | | Textutils.isempty (strURL)) {return "";} return M_strpiccachepath + stringutil.md5encode (strurl) + mfileexname;//". bmp";} 

Then write the list of adapter:

Private class ListAdapter extends Baseadapter implements Onscrolllistener {protected list<shopdata> items = new Arra Ylist<shopdata> ();p rotected static final int fetch_image_msg = 1;private lrucache<string, bitmap> mmemorycache;protected hashset<imageview> mitemsmissingimages = new hashset<imageview> ();p rotected Imageloaderhandler mhandler;protected imageloader mimagefetcher;public static final int TIMEOUT = 30000;//  Timeout Time 30 sec private Disklrucache Mdisklrucache; Public ListAdapter () {super (); Mhandler = new Imageloaderhandler (); int maxmemory = (int) runtime.getruntime (). MaxMemory ( int mcachesize = maxmemory/8;//assigns LruCache 1/8 4MmMemoryCache = new lrucache<string, bitmap> (mcachesize) {//Must be re- Write this method to measure the size of the Bitmap @overrideprotected int sizeOf (String key, Bitmap value) {return value.getrowbytes () * Value.getheight ( );}}; try {mdisklrucache = disklrucache. Open (New File (M_strpiccachepath), Getappversion (Mainactivitytest.this) , 1, 10 * 1024 * 1024);}  catch (IOException e) {e.printstacktrace ();} }/** * Synchronizes cache records to the journal file.

*/public void Fluchcache () {if (Mdisklrucache! = null) {try {Mdisklrucache.flush ();} catch (IOException e) {e.printstackt Race ();}}} @Overridepublic int GetCount () {return items.size ();} @Overridepublic Object getItem (int position) {return items.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Shopdatatag tag = new Shopdatatag (); if (CO Nvertview = = null) {Convertview = minflater.inflate (R.layout.listitem, null); tag.name = (TextView) Convertview.findviewbyid (r.id.name); tag.shopinfo = (TextView) Convertview.findviewbyid (r.id.info); Tag.icon = ( ImageView) Convertview.findviewbyid (R.id.image_icon); Convertview.settag (tag);} else {tag = (Shopdatatag) Convertview.gettag ();} TextView name = Tag.name; TextView info = Tag.shopinfo;imageview ImageView = Tag.icon; Shopdata data = items.get (position); Name.settext (data.name); Info.settext (Data.info); Imageview.settag (Data.url); Setcontactphoto (Data.url, ImageView); return convertview;} protected void Setcontactphoto (String url,imageview viewtouse) {if (Textutils.isempty (URL)) { Viewtouse.setimageresource (R.drawable.avatar);} else{//first See Mmemorycache can not get bitmapbitmap bitmap = mmemorycache.get (URL); if (bitmap! = null) {Viewtouse.setimagebitmap (bitmap);} else {Snapshot Snapshot = null; FileDescriptor filedescriptor = null; FileInputStream FileInputStream = null;try {//Because Mdisklrucache will use key as the file name. So the URL is converted through MD5 to keyfinal String key = Hashkeyfordisk (URL); snapShot = Mdisklrucache.get (key);//Assuming snapShot is empty, Just can't find the corresponding file if (SnapShot = = null) {//here to download fetchimage (viewtouse);} Else{fileinputstream = (fileinputstream) snapshot.getinputstream (0); filedescriptor = Fileinputstream.getfd (); if ( FileDescriptor = null) {bitmap = Bitmapfactory.decodefiledescriptor (FileDescriptor);} Suppose parsing a file into bitmap failed. Download again if (! Textutils.isempty (URL) && bitmap! = null) {mmemorycache.put (URL, bitmap); Viewtouse.setimagebitmap (bitmap);} Else{fetchimage (Viewtouse);}}} catch (IOException ex) {ex.printstacktrace ();} Finally{if (FileDescriptor = = NULL && FileInputStream! = null) {try {fileinputstream.close ();} catch (IOException e) {}}}}} private void Fetchimage (ImageView viewtouse) {viewtouse.setimageresource (R.drawable.avatar); Mitemsmissingimages.add (Viewtouse); if (mscrollstate! = onscrolllistener.scroll_state_fling) {sendFetchImageMessage (Viewtouse);}} public string <strong>hashKeyForDisk</strong> (string key) {convert key to MD5 file return Stringutil.md5encode (key) ;} Image Downloaderprivate Class Imageloaderhandler extends Handler {@Overridepublic void handlemessage (Message message) {if (isfinishing ()) {return;} Switch (message.what) {case fetch_image_msg: {final ImageView ImageView = (ImageView) message.obj;if (ImageView = = null) { break;} Final String url = (String) imageview.gettag (); if (Textutils.isempty (URL)) {break;} Bitmap map = getbitmapfrommemcache (URL); if (map = = null) {break;} Synchronized (ImageView) {final String Myurl = (String) Imageview.gettag ()if (textutils.equals (URL, myurl)) {imageview.setimagebitmap (map); Mitemsmissingimages.remove (ImageView);} else {}} Break;}}} public void clearimagefecthing () {removemessages (fetch_image_msg);}} Private class Imageloader implements Runnable {string url;private ImageView mimageview;public imageloader (string URL, Ima Geview imageView) {this.url = Url;this.mimageview = ImageView;} public void Run () {if (isfinishing ()) {return;} if (thread.interrupted ()) {return;} FileDescriptor filedescriptor = null; FileInputStream fileinputstream = null; Snapshot Snapshot = null;try {final String key = Hashkeyfordisk (URL); Snapshot = Mdisklrucache.get (key); if (Snapshot = = nul L) {//if the corresponding cache is not found, prepare to request data from the network. and writes the cache disklrucache.editor Editor = Mdisklrucache.edit (key); if (Editor! = null) {OutputStream OutputStream = Editor.newoutputstream (0); Boolean flag = Downloadimage (URL, outputstream), if (flag) {Editor.commit ();} else { Editor.abort ();}} After the cache is written, look again for the corresponding cache of key snapshot = Mdisklrucache.get (key);} This should delete the appropriate file if (SnapshoT! = null) {FileInputStream = (fileinputstream) snapshot.getinputstream (0); filedescriptor = Fileinputstream.getfd ();} Parses the cached data into a Bitmap object bitmap bitmap = null;if (filedescriptor! = null) {bitmap = Bitmapfactory.decodefiledescriptor ( FileDescriptor);} if (bitmap! = null) {//Bitmap object is added to the memory cache where Mmemorycache.put (URL, bitmap);}} catch (IOException e) {e.printstacktrace ();} finally {if (FileDescriptor = = NULL && FileInputStream! = null) {try {Fileinputstream.close ();} catch (IOException e) {}}}if (thread.interrupted ()) {return;} Message msg = new Message (); msg.what = Fetch_image_msg;msg.obj = Mimageview;mhandler.sendmessage (msg);}} Public Bitmap Getbitmapfrommemcache (String key) {return mmemorycache.get (key); public boolean downloadimage (String strurl,outputstream fos) {URL getUrl = null; Bitmap Bitmap = null; Bufferedoutputstream out = null; Bufferedinputstream in = null;try {getUrl = new URL (strURL),} catch (Malformedurlexception ex) {LOG.E ("Httputil", "Get Mal Formedurl ", ex); return false;} InputStream input = null; HttpURLConnection conn = null;try {conn = (httpurlconnection) geturl.openconnection (); Conn.setconnecttimeout (TIMEOUT) ; Conn.setreadtimeout (TIMEOUT); Conn.setdoinput (true); Conn.connect (); input = Conn.getinputstream (); in = new Bufferedinputstream (Input, 8 * 1024x768); out = new Bufferedoutputstream (FOS, 8 * 1024x768), int b;while ((b = In.read ())! =-1) {OU T.write (b);} return true;} catch (Exception ex) {LOG.E ("Httputil", "Downloadimage", Ex),} catch (OutOfMemoryError ex) {ex.printstacktrace ();} Finally {try {if (out! = null) {out.close (); out = null;} if (in! = null) {in.close (); in = null;} IF (conn! = null) {conn.disconnect (); conn = null;}} catch (Exception ex) {LOG.E ("Httputil", "Downloadimage finally", Ex);}} return false;} Private Boolean GetResponse (InputStream input, OutputStream OS, byte[] data) throws ioexception{if (input = = NULL | | os = = null | | data = = NULL) {return false;} int i = 0;while ((i = input.read (data))! =-1) {os.write (data, 0, I); Os.flush ();} Os.flush (); return true;} private void Processmissingimageitems (Abslistview view) {for (ImageView iv:mitemsmissingimages) { Sendfetchimagemessage (iv);}} protected void Sendfetchimagemessage (ImageView view) {final String url = (String) view.gettag (); if (Textutils.isempty ( URL)) {return;} Mimagefetcher = new Imageloader (URL, view); synchronized (mainactivitytest.this) {if (Simagefetchthreadpool = = null) { Simagefetchthreadpool = Executors.newfixedthreadpool (3);} Simagefetchthreadpool.execute (Mimagefetcher);}} public void clearimagefetching () {synchronized (mainactivitytest.this) {if (Simagefetchthreadpool! = null) { Simagefetchthreadpool.shutdownnow (); simagefetchthreadpool = null;}} Mhandler.clearimagefecthing ();} public void Clearmessages () {if (Mhandler! = null) {try {mhandler.removecallbacksandmessages (null);} catch ( java.lang.Throwable th) {}mhandler = null;}} @Overridepublic void onscrollstatechanged (abslistview view, int scrollstate) {mscrollstate = Scrollstate;if ( Scrollstate = = Onscrolllistener.scroll_state_fling) {clearimagefetching ();} else {processmissingimageitems (view);}} @Overridepublic void Onscroll (abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) {}} Private class Shopdatatag {TextView name; TextView shopinfo;imageview icon;}


:

Code: http://download.csdn.net/detail/baidu_nod/7777137

Use LRUCache and disklrucache to download images

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.