See the Netizen a piece of technical blog explained the use of LRUCache, I added it to my project, but added breakpoint found, the list up and down, it is true that you can not reload the picture, but reopen the activity or restart the application, LRUCache cache no longer exists, but need to re-network download, all I improved this method, added a layer to the phone memory to store the picture process.
In this case, when the picture is used, it is loaded from the LRUCache, and if the picture resource does not exist in the LRUCache, it is loaded from the phone store, and if it does not exist, a default picture is displayed first.
On the other hand, my project uses the picture of the ListView, when it is sliding, do not request the operation of the picture, so as not to waste unnecessary traffic, when it does not slide, will check which pictures are not in the phone storage, asynchronous request, The returned bitmap are stored in both LRUCache and the phone store.
Here are the key codes, some of which are variables in my project and can be ignored:
public class Taocanlistadapter extends Baseadapter implements onscrolllistener{/** * records All tasks that are downloading or waiting to be downloaded. */Private set<bitmapworkertask> taskcollection; /** * A core class of image caching technology that caches all downloaded images and removes the least recently used images when the program memory reaches the set value. */Private lrucache<string, bitmap> Mmemorycache; /** * The subscript of the first visible image */private int mfirstvisibleitem; /** * How many pictures can be seen on a screen * */private int mvisibleitemcount; /** * Record whether the program was just opened to solve the problem of entering the program without scrolling the screen and not downloading pictures. */Private Boolean isfirstenter = true; Final Oncheckedchangelistener Checkedchangelistener = new Oncheckedchangelistener () {@Overridepublic void OnCheckedChanged (Compoundbutton btn, Boolean value) {if (value) {if (Yixuannum < Xuanxiangnum) {//value changed then set to 1btn.settag ( R.id.tag_check, 1); Yixuannum + = 1;checkedtaocanidlist.add ((String) Btn.gettag (R.id.tag_dataid));} Else{toast.maketext (Taocanactivity.this, "up to select" + Xuanxiangnum + "x", Toast.length_short). Show (); Btn.setchecked ( false);}} Else{cHeckedtaocanidlist.remove (String) Btn.gettag (r.id.tag_dataid)) yixuannum-= 1;}}; Public Taocanlistadapter () {super (); taskcollection = new hashset<bitmapworkertask> (); Gets the application maximum available memory int maxmemory = (int) runtime.getruntime (). MaxMemory (); int cacheSize = MAXMEMORY/8; Set the picture cache size to the maximum available memory for the program 1/8 Mmemorycache = new lrucache<string, bitmap> (cacheSize) {@Override protected int sizeOf (String key, Bitmap Bitmap) {return bitmap.getbytecount (); } }; Taocanlistview.setonscrolllistener (this); } @Overridepublic view GetView (int position, view Convertview, ViewGroup arg2) {Viewholder holder = null;if (Convertview = = NULL) {Convertview = Layoutinflater.from (Getapplicationcontext ()). Inflate (R.layout.taocan_list_item, null); holder = New Viewholder (); holder.taocan_caiimg = (ImageView) Convertview.findviewbyid (r.id.taocan_caiimg); holder.taocan_ Caiming_text = (TextView) ConvertView.findviewbyid (r.id.taocan_caiming_text); holder.taocan_caiming_jiage = (TextView) Convertview.findviewbyid ( R.id.taocan_caiming_jiage); holder.taocan_tianjia_btn = (CheckBox) Convertview.findviewbyid (R.id.taocan_tianjia_ BTN); Convertview.settag (holder);} Holder = (viewholder) convertview.gettag (); Taocan Taocan = taocanlist.get (position); Holder.taocan_caiming_text.setText (Taocan.getfoodcnname ()); Holder.taocan _caiming_jiage.settext (Taocan.getprice () + "yuan/" + taocan.getunit ()); Holder.taocan_tianjia_btn.setTag (r.id.tag_ Dataid, Taocan.getfoodid ()); if (Position < Xuanxiangnum && Holder.taocan_tianjia_btn.getTag (r.id.tag_ check) = = null) {holder.taocan_tianjia_btn.setChecked (true); Yixuannum + = 1;checkedtaocanidlist.add (taocan.getfoodid ());} Holder.taocan_tianjia_btn.setOnCheckedChangeListener (Checkedchangelistener); if (Taocan.getphotopath ()! = NULL &&!taocan.getphotopath (). Equals ("")) {String Imgurl = globalvariables.getednpointout () + "/food/" + Taocan.getphotopath (); Holder.taocan_caiimg.settag (Imgurl); Setimageview (Imgurl, holder.taocan_caiimg);} Else{holder.taocan_caiimg.setimagedrawable (Getresources (). getdrawable (R.drawable.cai));} return Convertview;} @Overridepublic long getitemid (int arg0) {return 0;} @Overridepublic Object getItem (int arg0) {return null;} @Overridepublic int GetCount () {return taocanlist.size ();} @Override public void Onscroll (Abslistview view, int firstvisibleitem, int visibleitemcount, int totalit Emcount) {mfirstvisibleitem = Firstvisibleitem; Mvisibleitemcount = VisibleItemCount; The downloaded task should be called by onscrollstatechanged, but Onscrollstatechanged will not be called when the program is first entered,//So the download task is started here for the first entry program. if (isfirstenter && visibleitemcount > 0) {loadbitmaps (Firstvisibleitem, VisibleItemCount); Isfirstenter = false; }} @Override public void onscrollstatechanged (Abslistview view, int scrollstate) {//only if Gridv Iew to download the picture when it is still, the GridView cancels when slidingAll tasks being downloaded if (scrollstate = = Scroll_state_idle) {loadbitmaps (Mfirstvisibleitem, Mvisibleitemcount); } else {cancelalltasks (); }}/** * Set the picture for ImageView. First, remove the cache of the image from the LRUCache and set it to ImageView. If there is no cache for the picture in LRUCache, * set a default picture for ImageView. * * @param imageUrl * The URL address of the picture, used as the key for LRUCache. * @param ImageView * controls for displaying pictures. */private void Setimageview (String imageUrl, ImageView ImageView) {Bitmap Bitmap = Getbitmapfrommemorycach E (IMAGEURL); if (bitmap! = null) {Imageview.setimagebitmap (bitmap); } else {/** * lookup for local cache */Bitmap BITMAP1 = Findimgfromstorage (IMAGEURL) ; Imageview.setimagebitmap (BITMAP1); if (BITMAP1 = = null) {Imageview.setimageresource (R.DRAWABLE.CAI); }}}/** * Lookup of local cache */public BItmap findimgfromstorage (String imageUrl) {string bitmapname = Imageurl.substring (Imageurl.lastindexof ("/") + 1); String path = Environment.getexternalstoragedirectory (). GetPath (); File Cachedir = new file (path + "/mkb/"); file[] Cachefiles = Cachedir.listfiles (); int i = 0; if (null! = Cachefiles) {for (; i<cachefiles.length; i++) {if (Bitmapname.equals (Cachef Iles[i].getname ())) {break; }} if (I < cachefiles.length) {return bitmapfactory.decodefile (path + "/MK b/"+ bitmapname); }} return null;} /** * Store a picture in the LRUCache. * * @param key * LRUCache, where the URL of the image is passed in. * @param bitmap * LRUCache key, where bitmap objects downloaded from the network are passed in. */public void Addbitmaptomemorycache (String key, Bitmap Bitmap) {if (GetbitmapfrommemorycaChe (key) = = null) {Mmemorycache.put (key, bitmap); }}/** * Gets a picture from LRUCache and returns null if it does not exist. * * @param key * LRUCache, where the URL of the image is passed in. * @return The Bitmap object that corresponds to the incoming key, or null. */Public Bitmap Getbitmapfrommemorycache (String key) {return mmemorycache.get (key); }/** * Loads the bitmap object. This method checks the ImageView bitmap object visible in all screens in LRUCache, and if any ImageView bitmap object is found not in the cache, the asynchronous thread is opened to download the image. * * @param firstvisibleitem * The first visible subscript of ImageView * @param visibleitemcount * screen Total number of elements visible in */private void loadbitmaps (int firstvisibleitem, int visibleitemcount) {try { for (int i = Firstvisibleitem; I < Firstvisibleitem + VisibleItemCount; i++) {Taocan Taocan = taocanlist. Get (i); if (taocan.getphotopath () = null &&!taocan.getphotopath (). Equals ("")) {Bitmap Bitmap1 = Findimgfromsto Rage (Taocan.getphotopath ()); If the memory does not exist then re-request if (BITMAP1 = = null) {String IMAGEURL = globalvariables.getednpointout () + "/ food/"+ Taocan.getphotopath (); Bitmap Bitmap = Getbitmapfrommemorycache (IMAGEURL); if (bitmap = = null) {Bitmapworkertask task = new Bitmapworkertask (); Taskcollection.add (Task); Task.execute (IMAGEURL); } else {ImageView ImageView = (ImageView) taocanlistview.findviewwithtag (IMAGEURL); if (ImageView = null && bitmap! = null) {Imageview.setimagebitmap (bit MAP); }}}}}} catch (Exception e) { E.printstacktrace (); }}/** * Cancels all tasks that are downloading or waiting to be downloaded. */public void Cancelalltasks () { if (taskcollection! = null) {for (Bitmapworkertask task:taskcollection) {task.ca Ncel (FALSE); }}}/** * The task of downloading pictures asynchronously. * * @author Zhangda */class Bitmapworkertask extends Asynctask<string, Void, bitmap> {/* * * Image URL Address */private String IMAGEURL; @Override protected Bitmap doinbackground (String ... params) {imageUrl = params[0]; Start downloading pictures in the background Bitmap Bitmap = Downloadbitmap (Params[0]); if (bitmap! = null) {//The picture is downloaded and cached to Lrccache Addbitmaptomemorycache (Params[0], bitmap); }//Store to phone in memory String path = Environment.getexternalstoragedirectory (). Getpat H (); File dir = new file (path + "/mkb/"); if (!dir.exists ()) {dir.mkdirs (); } File Bitmapfile = new file (path + "/mkb/" + imageurl.substring (imageUrl. LastIndexOf ("/") + 1)); if (!bitmapfile.exists ()) {try {bitmapfile.createnew File (); } catch (IOException e) {e.printstacktrace (); }} FileOutputStream Fos; try {fos = new FileOutputStream (bitmapfile); Bitmap.compress (Bitmap.CompressFormat.PNG, N, FOS); Fos.close (); } catch (FileNotFoundException e) {e.printstacktrace (); } catch (IOException e) {E.PRintstacktrace (); } return bitmap; } @Override protected void OnPostExecute (Bitmap Bitmap) {super.onpostexecute (BITMAP); According to tag find the corresponding ImageView control, will download the good picture display. ImageView ImageView = (ImageView) taocanlistview.findviewwithtag (IMAGEURL); if (ImageView! = null && bitmap! = null) {Imageview.setimagebitmap (bitmap); } taskcollection.remove (this); /** * Set up an HTTP request and get the bitmap object. * * @param imageUrl * Image URL address * @return parsed Bitmap Object */Private Bitmap Downloadbitmap (String imageUrl) {Bitmap Bitmap = null; HttpURLConnection con = null; try {URL url = new URL (imageUrl); Con = (httpurlconnection) url.openconnection (); Con.setconnecttimeout (5 * 1000); Con.setreadtimeout (10 * 1000); Bitmap = Bitmapfactory.decodestream (Con.getinputstream ()); } catch (Exception e) {e.printstacktrace (); } finally {if (con! = null) {con.disconnect (); }} return bitmap; }} Private class Viewholder{private ImageView taocan_caiimg;private TextView Taocan_caiming_text;priv Ate TextView taocan_caiming_jiage;private CheckBox taocan_tianjia_btn;}}
adapter = new Taocanlistadapter (); Taocanlistview.setadapter (adapter);
Asynchronous requests for Android images and storage of images using LRUCache cache and phone memory, to avoid reloading page re-requests