Android image loaded Cache class _android

Source: Internet
Author: User
Tags save file

This article for you to share the Android image load cache class for your reference, the details are as follows

Import Java.io.File; 
Import Java.io.FileInputStream; 
Import java.io.FileNotFoundException; 
Import Java.io.FileOutputStream; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import java.lang.ref.SoftReference; 
Import java.net.HttpURLConnection; 
Import Java.net.URL; 
Import Java.util.LinkedHashMap; 
Import Java.util.concurrent.ConcurrentHashMap; 
Import Java.util.concurrent.ExecutorService; 
 
Import java.util.concurrent.Executors; 
Import Android.graphics.Bitmap; 
Import Android.graphics.BitmapFactory; 
Import Android.os.Build; 
Import Android.os.Handler; 
 
Import Android.text.TextUtils; /** * Image loader, the main function is to download pictures from the network and cache. The reason for writing another feature like this is that the old picture loading logic is very complicated, I write a lightweight * * @author H3C */public class Imageloaderengine {public St 
  atic final int load_img_success = 2010; Private final int max_capacity = Build.VERSION.SDK_INT > Build.version_codes. Gingerbread_mr1? 
  50:10;//level cache cache picture number private static Imageloaderengine instance; private static Handler Mhandler; Private Executorservice pool;//Background thread pool//Here Linkedhashmap do not use LRUCache because the LRUCache directly request the size of the memory rather than the number of pictures. This app already has a global LRUCache, duplicate application memory size for application disadvantage private linkedhashmap<string, bitmap> mfirstlevelcache;//<momentid 
  > Cache, Hard link bitmap, keep only the most recently used pictures. Private concurrenthashmap<string, softreference<bitmap>> msecondlevelcache;//<momentId> Public St atic imageloaderengine getinstance (Handler Handler) {if (instance = null) {instance = new Imageloaderengine 
    (); 
    } if (handler!= null) {Mhandler = handler; 
  return instance; 
  Private Imageloaderengine () {pool = Executors.newfixedthreadpool (4);//The default thread pool size is 6 initcache (); 
        } private void Initcache () {Mfirstlevelcache = new linkedhashmap<string, bitmap> (MAX_CAPACITY/2, 
 
      0.75f, True) {private static final long serialversionuid = 1L; 
     Protected Boolean removeeldestentry (Entry<string, bitmap> eldest) {   if (size () > Max_capacity) {//greater than the first cache size is moved to the level two cache Msecondlevelcache.put (Eldest.getkey (), NE 
          W softreference<bitmap> (Eldest.getvalue ())); 
        return true; 
      return false; 
    }; 
    };  
   Msecondlevelcache = new concurrenthashmap<string, softreference<bitmap>> ()//<momentId>}/** * Remove Cache * @param key/public void Deletecachebykey (string key) {String Sdcacheingpath = iohelper.ge 
    Tcachedpicturepath (Global.packagename, key); 
    String Sdcacheedpath = Sdcacheingpath + ". png"; 
    File File = new file (Sdcacheingpath); 
    if (file.exists ()) {file.delete (); 
    File = new file (Sdcacheedpath); 
    if (file.exists ()) {file.delete (); 
    } mfirstlevelcache.remove (key); 
  Msecondlevelcache.remove (key); 
      /** * FREE resources/public void Recycleimageloader () {new Thread () {The new Runnable () {@Override PubLIC void Run () {if (pool!= null) {Pool.shutdownnow (); } if (Mfirstlevelcache!= null) {for (Bitmap bmp:mFirstLevelCache.values ()) {if (BMP 
              != null) {bmp.recycle (); 
            BMP = NULL; 
          } mfirstlevelcache.clear (); 
        Mfirstlevelcache = null; 
        } if (Msecondlevelcache!= null) {msecondlevelcache.clear (); 
      } Mhandler = null; 
  }). Start (); /** * Background Request picture * * @param item */public void Loadimagebymoment (final nmoment moment,string Photot 
      AG) {if (Moment.ispicture () | | Moment.isvideo ()) {String id = moment.id + phototag; 
    Loadimagebyurl (id+ "", Moment.getpicture (global.widthpixels/3*2), moment.orientation); /** * Background Request picture * @param key * @param url/public void Loadimagebyurl (final String Key,fin Al String Url,final int Orientation) {Pool.submit (new Runnable () {public void run () {LOGHELPER.E ("Imageloadere 
          Ngine "," Download from the Network "); If the memory is in the IF (Mfirstlevelcache.get (key)!= null | | | msecondlevelcache.get (KEY)!= null) {//IF 
            The picture has been cached LOGHELPER.E ("Imageloaderengine", "Download picture error 1"); 
          Return //If there is a final String Sdcacheingpath = Iohelper.getcachedpicturepath in the SD card cache (Glob 
          Al.packagename, key); 
          File Cacheingfile = new file (Sdcacheingpath); 
            if (cacheingfile.exists ()) {//If caching is a long currenttime = System.currenttimemillis (); if ((Currenttime-cacheingfile.lastmodified ()) >2 * 1000) {LOGHELPER.E ("Imageloaderengine", "2 minutes is not Download complete, ready to delete it ... " 
              +currenttime+ "=" +cacheingfile.lastmodified ()); 
            Cacheingfile.delete (); else {getbitmapfromnetworkandaddtomemory (URL, key, orIentation); 
              LOGHELPER.E ("Imageloaderengine", "The second time come in should walk here ..."); 
            Return 
          } String Sdcacheedpath = Sdcacheingpath + ". png";//The cache is complete, it will change the name, or it will cause a cache error, the picture becomes black 
          File Cacheedfile = new file (Sdcacheedpath); 
            if (cacheedfile.exists ()) {//If the cache is LOGHELPER.E ("Imageloaderengine", "Download picture error 2"); 
          Return 
        } getbitmapfromnetworkandaddtomemory (URL, key, orientation); 
  } 
      }); } private void Getbitmapfromnetworkandaddtomemory (String url,string key,int orientation) {Bitmap bmp = Getbit 
    Mapfromurl (URL); 
       
      if (bmp!= null) {LOGHELPER.E ("Imageloaderengine", "Download network picture successful"); 
      if (Key.endswith ("_detaildaily")) {BMP = Scaledbitmap (BMP, Global.getthumbwidth ()); } if (orientation!= 0) {mfirstlevelcache.put (key, Viewhelper.rotatebitmap (orientation, BMP)); Direct display of the network after downloading} ElSE {mfirstlevelcache.put (key, BMP),///if downloaded directly from the network} if (Mhandler!= null) {Mhandler 
        . Removemessages (load_img_success); Mhandler.sendemptymessagedelayed (load_img_success, 600);//delay Prompt No data} final String SD 
      Cacheingpath = Iohelper.getcachedpicturepath (Global.packagename, key); 
    Savebitmaptofile (Sdcacheingpath, BMP); 
    else {LOGHELPER.E ("Imageloaderengine", "Download network picture failed ..."); 
    }/** * get * @param URL * directly from the network * @return/Public Bitmap getbitmapfromurl (String URL) { 
    URL myfileurl = null; 
    Bitmap Bitmap = null; 
    InputStream is = null; try {if (! 
      Uiutils.isnetworkavailable (Myapplication.getinstance ()) {return null; 
      } myfileurl = new URL (URL); 
      HttpURLConnection conn = (httpurlconnection) myfileurl. OpenConnection (); 
      Conn.setdoinput (TRUE); 
      Conn.connect (); is = conn.getInputStream (); 
    Bitmap = Bitmapfactory.decodestream (IS); 
        The catch (Exception e) {try {if (is!= null) {is.close (); 
      } catch (IOException E1) {e1.printstacktrace (); 
    } e.printstacktrace (); 
  return bitmap; 
  Public Bitmap getimageinmemory (Nmoment moment) {return getimageinmemory (moment, ""); /** * New interface, can be tagged according to tag moment, so you can expand the application scene, such as the first page needs large map, into the phase set page need small figure * @param moment * @param phototag * @r 
     
    Eturn */Public Bitmap getimageinmemory (nmoment moment, String phototag) {String id = moment.id + phototag; 
    Bitmap bmp = null; 1. 
    Get BMP = Getfromfirstlevelcache (ID) from a level cache; 
      if (BMP!= null &&!bmp.isrecycled ()) {LOGHELPER.E ("Imageloaderengine", "Level cache Fetch:" +id); 
    return BMP; }//2. 
    Get BMP = Getfromsecondlevelcache (ID) from level two cache; if (BMP!= null &&!bmp.isrecycled ()) {LOGHELPER.E ("Imageloaderengine", "Level two cache access:" +ID; 
    return BMP; 
    } if (BMP!= null && bmp.isrecycled ()) {return null; 
    else {return BMP; 
  } public void SetImage (String key,bitmap picture) {Mfirstlevelcache.put (key, picture); 
  /** * Get picture/public Bitmap getImage (Nmoment moment) {return GetImage (moment, ""); 
    Public Bitmap GetImage (nmoment moment, String phototag) {String id = moment.id + phototag; 
    Bitmap bmp = null; 1. 
    Get BMP = Getfromfirstlevelcache (ID) from a level cache; 
      if (BMP!= null &&!bmp.isrecycled ()) {LOGHELPER.E ("Imageloaderengine", "Level cache Fetch:" +id); 
    return BMP; }//2. 
    Get BMP = Getfromsecondlevelcache (ID) from level two cache; 
      if (BMP!= null &&!bmp.isrecycled ()) {LOGHELPER.E ("Imageloaderengine", "Level two cache Fetch:" +id); 
    return BMP; }//3. 
    Obtain BMP = Getfromsdcache (moment, Phototag) from SD card cache; if (BMP!= null &Amp;&!bmp.isrecycled ()) {LOGHELPER.E ("Imageloaderengine", "SD card Cache Capture:" +id); 
    return BMP; }//4.  
Obtain loadimagebymoment from the network (moment, Phototag); 
     
    LOGHELPER.E ("Imageloaderengine", "Local get Picture failed:" +moment.id+ "=" +moment.getpicture ()); 
    if (BMP!= null && bmp.isrecycled ()) {return null; 
    else {return BMP; 
    } public Bitmap getImage (String key,string URL) {Bitmap bmp = null; 1. 
    Get BMP = Getfromfirstlevelcache (key) from the first cache; 
    if (BMP!= null &&!bmp.isrecycled ()) {return BMP; }//2. 
    Get BMP = Getfromsecondlevelcache (key) from level two cache; 
    if (BMP!= null &&!bmp.isrecycled ()) {return BMP; }//3. 
    Obtain BMP = Getfromsdcachebykey (key,0) from SD card cache; 
    if (BMP!= null &&!bmp.isrecycled ()) {return BMP; }//4. 
     
    Obtain Loadimagebyurl (key, url,0) from the network; if (BMP!= null && bmp.isrecycled ()) {return null 
    else {return BMP; /** * First cache get Picture * * @param imgid * @return/private Bitmap Getfromfirstlevelcache (St 
    Ring imgid) {Bitmap Bitmap = null; 
      Synchronized (mfirstlevelcache) {bitmap = Mfirstlevelcache.get (Imgid); 
        if (bitmap!= null) {mfirstlevelcache.remove (imgid); 
      Mfirstlevelcache.put (Imgid, bitmap); 
  } return bitmap; /** * Level Two cache get picture * * @param URL * @return/private Bitmap getfromsecondlevelcache (String img 
    Id) {Bitmap Bitmap = null; 
    softreference<bitmap> softreference = Msecondlevelcache.get (Imgid); 
      if (softreference!= null) {bitmap = Softreference.get (); 
      if (bitmap = = null) {msecondlevelcache.remove (imgid); 
  } return bitmap; /** * get picture from SD card cache and put it in a first cache * * @param moment * @return * @throws ioexception * * Private B Itmap GetfromsdcachE (final nmoment moment,final String phototag) {Bitmap drawable = null; 
     
    String id = moment.id + phototag; 
     
    String Sdcacheingpath = Iohelper.getcachedpicturepath (global.packagename, id); 
    String Sdcacheedpath = Sdcacheingpath + ". png"; if (moment.islocal) {if (Moment.isvideo ()) {//get local path Sdcacheedpath = Moment.getpicture (Global.widt 
      HPIXELS/3*2); 
      else {sdcacheedpath = Moment.local_res_path; 
    } File cachefile = new file (Sdcacheedpath); 
      if (!cachefile.exists ()) {//exit LOGHELPER.E if no cache is complete ("Imageloaderengine", "cache file not found:" +sdcacheedpath); if (! 
        Textutils.isempty (Moment.local_res_path)) {//If there are pictures locally, replace Sdcacheedpath = Moment.local_res_path with local pictures first; 
        Cachefile = new File (Sdcacheedpath); if (cachefile.exists () &&! GlobalData.PHONE_MANUFACTURER.equalsIgnoreCase ("Samsung")) {LOGHELPER.E ("Imageloaderengine", "AK47 ...:" +globald Ata. PHone_manufacturer)//First find a local replacement picture. New Thread (New Runnable () {//downloads from the network @Override public void Run () {Loadimagebymome  
            NT (moment, Phototag); 
          }). Start (); 
        Return Getfitphoto (Sdcacheedpath, moment, cachefile); 
        else {return null; 
      } else {return null; 
 
    } drawable = Getfitphoto (Sdcacheedpath, moment, cachefile); if (drawable!= null) {if (moment.orientation!= 0) {drawable = Viewhelper. Rotatebitmap (Mo 
      Ment.orientation, drawable); 
      } if (Mfirstlevelcache!= null) {mfirstlevelcache.put (ID, drawable); 
    } else {cachefile.delete (); 
  return drawable; 
    Private Bitmap Getfitphoto (String sdcacheedpath,nmoment moment,file cachefile) {FileInputStream fs = null; 
    Bitmap result; try {bitmapfactory.options Options = new BitMapfactory.options (); 
      Options.injustdecodebounds = true; 
      Bitmapfactory.decodefile (Sdcacheedpath, Options); int hratio = (int) Math.ceil (Options.outheight/(float) moment.picture_height); Count height int wratio = (int) Math.ceil (Options.outwidth/(float) global.widthpixels);  Calculate width if (hratio > 1 | | wratio > 1) {if (Hratio > Wratio) {options.insamplesize = 
        Hratio; 
      else options.insamplesize = Wratio; 
      } options.inpurgeable = true; 
      Options.ininputshareable = true; 
      Options.indither = false; 
 
      Options.injustdecodebounds = false; 
      try {fs = new FileInputStream (cachefile); 
      catch (FileNotFoundException e) {e.printstacktrace (); 
    result = Bitmapfactory.decodefiledescriptor (FS.GETFD (), null, options); 
    catch (Exception e) {throw new RuntimeException (e); finally {IF (fs!= null) {try {fs.close (); 
        catch (IOException e) {e.printstacktrace (); 
  }} return result; 
    Private Bitmap Getfromsdcachebykey (String key,int orientation) {Bitmap = null; 
     
    FileInputStream fs = null; 
     
    String Sdcacheedpath = Iohelper.getcachedpicturepath (Global.packagename, key) + ". png"; 
    File Cachefile = new file (Sdcacheedpath); 
    if (!cachefile.exists ()) {//exit return NULL if no cache is completed; 
      try {bitmapfactory.options Options = new Bitmapfactory.options (); 
      Options.injustdecodebounds = true; 
      Bitmapfactory.decodefile (Sdcacheedpath, Options); int wratio = (int) Math.ceil (Options.outwidth/(float) global.widthpixels); 
      Calculate width options.insamplesize = wratio; 
      Options.inpurgeable = true; 
      Options.ininputshareable = true; 
      Options.indither = false; Options.injustdecodebouNDS = FALSE; 
      try {fs = new FileInputStream (cachefile); 
      catch (FileNotFoundException e) {e.printstacktrace (); 
 
      } drawable = Bitmapfactory.decodefiledescriptor (FS.GETFD (), null, options); if (drawable!= null) {if (orientation!= 0) {drawable = Viewhelper.rotatebitmap (Orientation, drawabl 
        e); 
      } mfirstlevelcache.put (key, drawable); 
      else {cachefile.delete (); 
    The catch (Exception e) {throw new RuntimeException (e); 
        finally {if (fs!= null) {try {fs.close (); 
        catch (IOException e) {e.printstacktrace (); 
  }} return drawable; 
    /** * Create a gray default figure * @param moment * @return/public Bitmap Getdefaultbitmap (Nmoment moment) { Return Imagehelper.createbitmap (Moment.picture_width, Moment.picture_height, R.color.image_bg_daiLY); /** * Save bitmap file to sd card, pass in JPG end path * @param filePath * @param mbitmap/public void Savebitmapto 
 
      File (String FilePath, Bitmap mbitmap) {try {File file = new file (FilePath); 
      if (!file.getparentfile (). exists ()) {File.getparentfile (). Mkdirs (); 
        } if (File.exists () && file.length () > 0) {Long currenttime = System.currenttimemillis (); 
              if ((Currenttime-file.lastmodified ()) > 2 * 1000) {LOGHELPER.E ("Imageloaderengine"), 
          "2 minutes have not finished downloading, ready to delete it ..." + currenttime + "=" + file.lastmodified ()); 
        File.delete (); 
        else {return; 
      } else {file.createnewfile (); 
      } FileOutputStream fout = null; 
      Fout = new FileOutputStream (file); 
      Mbitmap.compress (Bitmap.CompressFormat.JPEG, fout); 
      Fout.flush (); 
       
      Fout.close (); File.renameto (New File(filepath+ ". png")); 
      catch (Exception e) {e.printstacktrace (); 
    LOGHELPER.E ("Imageloaderengine", "Save Picture Error:" +e); 
  } LOGHELPER.E ("Imageloaderengine", "Save network Picture successfully" +filepath+ ". png"); 
   /** * Save file to cache, rewrite here instead of iohelper inside because Iohelper is too complex * * @param URL * @param filePath * @return 
        */Public boolean saveurlbitmaptofile (string URL, string filePath) {if (Textutils.isempty (FilePath)) { 
      return false; 
    } File IconFile = new file (FilePath); 
    if (iconfile.getparentfile () = = null) {return false; 
    } if (!iconfile.getparentfile (). exists ()) {Iconfile.getparentfile (). Mkdirs (); } if (Iconfile.exists () && iconfile.length () > 0) {Long currenttime = System.currenttimemillis () 
      ; if (currenttime-iconfile.lastmodified ()) >2 * 1000) {LOGHELPER.E ("Imageloaderengine", "2 minutes has not been downloaded, ready to delete it.") ." 
        +currenttime+ "=" +iconfile.lastmodified ()); IconfilE.delete (); 
      else {return true; 
    } FileOutputStream fos = null; 
    InputStream is = null; 
      try {fos = new FileOutputStream (FilePath); 
 
      is = new URL (URL). OpenStream (); 
      int data = Is.read (); 
        while (data!=-1) {fos.write (data); 
      data = Is.read (); 
      catch (IOException e) {loghelper.e ("Imageloaderengine", "Imageloaderengine download picture error" + E); 
      Iconfile.delete (); 
      E.printstacktrace (); 
    return false; 
        Finally {try {if (is!= null) {is.close (); 
        } if (fos!= null) {fos.close (); 
      } catch (IOException e) {e.printstacktrace (); 
    } iconfile.renameto (New File (filepath+. png)); 
  return true; /** * Scaling Bitmap * @param bmp * @param scaledvalue Scaling value * @return/public Bitmap Scaledbitma P (Bitmap bmp,int scaledvalue) {int Bmpwidth = bmp.getwidth (); 
     
    int bmpheight = Bmp.getheight (); 
      if (bmpwidth >= bmpheight) {//Horizontal map Bmpwidth = (bmpwidth * scaledvalue/bmpheight); 
    Bmpheight = Scaledvalue; 
      else {bmpheight = (Bmpheight * scaledvalue/bmpwidth); 
    Bmpwidth = Scaledvalue; 
    } Bitmap scaledbmp = Bitmap.createscaledbitmap (bmp,bmpwidth,bmpheight,true); 
    Bmp.recycle (); 
     
    BMP = NULL; 
  return scaledbmp; 
 } 
}

The above is a complete Android image loading cache class, I hope to help you learn.

Related Article

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.