Asynchronous loading of Android Images

Source: Internet
Author: User

Develop androidProgramGenerally, there are two operations: asynchronous loading and caching of images, while asynchronous loading of images mostly reads images from the Network (and also generates local image thumbnails ), to reduce network operations and accelerate image loading, You Need To Cache images. Therefore, many asynchronous loading methods on the Internet are closely related to image caching. However, users may already have a cache-related class library, which may be a little troublesome to use.

Recently, I used to handle image-related problems. I used to load my own images. However, some status controls are annoying, such as the reuse of imageview during listview scrolling, therefore, in the spirit of being lazy and making full use of existing resources, attackers can collect images and load them asynchronously.CodeFinally, find one in the greendroid UI library. One of the custom views of asyncimageview is used to asynchronously load images. However, like most images on the Internet, it is associated with the image cache, but it is only a simple memory cache with no file cache. The image loading method is also writable like other methods, which limits the scope of use and can only decode the image through inputstream, asynchronous processing like generating thumbnails or some other image processing cannot be used. Modifying an existing class library is always easier than writing it from the beginning, so asyncimageview is slightly modified so that it can customize the cache and image loading methods. asyncimageview is only slightly modified, mostly others source code.

1. Core class

Imageloader: Core class for image loading. images are loaded using a thread pool internally.

Imagerequest: indicates an image loading request.

Asyncimageview: asynchronously loads a view for a custom image.

Loadmethod: interface for customizing the image loading method. You can use this interface to customize the image loading method.

Cachecallback: cache interface, which can be used to read and write the cache

Asyncimageview. onimageviewloadlistener: Listener of image loading status (START, fail, end)

2. Image Loading Method
 Public   Void  Run () {process. setthreadpriority (process. thread_priority_background );  Final Handler H = Mhandler; Bitmap bitmap = Null  ; 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 loading method, use the custom method.                  If (Mloadmethod! = Null  ) {Bitmap = Mloadmethod. Load (murl );}  Else  {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. startswith ("file :///" ) Murl = Murl. replacefirst ("file :///","/" ); Inputstream = New  Fileinputstream (murl );}  //  Network                     Else  {  //  When loading images using the URL class, it is found that the images obtained through inputstream resolution obtained through the URL class on some models are always null, so httpclient Httpget httprequest = New  Httpget (murl); httpclient = New  Defaulthttpclient (); httpparams = New  Basichttpparams (); httpconnectionparams. setconnectiontimeout (httpparams, 5000); Httpconnectionparams. setsotimeout (httpparams, 5000 ); Httprequest. setparams (httpparams); httpresponse response = (Httpresponse=httpclient.exe cute (httprequest); httpentity entity = Response. getentity (); bufferedhttpentity bufhttpentity = New  Bufferedhttpentity (entity); inputstream instream = Bufhttpentity. getcontent (); bufferedinputstream bi =New  Bufferedinputstream (instream); inputstream = Bi ;}  //  Although asyncimageview has the bitmapfactory. Options method, the size of the image is generally unknown, so the corresponding insamplesize cannot be calculated,  //  The corresponding bitmapfactory. options cannot be set, so it is better to customize the loadmethod according to your own needs. Bitmap = bitmapfactory. decodestream (inputstream, Null  , (Moptions = Null )?Sdefaultoptions: moptions); inputstream. Close ();}  If (Mbitmapprocessor! = Null & Bitmap! = Null  ){  Final Bitmap processedbitmap = Mbitmapprocessor. 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 failed" );} 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 loadmethod is customized, the corresponding method is called to load the image. If there is no custom method, the default loading method is used. You can load local images, asset images, and network images, the source code of greendroid uses URLs to load network images. However, we encountered a problem when loading network images. Some models always return NULL for the imputstream resolution image obtained through the URL class, so it is changed to httpclient.

3. Usage

Use the setpath method of asyncimageview to load images. setpath has three overload methods:

Public void setpath (string path)

Public void setpath (string path, loadmethod)

Public void setpath (string path, loadmethod, string cachekey)

The first parameter specifies the path of the image to be loaded, and the second parameter is the custom image loading method. If this parameter is not specified, the default value is used.

The third parameter is used for caching. Generally, the path of the image to be loaded is unique. Therefore, you can use the first parameter as the cache key, however, there are also special cases, such as reading pictures in the LAN, generally the IP address is automatically obtained, so it may be inappropriate to use the image path as the cache key, therefore, you need to manually specify the key used as the cache as needed.

 /**  * Set the path of the image to be loaded, which can be the network path, asset file path (File: // android_asset), and local image path (File: // or /)**  @ Param  Path: Path of the image to be loaded. If it is null, the default image is loaded *  @ Param Loadmethod: the custom image loading method. It can be null. Use the default Loading Method *  @ Param  Cachekey cache key  */      Public   Void  Setpath (string path, loadmethod, string cachekey ){  //  Check the URL has changed          If (Mbitmap! = Null & Path! = Null & Path. Equals (murl )){ // Todo mbitmap! = NULL necessary?              Return  ;} Stoploading (); murl = Path; mcachekey = Cachekey; mloadmethod = Loadmethod;  //  Setting the URL to an empty string force the displayed image to  //  Default Image          If  (Textutils. isempty (murl) {mbitmap =Null  ; Setdefaultimage ();}  Else  {  If (! Mpaused) {reload ();}  Else  {  //  We're 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 may 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 & Amp; imageloader. getinstance (). getcache () = Null ) {Imageloader. getinstance (). setcache (mcache );}} 

Readcache () is used to read the cache. The Code is as follows:

 
PrivateBitmap readcache (){If(Mcache! =Null)ReturnMcache. readcache (textutils. isempty (mcachekey )?Murl: mcachekey );Return Null;}

The mcache allows you to set a custom cache method through setcachecallback (cachecallback callback), so that you can use the existing cache to load and cache images. If you want to specify the cache key, use the key specified by the user; otherwise, use the image path as the key.

4. Other important methods in asyncimageview

Reload ([Boolean force]): Reload

Stoploading (): stops loading. If loading is currently in progress, it will not work. If the loading task is in the loading thread pool queue, it will be canceled.

Setdefaultimage... () Class Method: Set the default image.

Setpause (Boolean pause): whether to load the Graph

 

Source code download: asyncimage

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.