[Mobile Development] Android Image asynchronously loaded Android-Universal-Image-Loader

Source: Internet
Author: User

In Android development, we often encounter OOM exceptions caused by too many images or improper operations. Sometimes, although this problem is solved, it may affect the running efficiency of the program, for example: during the process of sliding the scroll bar quickly, our program is still loading images on the server, which gives users an extremely bad experience. In fact, there are a lot of explanations on asynchronous loading and caching of images on the network, but writing a program in this area is still troublesome. We need to consider multiple threads, caching, memory overflow, and many other aspects, some coders have helped us solve this problem. Today I will introduce you to a popular open-source class library, it can solve everyone's troubles very well!

I. Introduction:

Android-Universal-Image-Loader is an open-source UI component program designed to provide a reusable instrument for asynchronous Image loading, caching, and display.

Download an Open Source class library from GitHub:Https://github.com/nostra13/Android-Universal-Image-Loader)


Features:

1. multi-threaded image loading;

2.Asynchronous image loading cache mechanism, including memory cache soft reference) and local cache;

3. dynamically configure the size of the thread pool for ImageLoader, http options, memory and CD cache mode, display images, and other options );

4.Implements monitoring and event processing for the loading process;

5. The ability to configure the display options for loading images, including processing rounded corners of images and Loading completed display animations;

(Official)

650) this. length = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/120J95634-0.png "title =" UniversalImageLoader.png "width =" 689 "height =" 450 "border =" 0 "hspace =" 0 "vspace =" 0 "style =" width: 689px; height: pixel PX; "alt =" 233715740.png"/>


Ii. Use

1. decompress the downloaded zip package to obtain the folder shown in

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/120J9E01-1.jpg "title =" QQ20131204232927.jpg "alt =" 233039238.jpg"/>

2. Import the universal-image-loader-1.8.6-with-sources.jar to the new project, see the example in the sample for use. To help new users quickly learn how to use it, I will briefly explain how to use ImageLoader in this class library to load images, ListView, GridView, ViewPager)


Demo project diagram:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/120J92Q8-2.jpg "title =" QQ20131204235755.jpg "alt =" 235758706.jpg"/>


2.1.When the program starts, you can initialize ImageLoaderConfiguration as needed.

