Original: http://www.cnblogs.com/angeldevil/archive/2012/09/16/2687174.html
Related: Https://github.com/nostra13/Android-Universal-Image-Loader
The development of Android programs, generally there will be two operations, the image of the asynchronous loading and caching, and the image of the asynchronous loading is mostly from the network to read pictures (and generate local image thumbnails and other operations), in order to reduce network operation, speed up the picture loading speed will need to cache the picture, So many pictures on the Internet asynchronous loading methods are closely related to the cache of the picture. But it's also possible that users already have a library of related libraries for caching, which can be a bit cumbersome to use.
The recent paragraph dealing with the picture-related problems, it was originally written by the picture loading, but some state control is more annoying, such as the ImageView of the ListView when scrolling, so in the lazy and full use of the existing resources of the attitude to the Internet to pick up the image asynchronous loading code, Eventually found in the Greendroid UI library, where a Asyncimageview custom view is used to load the picture asynchronously, but like most images on the web, it is associated with the cache of the image, but it's a simple memory cache with no file cache. The loading method of the picture is also written dead like the others, which limits its scope of use and can only be decode by inputstream, whereas asynchronous processing like generating thumbnails or some other image processing cannot be used. Modifying the existing class library is always easier than writing from scratch, so slightly modified the next asyncimageview, so that it can customize the cache and image loading method, for Asyncimageview only a little bit of modification, mostly others source code.
1. Core class
- Imageloader: Image loading core class, internal use line Cheng download image
- Imagerequest: Represents a request for a picture load
- Asyncimageview: Custom image loading View asynchronously
- Loadmethod: interface for customizing the image loading method, which can be implemented by implementing this interface to customize the loading method of the picture
- Cachecallback: Cache interface, can be implemented by implementing this interface to read and write to the cache
- Asyncimageview.onimageviewloadlistener: Picture loading status monitoring (start, fail, end)
2. Image Loading method
public void Run () {process.setthreadpriority (process.thread_priority_background); Final Handler h = mhandler; Bitmap Bitmap = null; Throwable throwable = null; H.sendmessage (Message.obtain (H, On_Start)); try {if (Textutils.isempty (Murl)) {throw new Exception ("The given URL cannot be null or empty"); }//If you have customized the Load method, use the custom method if (Mloadmethod! = null) {bitmap = Mloadmethod.load (Murl); } else {InputStream inputstream = null; Asset if (Murl.startswith ("file:///android_asset/")) {InputStream = Sassetmanager.open (Murl. Replacefirst ("file:///android_asset/", "")); }//File else if (Murl.startswith ("file:///") | | | Murl.startswith ("/")) {if (murl.st Artswith ("file:///")) Murl = Murl.replacefirst ("file:///", "/"); InputStream = new FileInputStream (Murl); }//NetWork else {//when loading a picture with a URL class, it is found that the image obtained by the InputStream parse obtained by the URL class above is always null, so use HTT Pclient HttpGet HttpRequest = new HttpGet (Murl); HttpClient HttpClient = new Defaulthttpclient (); Httpparams httpparams = new Basichttpparams (); Httpconnectionparams.setconnectiontimeout (Httpparams, 5000); Httpconnectionparams.setsotimeout (Httpparams, 5000); Httprequest.setparams (Httpparams); HttpResponse response = (HttpResponse) httpclient.execute (HttpRequest); httpentity entity = response.getentity (); Bufferedhttpentity bufhttpentity = new bufferedhttpentity (entity); InputStream instream = Bufhttpentity.getcontent (); Bufferedinputstream bi = new Bufferedinputstream (instream); InputStream = bi; }//Although there is a way to set bitmapfactory.options in Asyncimageview, the size of the picture is generally unknown, it is not possible to calculate the correspondingInsamplesize,//Can not set the corresponding bitmapfactory.options, so the general situation or according to their own needs to customize Loadmethod for good bitmap = Bitmapfact Ory.decodestream (InputStream, null, (moptions = = null)? sdefaultoptions:moptions); Inputstream.close (); } if (mbitmapprocessor = null && bitmap! = null) {final bitmap processedbitmap = mbitmapproces Sor.processimage (bitmap); if (processedbitmap! = null) {bitmap.recycle (); bitmap = Processedbitmap; }}} catch (Exception e) {log.e (Log_tag, "Error while fetching image", e); Throwable = e; if (bitmap = = null) {if (Throwable = = null) {throwable = new Exception ("Skia image decoding Faile D "); } h.sendmessage (Message.obtain (H, On_fail, Throwable)); } else {h.sendmessage (Message.obtain (H, On_end, bitmap)); if (Mcache! = null) {Mcache.writecache (textutils.isemptY (mcachekey)? Murl:mcachekey, bitmap); } }}
If the custom Loadmethod, will call the appropriate method to load the picture, if there is no custom, will use the default loading method, you can load local pictures, asset pictures and network pictures, greendroid source code to load the network image is the URL, But we have encountered a problem when loading network pictures, some models obtained by the URL class Imputstream resolution image always return NULL, so it was changed to HttpClient.
3. How to use
With the Asyncimageview SetPath method to load a picture, SetPath has 3 overloaded methods:
- public void SetPath (String path)
- public void SetPath (String path, Loadmethod loadmethod)
- public void SetPath (string path, Loadmethod Loadmethod, String cacheKey)
The first parameter specifies the path to the picture to be loaded, and the second parameter is a custom picture loading method, with the default if not specified.
As for the third parameter, is to do the cache, generally to load the path of the picture is unique, so the general use of the first parameter as a cache key on the line, but there are special cases, such as reading the local area network pictures, generally are automatically acquired IP, so according to the picture path as the cache key may be inappropriate , you need to manually specify the key to use as the cache as needed.
/** * Sets the path of the picture to be loaded, can be a network path, asset file path (file:///android_asset), local picture path (file:///or/) * * @param path of the image to be loaded in path, if Null loads the default picture * @param loadmethod A custom picture loading method, which can be null, using the default Load method * @param cacheKey Cache key */public void SETPA Th (string path, Loadmethod Loadmethod, String cacheKey) {//Check the URL has changed if (Mbitmap! = null & amp;& path! = null && path.equals (Murl)) {//TODO Mbitmap! = null necessary? Return } stoploading (); Murl = path; Mcachekey = CacheKey; Mloadmethod = Loadmethod; Setting the URL to a empty string force the displayed image to the//default image if (textutils.isempt Y (Murl)) {mbitmap = null; Setdefaultimage (); } else {if (!mpaused) {reload (); } else {//We ' re paused:let ' s look in a synchronous and efficient cache//prior using the Default image. Mbitmap = Readcache (); TODO may consume time if (mbitmap! = null) {Setimagebitmap (MBITMAP); } else {setdefaultimage (); } } } }
public void Reload (Boolean force) { if (mrequest = = NULL && Murl! = null) { //Prior Downloading the image ... let's look in a cache! Mbitmap = null; if (!force) { //This could take a long time. Mbitmap = Readcache (); } if (mbitmap! = null) { setimagebitmap (mbitmap); return; } Setdefaultimage (); Mrequest = new Imagerequest (Murl, this, Mimageprocessor, Moptions, Mcachekey); Mrequest.load (GetContext (), mloadmethod); if (imageloader.getinstance () = null && imageloader.getinstance (). GetCache () = = null) { Imageloader.getinstance (). Setcache (Mcache); } }
Readcache () is used to read the cache with the following code:
Private Bitmap Readcache () { if (mcache! = null) return Mcache.readcache (Textutils.isempty (mcachekey)? MURL:MC Achekey); return null; }
The Mcache user can Setcachecallback (Cachecallback callback) to set the user-defined caching method, so that the load of the picture and cache separated, so that users can use the existing cache implementation. If you want the user to specify the cache key to use the user-specified key, otherwise the path of the picture as key.
Other important methods in 4.AsyncImageView
- Reload ([Boolean force]): Reload
- Stoploading (): Stops loading if it is currently loading and has no effect if the load task is canceled in the load thread pool queue.
- Setdefaultimage ... () class method: Sets the default picture.
- Setpause (Boolean pause): Whether the picture is loaded
SOURCE Download: Asyncimage
Android Images Asynchronous loading