Android image cache Processing Method

Source: Internet
Author: User
Tags md5 digest md5 hash

of the challenges of developing for mobile devices is making your app run fast, even though it only has very limited capabilities. this is the problem we'll be adressing in this post, or to be more exact, We'll be adressing how to get your images fast and efficient on a mobile device. now obviously you can't get your image faster than the device's connection allows, but you can make sure you're Not waiting for downloads that you don't have to wait. this is where the image cache comes in. if you have an image, why not just reuse it when requesting it for the second time? Of course there are situations where this sort of behaviour is not wanted (for example, when the image on the server has changed), but mostly it will save you time, bandwidth and battery.

so what shoshould you take into account when implementing an image cache? Well, first of all, we want to store the images locally beyond the runtime of our cache. so we'll store them on the phone. we do this because most apps only run for a few minutes, meaning that the user will probably only request the image once (making our cache only part of the problem !). Secondly we want to store them in memory, for faster access on the second call. basically, we want to download an image once, store it in memory and on the phone and the next time the image is requested we'll just get it from the local file into memory and we're re done. now we cocould implement a background thread to refresh the image too, giving the cached image first and later returning the newly loaded image. personally, though, I prefer to use a timeout, simply because it prevents us from having to download the image everty time anyway, and that's exactly what we're re trying to prevent: P

I shoshould note that the image cache used in this tutorial is focussed on the Android 1.6 platform, but it can be easily converted into any other Java platform by replacing the drawable class with any other image class. also, at some points I'll go into some really minor details, so if you don't feel like reading the whole thing don't be afraid to skip a piece here and there

The imagecache class will be obviusly be a final Singleton class, to make it accessible from all places. we'll use hashmaps to store the image data with the hashed URL as the key, this way we'll be able to easily access the cached data using the URL passed by the request. as said earlier, we'll also be storing the images on the phone, using the same hash as the file name, this "naming convention" is mostly for usage of use (as you'll see later ).

Synchronization is very important when writing any kind of cache, as we obviously want it to be thread safe and we'll be doing some asyncronous loading ourselves to make matters even worse. there are two things we need to synchronize: requests for the same URL and access to the cache hashmap.

And now for the code. I'll be giving you the full code first and then go into the juicy details.

