Android Universal-Image-Loader framework Learning (I), androidimageloader
1. Overview of Universal-Image-Loader:
Android-Universal-Image-Loader is an open-source Image loading framework. This project aims to provide a reusable instrument for asynchronous Image loading, caching, and display.
Features of open-source libraries:
(1) multi-threaded download of images.
(2). You can configure ImageLoader, change the thread pool, image downloader, and so on.
(3) images can be cached in memory, file system, or SD card.
(4). Supports image download listening.
(5). You can better control the image loading process. For example, you can stop loading an image when the listview slides.
For other features, refer.
Ii. Simple use:
:
When not loaded:
Loaded successfully:
After importing the jar package in the project, you must configure ImageLoaderConfiguration to configure global image cache, such as thread, cache size, and resolution, then, ImageLoader is the execution class for downloading images and caching image display images. It passes the configured ImageLoaderConfiguration into ImageLoader to complete the initialization, that is, only ImageLoader can be used after initialization. getInstance (). displayImage () loads an image.
ImageLoader initialization can be implemented in Application:
Public class MyApp extends Application {@ Overridepublic void onCreate () {super. onCreate (); initImageLoader1 (getApplicationContext ();}/** custom configuration */public static void initImageLoader (Context context) {ImageLoaderConfiguration. builder config = new ImageLoaderConfiguration. builder (context); config. threadPoolSize (3); // Number of threads loaded in the thread pool config. threadPriority (Thread. NORM_PRIORITY-2); config. denyCacheImageMultiple SizesInMemory (); // multiple sizes of images not cached in the memory config. diskCacheFileNameGenerator (new Md5FileNameGenerator (); // use MD5config to specify the URI name when saving. diskCacheSize (50*1024*1024); // 50 MiBconfig. tasksProcessingOrder (QueueProcessingType. LIFO); config. writeDebugLogs (); // Remove for release app // initialize ImageLoaderImageLoader. getInstance (). init (config. build ();}/** default configuration. Generally, you can use the default configuration when there are no special requirements. */Public static void initImageLoader1 (Context context) {// create the default ImageLoader configuration Parameter ImageLoaderConfiguration = ImageLoaderConfiguration. createDefault (context); // initialize ImageLoaderImageLoader. getInstance (). init (configuration );}}
In diskCacheFileNameGenerator (); this indicates the way the cached file is named. There are two methods:
1. new Md5FileNameGenerator () // use MD5 to encrypt and name UIL
2. new HashCodeFileNameGenerator () // use HASHCODE to encrypt and name UIL
Then, under the AndroidManifest. xml configuration:
<! -- Network permission and cache permission --> <span style = "color: # ff0000;"> <uses-permission android: name = "android. permission. INTERNET "/> <uses-permission android: name =" android. permission. WRITE_EXTERNAL_STORAGE "/> </span> <application android: name =" com. example. androidimageview. myApp "android: allowBackup =" true "android: icon =" @ drawable/ic_launcher "android: label =" @ string/app_name "android: theme = "@ style/AppTheme"> <activity <span style = "color: # ff0000;"> android: name = "com. example. androidimageview. mainActivity "</span> android: label =" @ string/app_name "> <intent-filter> <action android: name =" android. intent. action. MAIN "/> <category android: name =" android. intent. category. LAUNCHER "/> </intent-filter> </activity> </application>
Define the layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <ListView android:id="@+id/listview1"android:layout_width="fill_parent"android:layout_height="fill_parent" /></RelativeLayout>
DisplayImageOptions is used for image loading. In this case, you can configure the options for displaying the image. The options include:
<Span style = "font-size: 24px;"> options = new DisplayImageOptions. builder (). showImageOnLoading (R. drawable. ic_stub) // sets the image displayed during the download process. showImageForEmptyUri (R. drawable. ic_empty) // sets the image to be displayed when the image Uri is null or incorrect. showImageOnFail (R. drawable. ic_error) // sets the image displayed when an error occurs during image loading/decoding. delayBeforeLoading (1000) // sets the delay time to start downloading. cacheInMemory (true) // sets whether the downloaded image is cached in memory. cacheOnDisk (true) // sets whether the downloaded resource is cached in the SD card. considerExifParams (true) // determines whether to consider the JPEG image EXIF parameter (rotation, flip ). imageScaleType (ImageScaleType. IN_SAMPLE_POWER_OF_2) // sets the encoding format of the image. bitmapConfig (Bitmap. config. RGB_565) // sets the image decoding type. displayer (new RoundedBitmapDisplayer (20) // whether to set it to a rounded corner or a radian. displayer (new FadeInBitmapDisplayer (1000) // specifies the animation time after the image is loaded. build (); </span>
The image display size will be based on the arrogance of your ImageView in the above Configuration:
ImageScaleType (ImageScaleType imageScaleType ):
Scale type mageScaleType:
(1). EXACTLY: The image will be scaled down in proportion to the target size.
(2). EXACTLY_STRETCHED: The image will be scaled to the target size.
(3). IN_SAMPLE_INT: integer multiple of the image to be sampled twice.
(4). IN_SAMPLE_POWER_OF_2: The image will be reduced by twice until the next step is reduced to make the image smaller.
(5). NONE: The image is not adjusted.
Item layout:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"><ImageViewandroid:id="@+id/image"android:layout_width="72dp"android:layout_height="72dp"android:layout_margin="3dip"android:adjustViewBounds="true"android:contentDescription="@string/descr_image"android:scaleType="centerCrop" /><TextViewandroid:id="@+id/text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="start|center_vertical"android:layout_marginLeft="20dip"android:textSize="22sp" /></LinearLayout>
Main Interface implementation:
Public class MainActivity extends Activity {private static final String TEST_FILE_NAME = "Universal Image Loader & =+ -_.,! ()~ '{}Png "; ListView listview1; public static final String [] IMAGES = new String [] {" http://img.dapixie.com/uploads/allimg/111105/1-111105145231.jpg "}; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); listview1 = (ListView) findViewById (R. id. listview1); listview1.setAdapter (new ImageAdapter (this);} @ Override pr Otected void onDestroy () {super. onDestroy (); AnimateFirstDisplayListener. displayedImages. clear (); ImageLoader. getInstance (). clearMemoryCache (); ImageLoader. getInstance (). stop ();} private static class ImageAdapter extends BaseAdapter {private static final String [] IMAGE_URLS = MainActivity. IMAGES; private LayoutInflater inflater; private ImageLoadingListener animateFirstListener = new AnimateFirstD IsplayListener (); private DisplayImageOptions options; ImageAdapter (Context context) {inflater = LayoutInflater. from (context); options = new DisplayImageOptions. builder (). showImageOnLoading (R. drawable. ic_stub) // sets the image displayed during the download process. showImageForEmptyUri (R. drawable. ic_empty) // sets the image to be displayed when the image Uri is null or incorrect. showImageOnFail (R. drawable. ic_error) // sets the image displayed when an error occurs during image loading/decoding. delayBeforeLoading (1000) // sets the delay time to start downloading. cacheInMem Ory (true) // sets whether the downloaded image is cached in memory. cacheOnDisk (true) // sets whether the downloaded resource is cached in the SD card. considerExifParams (true) // determines whether to consider the JPEG image EXIF parameter (rotation, flip ). imageScaleType (ImageScaleType. IN_SAMPLE_POWER_OF_2) // sets the encoding format of the image. bitmapConfig (Bitmap. config. RGB_565) // sets the image decoding type. displayer (new RoundedBitmapDisplayer (20) // whether to set it to a rounded corner or a radian. displayer (new FadeInBitmapDisplayer (1000) // specifies the animation time after the image is loaded. build () ;}@ Overridepublic int getCount () {return IMAG E_URLS.length ;}@ Overridepublic Object getItem (int position) {return position ;}@ Overridepublic long getItemId (int position) {return position ;}@ Overridepublic View getView (final int position, view convertView, ViewGroup parent) {View view = convertView; final ViewHolder holder; if (convertView = null) {view = inflater. inflate (R. layout. listview_item, parent, false); holder = new ViewHolder (); holder. tex T = (TextView) view. findViewById (R. id. text); holder. image = (ImageView) view. findViewById (R. id. image); view. setTag (holder);} else {holder = (ViewHolder) view. getTag ();} holder. text. setText ("Item" + (position + 1); ImageLoader. getInstance (). displayImage (IMAGE_URLS [position], holder. image, options, animateFirstListener); return view ;}} static class ViewHolder {TextView text; ImageView image;} private stat Ic class AnimateFirstDisplayListener extends SimpleImageLoadingListener {static final List <String> displayedImages = Collections. synchronizedList (new jsonlist <String> (); @ Overridepublic 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); displayedImages. add (imageUri );}}}}}
In use, mainly these ImageLoader. getInstance (). displayImage (), ImageLoader. getInstance (). loadImage (), ImageLoader. getInstance (). loadImageSync (), ImageLoader. getInstance (). the loadImageSync () method is synchronous, and android4.0 has a feature. network operations cannot be performed in the main thread, so ImageLoader. getInstance (). we will not use the loadImageSync () method.
This section mainly introduces three methods for reloading ImageLoader. getInstance (). displayImage:
(1). ImageLoader. getInstance (). displayImage (imageUrl, imageView): The parameter imageUrl indicates the URL of the image, and imageView indicates the IMAGEVIEW control that carries the image.
(2 ). imageLoader. getInstance (). displayImage (imageUrl, imageView, options): The parameter imageUrl indicates the URL of the image, imageView indicates the IMAGEVIEW control that carries the image, and options indicates the DisplayImageOptions configuration file.
(3). ImageLoader. getInstance (). displayImage (IMAGE_URLS [position], holder. image, options, animateFirstListener): This is a method used in the above Code. AnimateFirstListener: The image loading listener.
ImageLoadingListener can also be used for image download listening. This method is complicated and simple SimpleImageLoadingListener can be used.
New ImageLoadingListener () {@ Overridepublic void onLoadingCancelled (String arg0, View arg1) {// executed when loading is canceled} @ Overridepublic void onLoadingComplete (String arg0, View arg1, Bitmap arg2) {// run when loading is successful} @ Overridepublic void onLoadingFailed (String arg0, View arg1, FailReason arg2) {// run when loading fails} @ Overridepublic void onLoadingStarted (String arg0, view arg1) {// run when loading starts }};
3. load images from other sources:
String imageUri = "http://site.com/image.png"; // from WebString imageUri = "file:///mnt/sdcard/image.png"; // from SD cardString imageUri = "content://media/external/audio/albumart/13"; // from content providerString imageUri = "assets://image.png"; // from assetsString imageUri = "drawable://" + R.drawable.image; // from drawables (only images, non-9patch)
4. Avoid oom (I also learned from other people's blogs, paste the great god blog address http://blog.csdn.net/xiaanming/article/details/26810303 ):
1. Reduce the number of threads in the thread pool. We recommend that you configure 1-5 in. threadPoolSize in ImageLoaderConfiguration.
2. Set bitmapConfig to Bitmap. Config. RGB_565 in the DisplayImageOptions option. Because the default value is ARGB_8888, using RGB_565 will consume 2 times less memory than using ARGB_8888.
3. Configure the image memory cache in ImageLoaderConfiguration to memoryCache (new WeakMemoryCache () or not use the memory cache.
4. Set. imageScaleType (ImageScaleType. IN_SAMPLE_INT) or imageScaleType (ImageScaleType. EXACTLY) in the DisplayImageOptions option)
Through the above, I believe you have a good understanding of the use of the Universal-Image-Loader framework. When using this framework, we try to use the displayImage () method to load images, loadImage () is to call back the image object to the onLoadingComplete () method of the ImageLoadingListener interface. We need to manually set it to the ImageView and the displayImage () method, weak references is used for ImageView objects to facilitate the Garbage Collector to recycle ImageView objects. If we want to load images of a fixed size, we need to pass an ImageSize object using the loadImage () method, the displayImage () method will crop the Image Based on the ImageView object measurement value, or the value set by android: layout_width and android: layout_height, or the value set by android: maxWidth and/or android: maxHeight.