Android--异步加载图片(头像加载)

来源:互联网 发布:企业logo设计软件 编辑:程序博客网 时间:2024/06/05 07:10

参考博客:http://www.cnblogs.com/zhangs1986/p/3248235.html
 自己用的一个头像图片异步加载DEMO,只有一个外部类;只是实现了异步加载的功能。

MainActivity.java

package com.liefyuan.imagetest;import android.graphics.drawable.Drawable;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.ImageView;public class MainActivity extends AppCompatActivity {    @Override    public void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        loadImage("http://101.200.46.138:9999/ftp1/25.jpg", R.id.imageView1);        loadImage("http://101.200.46.138:9999/ftp1/32.jpg", R.id.imageView2);        loadImage("http://static.firefoxchina.cn/img/201707/8_596c1170341f20.jpg", R.id.imageView3);        loadImage("http://csdnimg.cn/www/images/csdnindex_logo.gif", R.id.imageView4);        loadImage("http://images.cnblogs.com/logo_small.gif", R.id.imageView5);    }    private AsyncImageLoader asyncImageLoader = new AsyncImageLoader();    // 引入线程池,并引入内存缓存功能,并对外部调用封装了接口,简化调用过程    private void loadImage(final String url, final int id)    {        // 如果缓存过就会从缓存中取出图像,ImageCallback接口中方法也不会被执行        Drawable cacheImage = asyncImageLoader.loadDrawable(url, new AsyncImageLoader.ImageCallback()        {            // 请参见实现:如果第一次加载url时下面方法会执行            public void imageLoaded(Drawable imageDrawable)            {                ((ImageView) findViewById(id)).setImageDrawable(imageDrawable);            }        });        if (cacheImage != null)        {            ((ImageView) findViewById(id)).setImageDrawable(cacheImage);        }    }}

AsyncImageLoader.java

package com.liefyuan.imagetest;import android.graphics.drawable.Drawable;import android.os.Handler;import android.os.SystemClock;import android.util.Log;import java.lang.ref.SoftReference;import java.net.URL;import java.util.HashMap;import java.util.Map;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * Created by yuanlifu on 2017/7/17. * */public class AsyncImageLoader {    // 为了加快速度,在内存中开启缓存(主要应用于重复图片较多时,或者同一个图片要多次被访问,比如在ListView时来回滚动)    public Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();    private ExecutorService executorService = Executors.newFixedThreadPool(5); // 固定五个线程来执行任务    private final Handler handler = new Handler();    /**     *     * @param imageUrl     *            图像url地址     * @param callback     *            回调接口     * @return 返回内存中缓存的图像,第一次加载返回null     */    public Drawable loadDrawable(final String imageUrl, final ImageCallback callback)    {        // 如果缓存过就从缓存中取出数据        if (imageCache.containsKey(imageUrl))        {            SoftReference<Drawable> softReference = imageCache.get(imageUrl);            if (softReference.get() != null)            {                Log.i("MainActivity", "图片存在缓存中.");                return softReference.get();            }        }        // 缓存中没有图像,则从网络上取出数据,并将取出的数据缓存到内存中        executorService.submit(new Runnable()        {            public void run()            {                try                {                    Log.i("MainActivity", "下载图片...");                    final Drawable drawable = loadImageFromUrl(imageUrl);                    imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));                    handler.post(new Runnable()                    {                        public void run()                        {                            callback.imageLoaded(drawable);                        }                    });                } catch (Exception e)                {                    throw new RuntimeException(e);                }            }        });        return null;    }    // 从网络上取数据方法    protected Drawable loadImageFromUrl(String imageUrl)    {        try        {            // 测试时,模拟网络延时,实际时这行代码不能有            SystemClock.sleep(2000);            return Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");        } catch (Exception e)        {            throw new RuntimeException(e);        }    }    // 对外界开放的回调接口    public interface ImageCallback    {        // 注意 此方法是用来设置目标对象的图像资源        public void imageLoaded(Drawable imageDrawable);    }}

视图文件
activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:orientation="vertical"    tools:context="com.liefyuan.imagetest.MainActivity">    <TextView        android:text="图片区域开始"        android:id="@+id/textView2"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <ImageView        android:id="@+id/imageView1"        android:layout_height="wrap_content"        android:src="@drawable/icon"        android:layout_width="wrap_content" />    <ImageView        android:id="@+id/imageView2"        android:layout_height="wrap_content"        android:src="@drawable/icon"        android:layout_width="wrap_content" />    <ImageView        android:id="@+id/imageView3"        android:layout_height="wrap_content"        android:src="@drawable/icon"        android:layout_width="wrap_content" />    <ImageView        android:id="@+id/imageView4"        android:layout_height="wrap_content"        android:src="@drawable/icon"        android:layout_width="wrap_content" />    <ImageView        android:id="@+id/imageView5"        android:layout_height="wrap_content"        android:src="@drawable/icon"        android:layout_width="wrap_content" />    <TextView        android:text="图片区域结束"        android:id="@+id/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content" /></LinearLayout>
原创粉丝点击