Analysis of image download tool class AsyncImageLoader in android

Source: Internet
Author: User

 

During this time, I saw many people use this image download class for listview (for example, simulating the Sina client). I don't know which kind of class was written by anyone, I took over other people when I used this class. At the beginning, I felt that this class was better written than the AsyncImageTask I wrote. java is much better. Let's talk about what I first wrote:

Public class AsyncImageTask extends AsyncTask <String, Void, InputStream> {

Private ImageView imageView;

Public AsyncImageTask (ImageView imageView ){

This. imageView = imageView;

}

@ Override

Protected InputStream doInBackground (String... params ){

 

InputStream inputStream = null;

Try {

URL url = new URL (params [0]);

InputStream = url. openStream ();

} Catch (IOException e ){

E. printStackTrace ();

}

Return inputStream;

}

@ Override

Protected void onPostExecute (InputStream result ){

If (imageView! = Null & result! = Null ){

Bitmap bmp = BitmapFactory. decodeStream (result );

ImageView. setImageBitmap (bmp );

}

Super. onPostExecute (result );

}

}

I feel awkward when I finish writing it. It can satisfy my needs at that time. That's the case. (which of the following experts can tell me the disadvantages?) in this class, you only need to input the ImageView and network address of the image to display the image. After the image is downloaded, it will be displayed. Later, my supervisor replaced it and used the AsyncImageLoader. java class. Let's take a closer look at it. The writing is really good. Do not talk nonsense. First paste the code of this class (AsyncImageLoader. java ):

  

Public class AsyncImageLoader {

 

Private HashMap <String, SoftReference <Drawable> imageCache;

Public AsyncImageLoader (){

ImageCache = new HashMap <String, SoftReference <Drawable> ();

}

Public Drawable loadDrawable (final String imageUrl, final ImageCallback imageCallback ){

If (imageCache. containsKey (imageUrl )){

SoftReference <Drawable> softReference = imageCache. get (imageUrl );

Drawable drawable = softReference. get ();

If (drawable! = Null ){

Return drawable;

}

}

Final Handler handler = new Handler (){

Public void handleMessage (Message message ){

ImageCallback. imageLoaded (Drawable) message. obj, imageUrl );

}

};

New Thread (){

@ Override

Public void run (){

Drawable drawable = loadImageFromUrl (imageUrl );

ImageCache. put (imageUrl, new SoftReference <Drawable> (drawable ));

Message message = handler. obtainMessage (0, drawable );

Handler. sendMessage (message );

}

}. Start ();

Return null;

}

Public static Drawable loadImageFromUrl (String url ){

URL m;

InputStream I = null;

Try {

M = new URL (url );

I = (InputStream) m. getContent ();

} Catch (MalformedURLException e1 ){

E1.printStackTrace ();

} Catch (IOException e ){

E. printStackTrace ();

}

Drawable d = Drawable. createFromStream (I, "src ");

Return d;

}

Public interface ImageCallback {

Public void imageLoaded (Drawable imageDrawable, String imageUrl );

}

 

}

Implementation Method: Pass in the network address of the image and an object that implements the ImageCallback action. When imageCache exists in the image, the image is returned. When imageCache does not have this image, an asynchronous thread of the Instance downloads the image and returns null at the same time. Finally, the imageLoaded method is called when the image download is complete.

Let's talk about the advantages of this class design: 1. The policy mode is adopted; 2. the SoftReference keyword is used.

First, let's talk about the policy mode. The program encapsulates the operations performed after the image is downloaded into an ImageCallback abstract class, making the system more flexible and easy to expand.

In Java memory management, there are four categories of references: strong reference HardReference, weak reference WeakReference, soft reference SoftReference, and Virtual Reference PhantomReference. Their differences are also obvious. Even if the VM memory is too tight to throw out OOM, the referenced objects will not be recycled, and WeakReference is more suitable for a small number of objects, however, objects with a relatively large volume are the most vulnerable to garbage collection among the four references, however, when we use SoftReference to display App icons for every App similar to the Android Market, we can consider using it to solve the problem of memory not being quickly recycled. When the memory shortage is facing a Java VM crash and OOM is thrown out, soft reference will forcibly recycle the memory. The final Virtual Reference has no practical significance. It only observes the GC activity status. It is more practical for testing and must be used with ReferenceQueue. For a group of data, we can add a group of SoftReference objects through HashMap to temporarily retain some data, and for the content that needs to be retrieved through the network repeatedly, cache can be stored through a local file system or database.

The last sentence is true. In fact, this is also true in most cases.

Let's talk about its usage. It is usually used as a variable of an adapter, for example:

Class BookAdapter extends ArrayAdapter <BookInfo> {

AsyncImageLoader asyncImageLoader;

Context mContext;

BookAdapter (Context context, List <BookInfo> data ){

Super (context, 0, data );

AsyncImageLoader = new AsyncImageLoader ();

MContext = context;

}

@ Override

Public View getView (int position, View convertView, ViewGroup parent ){

ViewCache holder;

If (convertView = null ){

LayoutInflater inflate = (LayoutInflater) mContext. getSystemService (Context. LAYOUT_INFLATER_SERVICE );

ConvertView = inflate. inflate (com.slider.cn. R. layout. list_item, null );

Holder = new ViewCache ();

Holder. icon = (ImageView) convertView. findViewById (com.slider.cn. R. id. note_icon );

Holder. name = (TextView) convertView. findViewById (com.slider.cn. R. id. note_name );

Holder. date = (TextView) convertView. findViewById (com.slider.cn. R. id. note_date );

ConvertView. setTag (holder );

} Else {

Holder = (ViewCache) convertView. getTag ();

}

Final BookInfo bookInfo = getItem (position );

Holder. name. setText (bookInfo. getName (). toString ());

Holder. date. setText (bookInfo. getInfo ());

Holder. icon. setTag (bookInfo. getUri ());

//

Drawable drawable = asyncImageLoader. loadDrawable (bookInfo. getUri (), new ImageCallback (){

@ Override

Public void imageLoaded (Drawable imageDrawable, String imageUrl ){

ImageView imageViewByTag = (ImageView) BookListView. this. findViewWithTag (bookInfo. getUri ());

If (imageViewByTag! = Null ){

ImageViewByTag. setImageDrawable (imageDrawable );

} Else {

// Load image failed from Internet

}

}

});

If (drawable = null ){

Holder. icon. setImageDrawable (drawable_waiting );

} Else {

Holder. icon. setImageDrawable (drawable );

}

Return convertView;

}

}

Static class ViewCache {

ImageView icon;

TextView name;

TextView date;

}

However, it seems to have some imperfections. For example, it may cause threads (or even more) that download more than 20 images at the same time. It does not limit the number of threads. Let's use a thread pool with fixed data. For example, how can we add duplicate data to an image, and how can we handle the priority of threads in a thread pool? (For example, the thread you want to add recently has the highest priority, because you always want to see the content of the current interface first, and do not care when the content of the interface is skipped, there are too many things to be said here. In fact, most applications can be handled by completing the above steps)

I just started to write a blog recently. If anything is wrong, please kindly advise.

 

References:

Http://www.cnblogs.com/enricozhang/archive/2010/06/12/1756904.html

Http://www.bkjia.com/kf/201111/111967.html

Author slider

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.