Public class MyApplication extends Application {@ Override public void onCreate () {super. onCreate (); initImageLoader (getApplicationContext ();}/** initialize the configuration information of the image loading class **/public static void initImageLoader (Context context) {// This configuration tuning is M. you can tune every option, you may tune some of them, // or you can create default configuration by // ImageLoaderConfiguration. createDefault (t His); // method. imageLoaderConfiguration config = new ImageLoaderConfiguration. builder (context ). threadPriority (Thread. NORM_PRIORITY-2) // Number of threads for loading images. denyCacheImageMultipleSizesInMemory () // the size of the decoded image is cached in the memory.. DiscCacheFileNameGenerator (new Md5FileNameGenerator () // sets the name of the disk cache file. tasksProcessingOrder (QueueProcessingType. LIFO) // sets the process of loading the display image queue. writeDebugLogs () // Remove for release app. build (); // Initialize ImageLoader with configuration. imageLoader. getInstance (). init (config );}}

In AndroidManifest. xml

android:name=".MyApplication"


. In MainActivity, we only jump to the corresponding interface. Next, let's take a look at the specific usage in ListView. The remaining two will take a look at the Demo. The principle is the same.

ImageListActivity:

/*** Use ImageLoader * @ author ZHF in listView **/public class ImageListActivity extends AbsListViewBaseActivity {DisplayImageOptions options; // configure the image loading and display options String [] imageUrls; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. ac_image_list); // obtain the url array Bundle bundle = getIntent (). getExtras (); imageUrls = bundle. getStringArray (Extra. IMAGES); // configure the image loading and display options. For more information, see the doc documentation.) options = new DisplayImageOptions. builder (). showStubImage (R. drawable. ic_stub) // display the image during ImageView loading. showImageForEmptyUri (R. drawable. ic_empty) // when the image connection address is null. showImageOnFail (R. drawable. ic_error) // image loading failed. cacheInMemory (true) // cache is loaded in the memory when an image is loaded. cacheOnDisc (true) // cache is loaded in the disk when the image is loaded. displayer (new RoundedBitmapDisplayer (20) // sets the user to load the image task (the rounded corner image is displayed here ). buil D (); listView = (ListView) findViewById (android. r. id. list); // bind the adapter listView. setAdapter (new ItemAdapter (); listView. setOnItemClickListener (new OnItemClickListener () {@ Override public void onItemClick (AdapterView <?> Parent, View view, int position, long id) {startImagePagerActivity (position) ;}}) ;}@ Override public void onBackPressed () {AnimateFirstDisplayListener. displayedImages. clear (); super. onBackPressed ();} private void startImagePagerActivity (int position) {Intent intent = new Intent (this, ImagePagerActivity. class); intent. putExtra (Extra. IMAGES, imageUrls); intent. putExtra (Extra. IMAGE_POSITION, po Sition); startActivity (intent);}/** custom image adapter **/class ItemAdapter extends BaseAdapter {private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener (); private class ViewHolder {public TextView text; public ImageView image ;}@ Override public int getCount () {return imageUrls. length ;}@ Override public Object getItem (int position) {return position ;}@ Override public long GetItemId (int position) {return position ;}@ Override public View getView (final int position, View convertView, ViewGroup parent) {View view = convertView; final ViewHolder holder; if (convertView = null) {view = getLayoutInflater (). inflate (R. layout. item_list_image, parent, false); holder = new ViewHolder (); holder. text = (TextView) view. findViewById (R. id. text); holder. image = (ImageView) vie W. findViewById (R. id. image); view. setTag (holder);} else {holder = (ViewHolder) view. getTag ();} holder. text. setText ("Item" + (position + 1); // Adds display image task to execution pool. image will be set to ImageView when it's turn. imageLoader. displayImage (imageUrls [position], holder. image, options, animateFirstListener); return view ;}/ ** image loading listener event **/private static class AnimateFirstDisplay Listener extends SimpleImageLoadingListener {static final List <String> displayedImages = Collections. synchronizedList (new jsonlist <String> (); @ Override public void onLoadingComplete (String imageUri, View, Bitmap loadedImage) {if (loadedImage! = Null) {ImageView imageView = (ImageView) view; boolean firstDisplay =! DisplayedImages. contains (imageUri); if (firstDisplay) {FadeInBitmapDisplayer. animate (imageView, 500); // sets the image hiding animation to 500 ms displayedImages. add (imageUri); // add the image uri to the set }}}}}

Note:

1. to load an image by using ImageLoader, you only need to call the displayImage method in the getView method of the Adapter to load the asynchronous list image, options is the previously defined image loading and display options. Here we use RoundedBitmapDisplayer rounded corner image display.) The animateFirstListener is the listener event when the image is loaded for the first time, the purpose is to display a fade-in display animation. You can add other events.

2. in my own test, the URLs of images in the Constant class in the examples on the official website are slow to link to the mobile phone, which is completely ineffective. Then I changed them to the Uris of other series of images for easy observation!


:

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/120J963a-3.png "width =" 192 "height =" 320 "title =" device-2013-12-05-001327.png "alt =" 001446807.png"/> 650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/120J91234-4.png "style =" width: 192px; height: 320px; "title =" device-2013-12-05-001406.png "width =" 192 "height =" 320 "border =" 0 "hspace =" 0 "vspace =" 0 "alt =" 001446272.png"/> 650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131229/120J95527-5.png "style =" width: 192px; height: 320px; "title =" device-2013-12-05-001434.png "width =" 192 "height =" 320 "border =" 0 "hspace =" 0 "vspace =" 0 "alt =" 001447354.png"/>


Finally, when using this tool, remember to pay attention to the cached files in the/sdcard/Android/data/[package_name]/cache directory. Remember to clear the cache regularly. Otherwise, the SD card will be full after a long period of time. You can also configure the SD Cache Policy in ImageLoaderConfiguration to limit the number of cached files.MemoryCacheSizePercentage), Restrict the maximum size of cached filesMemoryCacheSize).


The Demo source code has been uploaded!



This article from the "crazy Snail" blog, please be sure to keep this source http://smallwoniu.blog.51cto.com/3911954/1336194

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.