Package utils; import android. content. context; import android. graphics. drawable. drawable; import android. util. log; import Java. io. file; import Java. io. fileoutputstream; import Java. io. inputstream; import Java. lang. ref. weakreference; import Java. math. biginteger; import java.net. URL; import Java. security. messagedigest; import Java. security. nosuchalgorithmexception; import Java. util. arraylist; import Java. util. dat E; import Java. util. hashmap; import Java. util. list; import Java. util. random;/*** the imagecache class can be used to download images and store them in the * cache directory of the device. multiple requests to the same URL will result * in a single download, until the cache timeout has passed. * @ author Thomas vervest */public class imagecache {/*** the imagecallback interface defines a single meth Od used to pass an image * Back To The Calling object when it has been loaded. */public static interface imagecallback {/*** the onimageloaded method is called by the imagecache when an image * has been loaded. * @ Param image the requested image in the form of a drawable object. * @ Param URL the originally requested URL */void onimageloaded (drawable image, string URL);} Private Static imageca Che _ instance = NULL;/*** gets the singleton instance of the imagecache. * @ return the imagecache. */Public synchronized static imagecache getinstance () {If (_ instance = NULL) {_ instance = new imagecache () ;}return _ instance ;} private Static final long cache_timeout = 60000; private final object _ Lock = new object (); Private hashmap <string, weakreference <drawable> _ cache; private hashmap <String, list <imagecallback> _ callbacks; private imagecache () {_ cache = new hashmap <string, weakreference <drawable> (); _ callbacks = new hashmap <string, list <imagecallback> ();} private string gethash (string URL) {try {messagedigest digest = messagedigest. getinstance ("MD5"); Digest. update (URL. getbytes (); return New biginteger (Digest. digest ()). tostring (16);} catch (nosuchalgorithmexception ex) {// This shoshould never happen, but just to make sure return the URL return URL;} private drawable drawablefromcache (string URL, string hash) {drawable d = NULL; synchronized (_ Lock) {If (_ cache. containskey (hash) {weakreference ref = _ cache. get (hash); If (Ref! = NULL) {d = ref. get (); If (D = NULL) _ cache. remove (hash) ;}}return D;} private drawable loadsync (string URL, string hash, context) {drawable d = NULL; try {d = drawablefromcache (URL ); file F = new file (context. getcachedir (), hash); Boolean timeout = f. lastmodified () + cache_timeout <new date (). gettime (); If (D = NULL | timeout) {If (timeout) F. delete (); If (! F. exists () {inputstream is = new URL (URL + "? Rand = "+ new random (). nextint ()). openconnection (). getinputstream (); If (F. createnewfile () {fileoutputstream fo = new fileoutputstream (f); byte [] buffer = new byte [256]; int size; while (size = is. read (buffer)> 0) {fo. write (buffer, 0, size);} fo. flush (); FO. close () ;}d = drawable. createfrompath (F. getabsolutepath (); synchronized (_ Lock) {_ cache. put (hash, new weakreference (D) ;}} catch (Exception ex) {log. E (getclass (). getname (), Ex. getmessage (), Ex);} return D;}/*** loads an image from the passed URL and callthe callback method when * the image is done loading. * @ Param URL the URL of the target image. * @ Param callback A imagecallback object to pass the loaded image. if null, * the image will only be pre-loaded into the cache. * @ Param context the context of the new Dra Wable image. */Public void loadasync (final string URL, final imagecallback callback, final context) {final string hash = gethash (URL); synchronized (_ Lock) {list callbacks = _ callbacks. get (hash); If (callbacks! = NULL) {If (callback! = NULL) Callbacks. Add (callback); return;} callbacks = new arraylist (); If (callback! = NULL) callbacks. add (callback); _ callbacks. put (hash, callbacks);} new thread (New runnable () {@ override public void run () {drawable d = loadsync (URL, context); List callbacks; synchronized (_ Lock) {callbacks = _ callbacks. remove (hash) ;}for (imagecallback ITER: callbacks) {ITER. onimageloaded (D, URL) ;}}, "imagecache Loader:" + URL ). start ();}}

I presume you know the basics of the Singleton pattern, so I'll skip the details on that and begin with the variables definitions (see snippet below ). the static and final cache_timeout variable kinda spreaks for itself, it defines the maximum time an image is allowed to remain cached before it has to be downloaded from the server again. this time is in milliseconds, so 60000 means images in the cache will be invalid after a minute.

We'll be using the _ Lock Object to synchronize all our actions. we use a final object for this because we will be accessing the cache from different scopes (both imagecache internal as well as inline runnable objects ), so we need a consistent Lock Object (not just "This ").

next we have the actual drawable cache. we're re using a basic hashmap with a string key and a weakreference object referencing the actual drawable. the weakreference object keeps the drawable object open for garbage collection, so the JVM will be able to remove unused drawables from our cache if nessecary. this won't bother us (as you'll see later on) because when a drawable is GC 'd we'll just grab the local file and recreate it. this way we'll have fast access to our drawable and at the same time prevents huge chunks of memory being reserved for nothing, while the phone is running out of memory.

Last but not least is a hashmap containing a string key and a list with imagecallback objects. this is our main means of transferring a loaded image back to the requesting object. the reason why this is a list (and not just a single imagecallback object) is because we don't want to request the same image multiple times at the same time (remember the synchronization points ?). Basically we do the acutal request once and if another request is done while the image is downloading we'll just add the request to the list of imagecallback objects for that image. this way if we request an image multiple times, we'll be able to hand the image back as soon as the first download finishes. how's that for efficient!

 
Private Static final long cache_timeout = 60000; private final object _ Lock = new object (); Private hashmap> _ cache; private hashmap> _ callbacks;

The constructor is private because this is after all a singleton class and we don't want anybody else making a second instance. other than that it's nothing special, we just initialize the cache and callbacks hashmaps.

 
Private imagecache () {_ cache = new hashmap <string, weakreference <drawable> (); _ callbacks = new hashmap <string, list <imagecallback> ();}

Now for the first trick we have up our sleeve: the URL hash. we take the URL and make a MD5 hash of it, and this is our hashmap key. okey, so it isn' t really such a special trick, but it gets the job done. oh, and just in case the MD5 Digest isn't known, we'll return the URL. less elegant, but it gets the job done just as well (although you really wowould want to think of another way of generati Ng a hash if you discover this to be true ...).

Private string gethash (string URL) {try {messagedigest digest = messagedigest. getinstance ("MD5"); Digest. update (URL. getbytes (); return New biginteger (Digest. digest ()). tostring (16);} catch (nosuchalgorithmexception ex) {// This shoshould never happen, but just to make sure return the URL return URL ;}}

The next method does all the drawable retreiving work. first we get the hash of the URL. next we enter a synchronization block to prevent the image loading thread from modifying the cache while we're re reading from it. if the cache contains the hash key we get the weakreference object from it and check if the reference is still valid and if the reference has been GC 'd we'll remove the item from the cache. finally we return the drawable object or null.

Private drawable drawablefromcache (string URL, string hash) {drawable d = NULL; synchronized (_ Lock) {If (_ cache. containskey (hash) {weakreference ref = _ cache. get (hash); If (Ref! = NULL) {d = ref. Get (); If (D = NULL) _ cache. Remove (hash) ;}} return D ;}

Next we'll be discussing the workhorse of the imagecache class, the loadsync method. this method loads the image from the server and adds it to the cache hashmap. we also pass a context object to the method so we can get the cache directory of the current context.

First we try to get the drawable form the cache, obviusly there is no use in downloading an image we already have (that's the point of the cache, remember ?). Right, so next up is getting the file from the cache directory. as described earlier, the name of the files is the hash, so we'll be looking for that file. next we check if the timeout has passed and the file shocould be deleted and downloaded again from the server. we can see when we last updated the file by checking the last modification date, and if the file does not exist the last modified value of the Will be 0, so all will be fine.

If we couldn't retreive the image from memory we'll try to load it from the local file. if the cache expired we'll delete the local file, forcing the cache to download it from the server. next we create a drawable from the file and add it to the cache hashmap (and, as usual, we do this in a synchronized block ). finally we return the new drawable, or null on error.

Private drawable loadsync (string URL, string hash, context) {drawable d = NULL; try {d = drawablefromcache (URL); file F = new file (context. getcachedir (), hash); Boolean timeout = f. lastmodified () + cache_timeout> = new date (). gettime (); If (D = NULL | timeout) {If (timeout) F. delete (); If (! F. exists () {inputstream is = new URL (URL + "? Rand = "+ new random (). nextint ()). openconnection (). getinputstream (); If (F. createnewfile () {fileoutputstream fo = new fileoutputstream (f); byte [] buffer = new byte [256]; int size; while (size = is. read (buffer)> 0) {fo. write (buffer, 0, size);} fo. flush (); FO. close () ;}d = drawable. createfrompath (F. getabsolutepath (); synchronized (_ Lock) {_ cache. put (hash, new weakreference (D) ;}} catch (exception ex) {log. E (getclass (). getname (), Ex. getmessage (), Ex);} return D ;}

The loadasync method is the only public method of the imagecache class. it makes sure no redundant downloads are executed and callthe callbacks if either the drawable is retreived from the cache or downloaded form the server. first of all we get the hash of the URL. this variable is final because we'll be reusing it in the downloading thread. that is, if we haven't cached it already ofcourse.

The next part is wrapped in a synchronized block, again to prevent simultanious reading and writing of the cache, but also to prevent simultainous access to the callback lists. what we do here is check if there are any imagecallback objects registered with the hash key. we know that a download is in progress if there already is a callback registered. in this situation we'll just add the new callback to the list and stop. if no Callbacks are registered for the hash we'll set a new list to the hash key, containing the new callback.

next we'll start a new thread to download the image using the loadsync method. the loadsync method returns the new drawable, and all we have to do next is pass it to all the callbacks registered for it. we get the list of registered callbacks from the callbacks hashmap. of course we do this in a synchronization block, for the usual reasons, and we remove the list from the hashmap to prevent us F Rom invoking the same callback twice. Now all that's left to do is invoke all the callbacks in the list and we're done!

 Public void loadasync (final string URL, final imagecallback callback, final context) {final string hash = gethash (URL); synchronized (_ Lock) {list callbacks = _ callbacks. get (hash); If (callbacks! = NULL) {If (callback! = NULL) Callbacks. Add (callback); return;} callbacks = new arraylist (); If (callback! = NULL) callbacks. add (callback); _ callbacks. put (hash, callbacks);} new thread (New runnable () {@ override public void run () {drawable d = loadsync (URL, context); List callbacks; synchronized (_ Lock) {callbacks = _ callbacks. remove (hash) ;}for (imagecallback ITER: callbacks) {ITER. onimageloaded (D, URL) ;}}, "imagecache Loader:" + URL ). start () ;}

and that's the whole lot! There are some minor points in the class that can be improved. if a timeout occurs on an image the imagecache cocould return the old image before the new image has loaded. this way the user sees the old image and as soon as the new image has been loaded the image refreshes to the updated version. it isn' t a big improvement, but it cocould be a really cool feature

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.