安卓图片加载框架--Universal-Image-Loader

简介:   今天来介绍图片加载的框架Android-Universal-Image-Loader   GITHUB上的下载路径为:https://github.com/nostra13/Android-Universal-Image-Loader   也可以自行百度下载。

  今天来介绍图片加载的框架Android-Universal-Image-Loader

  GITHUB上的下载路径为:https://github.com/nostra13/Android-Universal-Image-Loader

  也可以自行百度下载。

  首先来封装的一个类CacheTool ,由于其他加载图片的方法有点繁琐,所以这里仅封装了一个简单实用的加载方法:

 

 
 
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Environment;
import android.widget.ImageView;

import java.io.File;

import com.ncct.app.R;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

/**
 * 图片加载框架
 * 
 * @author jiang
 * 
 */
public class CacheTool {

    private static File cacheDir = Environment.getDataDirectory();
    private static DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.loading_img)
            .showImageForEmptyUri(R.drawable.loading_error).showImageOnFail(R.drawable.loading_error)
            .cacheInMemory(true).cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();

    private static ImageLoaderConfiguration config;

    public static void Init(Context context) {
        config = new ImageLoaderConfiguration.Builder(context).memoryCacheExtraOptions(480, 800) // max
                                                                                                    // width,
                                                                                                    // max
                                                                                                    // height,即保存的每个缓存文件的最大长宽
                .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75, null) // Can
                                                                                // slow
                                                                                // ImageLoader,
                                                                                // use
                                                                                // it
                                                                                // carefully
                                                                                // (Better
                                                                                // don't
                                                                                // use
                                                                                // it)/设置缓存的详细信息,最好不要设置这个
                .threadPoolSize(3)// 线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You
                                                                                // can
                                                                                // pass
                                                                                // your
                                                                                // own
                                                                                // memory
                                                                                // cache
                                                                                // implementation/你可以通过自己的内存缓存实现
                .memoryCacheSize(2 * 1024 * 1024).discCacheSize(50 * 1024 * 1024)
                .discCacheFileNameGenerator(new Md5FileNameGenerator())// 将保存的时候的URI名称用MD5
                                                                        // 加密
                .tasksProcessingOrder(QueueProcessingType.LIFO).discCacheFileCount(100) // 缓存的文件数量
                // .discCache(new UnlimitedDiscCache(cacheDir))// 自定义缓存路径
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                .imageDownloader(new BaseImageDownloader(context, 5 * 1000, 30 * 1000)) // connectTimeout
                                                                                        // (5
                                                                                        // s),
                                                                                        // readTimeout
                                                                                        // (30
                                                                                        // s)超时时间
                .writeDebugLogs() // Remove for release app
                .build();// 开始构建
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);
    }

    /**
     * 加载图片并监听回调结果
     * 
     * @param iv
     * @param url
     * @param mImageLoadingListener
     */
    public static void displayImg(ImageView iv, String url, ImageLoadingListener mImageLoadingListener) {
        ImageLoader.getInstance().displayImage(url, iv, options, mImageLoadingListener);
    }

    /**
     * 加载图片
     * 
     * @param iv
     * @param url
     */
    public static void displayImg(ImageView iv, String url) {

        ImageLoader.getInstance().displayImage(url, iv, options);
    }

    /**
     * 清除内存
     */
    public static void clearMemoryCache() {
        ImageLoader.getInstance().clearMemoryCache();
    }

    /**
     * 清除缓存
     */
    public static void clearDiskCache() {
        ImageLoader.getInstance().clearDiscCache();
    }

    /**
     * 得到某个图片的缓存路径
     * 
     * @param imageUrl
     * @return
     */
    public static String getImagePath(String imageUrl) {
        return ImageLoader.getInstance().getDiscCache().get(imageUrl).getPath();
    }

}

 

  封装好了,里面都有详细的介绍,这里介绍下上面的中的ImageLoadingListener 接口回调,按ctrl + 鼠标左键可以进入jar包里的java文件:

/*******************************************************************************
 * Copyright 2011-2013 Sergey Tarasevich
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.nostra13.universalimageloader.core.assist;

import android.graphics.Bitmap;
import android.view.View;

/**
 * Listener for image loading process.<br />
 * You can use {@link SimpleImageLoadingListener} for implementing only needed methods.
 *
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 * @see SimpleImageLoadingListener
 * @see FailReason
 * @since 1.0.0
 */
public interface ImageLoadingListener {

    /**
     * Is called when image loading task was started
     *
     * @param imageUri Loading image URI
     * @param view     View for image
     */
    void onLoadingStarted(String imageUri, View view);

