Android combines volley's Networkimageview to implement picture file caching

Source: Internet
Author: User

Image caching is often used when writing Android applications, and for network requests using the network Communication library on the Android platform , Volley can make network communication faster, simpler, more robust, and Volley is especially suitable for scenes with small amounts of data but frequent communication, so you can use volley to request a network picture. Next I will be in a project of the picture cache module to share with you, welcome criticism.

/** * @author * @date 2015/4/14 * Use file cache image */public class Imagefilecacheutils {private static final String Chchedir = "I Magechace ";//cache directory private static final String Wholesale_conv =". Cache ";//buffer file suffix private static final int MB = 1024 * 1024; private static final int cache_size = 80;//Cache Maximum Capacity (the LRU algorithm is used to remove the least recently used cache file) private static final int free_sd_space_needed _to_cache = 100;//The minimum amount remaining for the SD card required by the cache is private static imagefilecacheutils instance = NULL; Singleton mode public static Imagefilecacheutils getinstance () {if (instance = = null) {synchronized (Imagefilecacheutils.class) { if (instance = = null) {instance = new Imagefilecacheutils ();}}} return instance;} Public Imagefilecacheutils () {RemoveCache (Getdirectory ());} /** * Get picture from file cache * @param URL * @return */public Bitmap getImage (final string url) {Final string path = Getdirectory () + "/ "+converturltofilename (URL); File File = new file (path), if (File.exists ()) {Bitmap Bitmap = bitmapfactory.decodefile (path), if (Bitmap = = null) { File.delete (); return null;} else {Updatefiletime (path);//update file latest access time return bitmap;}} else {return null;}} /** * Get Cache Directory * @return */private string getdirectory () {String dir = Getsdpath () + "/" + Chchedir;return dir;} Private String Getsdpath () {File Sddir = Null;boolean adcardexit = Environment.getexternalstoragestate (). EndsWith ( environment.media_mounted);//Determine if the SD card is mounted if (adcardexit) {sddir = Environment.getexternalstoragedirectory ();//Get root directory} if (sddir! = null) {return sddir.tostring ();} else {return "";}}  /** * Modified the last modified time of the file * @param path */private void Updatefiletime (String path) {File File = new file (path); Long Newmodeifytime = System.currenttimemillis (); file.setlastmodified (newmodeifytime);} public void Savebitmap (Bitmap bitmap,string URL) {if (Bitmap = = null) {return;} Determine the space on the SD card if (Free_sd_space_needed_to_cache > Freespaceonsd ()) {return;} String fileName = converturltofilename (URL); String dir = getdirectory (); File Dirfile = new file (dir), if (!dirfile.exists ()) {dirfile.mkdirs ();} File File = new file (dir + "/" +filename); try{file.createnewfile (); OutputStream outputstream = new FileOutputStream (file); Bitmap.compress ( Bitmap.CompressFormat.JPEG, OutputStream); Outputstream.flush (); Outputstream.close (); catch (IOException e) {e.printstacktrace ();}} /** * Calculate the remaining space on the SD card * @return */private int freespaceonsd () {StatFs StatFs = new StatFs (environment.getexternalstoragedirect Ory (). GetPath ());d ouble sdfreemb = (double) statfs.getavailableblocks () * (double) statfs.getblocksize ())/MB; LOG.I ("Test", "Space Remaining:" +SDFREEMB); return (int) sdfreemb;} /** * Translate URL to filename * @param URL * @return */private String converturltofilename (string url) {string[] STRs = Url.split ("/"); r Eturn Strs[strs.length-1] + wholesale_conv;} /** * Calculate the file size of the storage directory * When the total size of the file is greater than the specified size or the remaining space of the SD card is less than the Free_sd_space_needed_to_cache, then delete 40% files that have not been used recently * @param dirpath * @r Eturn */private boolean RemoveCache (String dirpath) {file Dirfile = new File (Dirpath); file[] files = dirfile.listfiles (); if (files = = NULL | | files.length <= 0) {return true;} If the SD card is not mounted if (! EnVironment.getexternalstoragestate (). Equals (environment.media_mounted)) {return false;} int dirsize = 0;for (int i = 0; i < files.length; i++) {if (Files[i].getname (). Contains (Wholesale_conv)) {dirsize + = fi Les[i].length ();}} if (Dirsize > cache_size * MB | | Free_sd_space_needed_to_cache > Freespaceonsd ()) {int removefactor = (int) ((0.4 * files.length) + 1); Arrays.sort (Files, new Filelastmodifysoft ()); for (int i = 0; i < Removefactor; i++) {if (Files[i].getname (). Contains (WH Olesale_conv)) {Files[i].delete ();}}} if (FREESPACEONSD () <= cache_size) {return false;} return true; }//Comparator class private class Filelastmodifysoft implements comparator<file>{@Overridepublic int compare (file arg0, file ARG1) {if (arg0.lastmodified () > Arg1.lastmodified ()) {return 1;} else if (arg0.lastmodified () = = Arg1.lastmodified ()) {return 0;} else {return-1;}}}
Using Volley's Networkimageview to load a picture requires passing in a imageloader, which requires a class that implements the Imagecache interface when constructing Imageloader, so this class is constructed first:

public class Imagefilecache implements imagecache{@Overridepublic Bitmap getbitmap (String URL) {return Imagefilecacheutils.getinstance (). GetImage (URL);} @Overridepublic void Putbitmap (String url, Bitmap Bitmap) {imagefilecacheutils.getinstance (). Savebitmap (Bitmap, URL);}}
Next, use Networkimageview to load the network pictures:

To use volley custom components in a layout file:

<com.android.volley.toolbox.networkimageview                android:id= "@+id/activity_icon"                android:layout_width= " @dimen/activity_icon_size_w "                android:layout_height=" @dimen/activity_icon_size_h "                android:layout_ marginright= "4DP"                android:scaletype= "centerinside"                android:src= "@drawable/activity_example"/>

<pre name= "code" class= "java" style= "Color:rgb (85, 85, 85); font-size:14px; line-height:26px; Orphans:2; Widows:2; " >//initialization Imageloaderimageloader Imageloader = new Imageloader (volley.newrequestqueue (context), new Imagefilecache ()) ;
Activity_icon.setdefaultimageresid (r.drawable.activity_example); Activity_icon.seterrorimageresid ( R.drawable.activity_example);
<pre name= "code" class= "java" style= "Color:rgb (85, 85, 85); font-size:14px; line-height:26px; Orphans:2; Widows:2; " >holder.activity_icon.setimageurl (A.getlogo (), imageloader);


This module can be used directly in your own project and hopefully can help everyone.
Copyright Notice: This article is for bloggers original articles, need to be reproduced, please indicate the source in the form of links .




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android combines volley's Networkimageview to implement picture file caching

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.