Android implementation picture asynchronous request plus level three cache _android

Source: Internet
Author: User
Tags md5 parent directory static class

The use of Xutils framework is very convenient, but today to use code to achieve Bitmaputils function, very simple,

Asynctask Request a picture

### #AsyncTask

# # # # # # # # # # # # # # #AsyncTask是线程池 +handler encapsulation The first generic: parameter type type of the argument (consistent with Doinbackground) the second generic:
# # # #更新进度的参数类型 (consistent with onprogressupdate) the third generic: Returns the parameter type of the result (consistent with OnPostExecute,
# #和doInBackground返回类型一致)

See Asynctask Source:

Public abstract class Asynctask<params, Progress, result> {
 private static final String Log_tag = "Asynctask"; 
   private static final int core_pool_size = 5;
 private static final int maximum_pool_size = 128;
 private static final int keep_alive = 1;

 private static final Threadfactory sthreadfactory = new Threadfactory () {
  private final atomicinteger mcount = new Ato Micinteger (1);

  Public thread Newthread (Runnable r) {return
   new Thread (R, "Asynctask #" + mcount.getandincrement ());
  }
 ;


Core thread 5 Max thread 128  This is the asynctask thread pool   then sends a message via Handler, which internally instantiates a static custom class Internalhandler, which inherits from Handler. In this custom class, an object called Asynctaskresult is bound, and each time a child thread needs to notify the main thread, it calls Sendtotarget to send the message to handler itself. Then in handler's Handlemessage asynctaskresult depending on the type of message (for example, message_post_progress updates the progress bar, Message_post_cancel To cancel a task and do different things, it is worth mentioning that these operations are performed on the UI thread, meaning that the handler object is automatically invoked on the main thread once the child thread is required to interact with the UI thread.

 private static final Internalhandler Shandler = new Internalhandler ();
    Mfuture = new Futuretask<result> (mworker) {@Override protected void more ... do () {message message;
    result result = NULL;
    try {result = get ();
    catch (Interruptedexception e) {ANDROID.UTIL.LOG.W (Log_tag, E);
       catch (Executionexception e) {throw new RuntimeException ("An error occured while executing doinbackground ()",
    E.getcause ()); catch (cancellationexception e) {message = Shandler.obtainmessage (Message_post_cancel, New asynctaskresult& Lt
     Result> (Asynctask.this, (result[)) (null));
     Message.sendtotarget ();
    Return catch (Throwable t) {throw new RuntimeException ("An error occured while executing" + "doinbackground ()", t
    ); Message = Shandler.obtainmessage (Message_post_result, New asynctaskresult<result> (Asynctask.this, Resul
    t));
   Message.sendtotarget ();
 }
  }; Private StatiC Class Internalhandler extends Handler {@SuppressWarnings ({"Unchecked", "Rawuseofparameterizedtype"}) @Override Pu
   Blic void More ... handlemessage (msg) {Asynctaskresult result = (Asynctaskresult) msg.obj; Switch (msg.what) {case Message_post_result://There be only one result Result.mTask.finish (result.mdata[0
     ]);
    Break
     Case MESSAGE_POST_PROGRESS:result.mTask.onProgressUpdate (Result.mdata);
    Break
     Case MESSAGE_POST_CANCEL:result.mTask.onCancelled ();
   Break
 }
  }
 }


Look at the first step of the code we first request a picture and parse the note written in detail.

Netcacheutils.java

Import Java.io.InputStream;
Import java.net.HttpURLConnection;

Import Java.net.URL;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.os.AsyncTask;

Import Android.widget.ImageView; 
 /** * Network Cache * * @author Ace * @date 2016-02-18/public class Netcacheutils {private Localcacheutils mlocalutils;

 Private Memorycacheutils mmemoryutils;
  Public Netcacheutils (Localcacheutils localutils, memorycacheutils memoryutils) {mlocalutils = LocalUtils;
 Mmemoryutils = memoryutils;
  public void Getbitmapfromnet (ImageView imageview, String URL) {bitmaptask task = new Bitmaptask ();
 Task.execute (ImageView, URL); /** * Asynctask is the wrapper of the thread pool +handler the first generic: parameter type type of the argument (and Doinbackground consistent) second generic: * Update progress parameter type (and onprogressupdate consistent) third generic: Returns the parameter type of the result (consistent with OnPostExecute, * and Doinbackground return type) * * Class Bitmaptask extends Asynctask<object, Integer, Bitmap
  > {private ImageView Mimageview;

  Private String URL; Main thread run, preload @Override protected void OnPreExecute () {super.onpreexecute ();  //Child threads run, asynchronous load logic is handled in this method @Override protected Bitmap doinbackground (Object ... params) {Mimageview = (ImageView)
   Params[0];
   url = (String) params[1];
  Mimageview.settag (URL);//bind ImageView and URL together//publishprogress (values)//Notify progress//Download picture return download (URL);
  }//Main thread run, update progress @Override protected void onprogressupdate (Integer ... values) {super.onprogressupdate (values); }//Main thread run, update main interface @Override protected void OnPostExecute (Bitmap result) {if (result!= null) {//judge the current picture is
    No is the picture ImageView want to prevent ListView reuse caused by the image of the disorder occurs string bindurl = (string) mimageview.gettag ();
 if (bindurl.equals (URL)) {//to ImageView set the picture Mimageview.setimagebitmap (result);

     Save the picture in the local mlocalutils.setbitmaptolocal (result, URL);
    Save the picture in memory mmemoryutils.setbitmaptomemory (URL, result); /** * Download picture * * @param url/public Bitmap download (String URL) {HttpURLConnection conn = null;

   try {conn = (httpurlconnection) (new URL (URL). OpenConnection ());
   Conn.setconnecttimeout (5000);
   Conn.setreadtimeout (5000);

   Conn.setrequestmethod ("get");

   Conn.connect ();
   int responsecode = Conn.getresponsecode ();
    if (Responsecode =) {InputStream in = Conn.getinputstream ();
    Converts the flow into a Bitmap object Bitmap Bitmap = Bitmapfactory.decodestream (in);
   return bitmap;
  } catch (Exception e) {e.printstacktrace ();
   finally {if (conn!= null) {conn.disconnect ();
 } return null;
 }

}


memorycacheutils.java  used LRUCache is very simple
I simply translate the document:

* A cache that holds strong references to a limited number of values. Each time * A value was accessed, it is moved to the head of a queue. When a value was * added to a full cache, the value at the "end of" \ Evicted and may * become eligible for GA 

Rbage collection.
* Cache saves a strong reference to limit the amount of content, and whenever item is accessed, the item is moved to the head of the queue.
* When a new item is added when the cache is full, the item at the end of the queue is reclaimed. 
* <p>if your cached values hold resources this need to be explicitly released, * override {@link #entryRemoved}. * If a value of your cache needs to be explicitly released, rewrite entryremoved () * <p>by default, the cache size is measured in the number of entries. Override * {@link #sizeOf} to size of the cache in different units.

 For example, this cache * was limited to 4MiB of bitmaps: The default cache size is the number of item measurements, and the rewrite sizeof calculates the size of the different item. {@code * int cacheSize = 4 * 1024 * 1024;//4MiB * lrucache<string, bitmap> bitmapcache = new Lrucache<strin G, bitmap> (cacheSize) {* protected int sizeOf (String key, Bitmap value) {* return Value.getbytecount (); *} *}}-------------------------------------------------------------------<p>this class is Thread-safe. Perform multiple cache operations atomically by * Synchronizing on the cache: <pre> {@code * synchronized (cache) 
{* IF (cache.get (key) = = null) {* CACHE.PUT (key, value);  *}}</pre> * He is thread-safe, performs multiple cache operations automatically and locks-------------------------<p>this class does not allow NULL to be used as a key or value. A return * value of NULL from {@link #get}, {@link #put} or {@link #remove} are * unambiguous:the key ' "
He.

 * Do not allow key or value NULL * when get (), put (), remove () return value is NULL, key corresponding item is not in cache

The most important thing is probably the above: use it very simply
to see the code:

 import android.graphics.Bitmap; import Android.support.v4.util.LruCache;  /** * Memory Cache Tool Class * * @author Ace * @date 2016-02-19/public class Memorycacheutils {//Android 2.3 (API level//

 9) Start, the garbage collector will be more inclined to reclaim the object holding soft references or weak references, which makes soft references and weak references become no longer reliable, it is recommended to use LruCache, it is strong reference private lrucache<string, bitmap> Mcache; Public memorycacheutils () {int maxmemory = (int) runtime.getruntime (). MaxMemory ()//Get maximum memory allocated by virtual machine//16 M//LRU The least recent use, by controlling the memory not exceeding the maximum value (specified by the developer), to solve the memory overflow, as the above translation says if the cache is full, it cleans up the least recently used cached object mcache = new lrucache<string, Bit Map> (MAXMEMORY/8) {@Override protected int sizeOf (String key, Bitmap value) {//computes the size of a Bitmap int siz
   E = value.getrowbytes () * value.getheight ();//The number of bytes per line multiplied by the height return size;
 }
  };
 Public Bitmap getbitmapfrommemory (String URL) {return mcache.get (URL);
 public void setbitmaptomemory (String url, Bitmap Bitmap) {mcache.put (URL, Bitmap); }

}


The last level cache local cache saves the picture file name of the network download as MD5 to the memory card's development directory

/** * Local Cache Tool Class * * @author Ace * @date 2016-02-19/public class Localcacheutils {//Picture cached folder public static fin

 Al String dir_path = environment. getExternalStorageDirectory (). GetAbsolutePath () + "/ace_bitmap_cache";

   Public Bitmap getbitmapfromlocal (String url) {try {file file = new File (Dir_path, Md5encoder.encode (URL));
    if (file.exists ()) {Bitmap Bitmap = Bitmapfactory.decodestream (new FileInputStream (file));
   return bitmap;
  } catch (Exception e) {e.printstacktrace ();
 return null;

  public void Setbitmaptolocal (Bitmap Bitmap, String url) {File Dirfile = new File (Dir_path); Create a folder if the folder folder does not exist or it is not a folder. Mkdirs,mkdir the difference is that if a folder has several layers of paths, the former creates a missing parent directory which does not create these parent directories if (!dirfile.exists () | |!
  Dirfile.isdirectory ()) {dirfile.mkdirs ();
   try {File File = new file (Dir_path, Md5encoder.encode (URL)); Save picture compression locally, parameter 1: Compressed format, Parameter 2: Compression quality (0-100), Parameter 3: output stream bitmap.compress (compressformat.jpeg, New fileoutputsTream (file));
  catch (Exception e) {e.printstacktrace ();

 }
 }

}

Md5encoder

Import Java.security.MessageDigest;

public class Md5encoder {public
 
 static string encode (string string) throws Exception {
  byte[] hash = messagediges T.getinstance ("MD5"). Digest (String.getbytes ("UTF-8"));
  StringBuilder hex = new StringBuilder (Hash.length * 2);
  for (byte b:hash) {
   if ((b & 0xFF) < 0x10) {
    hex.append ("0");
   }
   Hex.append (integer.tohexstring (b & 0xFF));
  }
  return hex.tostring ();
 }

Finally, create a new tool class to use our top three caching methods

/** * Level Three Cache tool class * * @author Ace * @date 2016-02-19/public class Mybitmaputils {//Network Cache tool class private Netcacheutil
 s mnetutils;
 Local Cache tool class private localcacheutils mlocalutils;

 Memory Cache Tool class private memorycacheutils mmemoryutils;
  Public Mybitmaputils () {mmemoryutils = new memorycacheutils ();
  Mlocalutils = new Localcacheutils ();
 Mnetutils = new Netcacheutils (mlocalutils, mmemoryutils); public void display (ImageView imageview, String URL) {//Set default loading picture Imageview.setimageresource (r.drawable.news_pic_

  Default);
  Load Bitmap Bitmap = mmemoryutils.getbitmapfrommemory (URL) from the memory cache first;
   if (bitmap!= null) {Imageview.setimagebitmap (bitmap);
   System.out.println ("read pictures from memory ...");
  Return
  }//Then load bitmap = mlocalutils.getbitmapfromlocal (URL) from the local cache;
   if (bitmap!= null) {Imageview.setimagebitmap (bitmap);
   System.out.println ("read the picture from the local ...");
   Set the picture mmemoryutils.setbitmaptomemory (URL, bitmap) to the memory;
  Return }//Load Mnetutils.getbitmapfro from the network cacheMNet (ImageView, URL);

 }

}

The above is the entire contents of this article, I hope to learn more about Android software programming help.

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.