    /**
     * Is called when an error was occurred during image loading
     *
     * @param imageUri   Loading image URI
     * @param view       View for image. Can be <b>null</b>.
     * @param failReason {@linkplain FailReason The reason} why image loading was failed
     */
    void onLoadingFailed(String imageUri, View view, FailReason failReason);

    /**
     * Is called when image is loaded successfully (and displayed in View if one was specified)
     *
     * @param imageUri    Loaded image URI
     * @param view        View for image. Can be <b>null</b>.
     * @param loadedImage Bitmap of loaded and decoded image
     */
    void onLoadingComplete(String imageUri, View view, Bitmap loadedImage);

    /**
     * Is called when image loading task was cancelled because View for image was reused in newer task
     *
     * @param imageUri Loading image URI
     * @param view     View for image. Can be <b>null</b>.
     */
    void onLoadingCancelled(String imageUri, View view);
}

  从以上代码中我们可以了解到接口中我们可以监听到开始、失败、完成、取消的动作。

  现在开始使用吧:

    private ImageView My_Head;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.personcenter);
        My_Head = (ImageView) findViewById(R.id.My_Head);
                String Url = "http://pic.nipic.com/2007-11-09/200711912453162_2.jpg";
                CacheTool.displayImg(My_Head , Url );
    }     

   Mark一下,暂存一个直接通过URL获取bitmap的函数,未作内存处理。

    /**
     * 获取指定路径的图片
     * 
     * @param urlpath
     * @return
     * @throws Exception
     */
    public Bitmap getImage(String urlpath) throws Exception {
        URL url = new URL(urlpath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        Bitmap bitmap = null;
        InputStream inputStream = conn.getInputStream();
        bitmap = BitmapFactory.decodeStream(inputStream);
        return bitmap;
    }

 

遗失的拂晓
目录
相关文章
|
Android开发
Android开发教程 - 使用Data Binding(七)使用BindingAdapter简化图片加载
本系列目录 使用Data Binding(一)介绍 使用Data Binding(二)集成与配置 使用Data Binding(三)在Activity中的使用 使用Data Binding(四)在Fragment中的使用 ...
1095 0
|
27天前
|
存储 缓存 算法
构建安卓应用的高效图片加载策略
【4月更文挑战第16天】在移动设备上优化用户体验的关键之一是快速而高效的图片加载。对于Android平台而言,由于设备多样性和网络环境的不稳定性,设计一个既能提升速度又能减少资源消耗的图片加载策略尤为重要。本文将深入探讨在Android应用中实现图片加载的几种技术手段,包括图片格式选择、内存缓存、磁盘缓存以及使用第三方库等,旨在为开发者提供一套综合性的解决方案,以实现在不同设备和网络环境下的高效图片加载。
|
5月前
|
API Android开发
[Android]图片加载库Glide
[Android]图片加载库Glide
59 0
|
9月前
|
JSON Java Android开发
Android 中使用Volley进行网络请求和图片加载详解
Android 中使用Volley进行网络请求和图片加载详解
215 0
Android 中使用Volley进行网络请求和图片加载详解
|
11月前
|
Android开发
Android图片加载开源库对比
Android图片加载开源库对比
72 0
Android组件化开发(三)--图片加载组件封装
今天我们来封装一个`图片加载库`:`lib_image_loader`
|
存储 Android开发 图形学
Android | 毫分缕析!说说图片加载的整个过程
Android | 毫分缕析!说说图片加载的整个过程
96 0
Android | 毫分缕析!说说图片加载的整个过程
|
缓存 算法 Android开发
android 图片加载优化,避免oom问题产生
1,及时回收bitmap,在activity的onstop()和onDestory()里面调用如下代码进行bitmap的回收: // 先判断是否已经回收 if(bitmap != null && !bitmap.
1187 0
|
Android开发 Kotlin Java
从最简单的图片加载,教你Android实现异步!
异步,在安卓开发中简直是再熟悉不过了。 说到异步,脑海中立马浮现的就是多线程开发,Thread、Handler啥的一一涌上心头… 我们知道在Android开发中不能在非UI线程中更新UI,但是,有的时候我们需要在代码中执行一些诸如访问网络、查询数据库等耗时操作,为了不阻塞UI线程,我们时常会开启一个新的线程(工作线程)来执行这些耗时操作,然后我们可能需要将查询到的数据渲染到UI组件上,那么这个时候我们就需要考虑异步更新UI的问题了。
1386 0
|
Android开发 缓存 编解码
Android应用开发-图片加载库Glide
Glide Picasso和Glide之间的区别: Picasso 仅仅缓存了全尺寸的图像;然而 Glide 缓存了原始图像,全分辨率图像和另外小版本的图像。
905 0