从零开始编写图片加载库(四)之图片缓存MemoryCache

本文介绍如何在有限的手机内存中优化图片加载过程,通过内存缓存机制实现快速加载,减少网络请求,提升用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

图片加载通过内存加载是最快的,然而手机的内存并不是取之不尽的,所以在开发过程中还需要注意就是内存的使用问题,本节将不涉及内存使用和优化问题,本节只介绍图片下载后从内存中加载。

第一步:编写MemoryCache类

package cn.sundroid.cache;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import android.graphics.Bitmap;

public class WeakMemoryCache {

    /**保存Bitmap的对象*/
    private final Map<String, Reference<Bitmap>> softMap = Collections
            .synchronizedMap(new HashMap<String, Reference<Bitmap>>());

    /**
     * 根据键获得Bitmap
     * @param key 查询需要的键
     * @return
     */
    public Bitmap get(String key) {
        if (key == null) {
            throw new NullPointerException("key == null");
        }
        Bitmap result = null;
        Reference<Bitmap> reference = softMap.get(key);
        if (reference != null) {
            result = reference.get();
        }
        return result;
    }

    /**
     * 
     * 保存Bitmap到内存
     * @param key 键
     * @param value 值
     * @return
     */
    public boolean put(String key, Bitmap value) {
        if (key == null || value == null) {
            throw new NullPointerException("key == null || value == null");
        }
        softMap.put(key, new WeakReference<Bitmap>(value));
        return false;

    }

    /**
     * 根据key从内存中移除Bitmap对象
     * @param key
     * @return
     */
    public Bitmap remove(String key) {
        Reference<Bitmap> bmpRef = softMap.remove(key);
        return bmpRef == null ? null : bmpRef.get();
    }

    /**
     * 清空操作
     */
    public void clear() {
        softMap.clear();
    }


}

第二步:编写实现,下载图片后在handler里面接收更新UI通知,从cache里面取图片。

package cn.sundroid.loader;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import cn.sundroid.cache.WeakMemoryCache;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;

public class MainActivity extends Activity {

    private ImageView image;
    private final String TAG = "ImageLoader";

    private WeakMemoryCache cache = new WeakMemoryCache();
    private final String IMAGE_CACHE_KEY = "image_cache_key";
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            Bitmap bitmap = cache.get(IMAGE_CACHE_KEY);
            Log.e(TAG, "get bitmap from memory cache");
            image.setImageBitmap(bitmap);
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = (ImageView) findViewById(R.id.image);
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    //网络连接
                    HttpURLConnection connection = (HttpURLConnection) new URL(
                            "http://pic5.nipic.com/20091228/2588536_142951087553_2.jpg")
                            .openConnection();
                    connection.setConnectTimeout(3 * 1000);
                    connection.setReadTimeout(20 * 1000);
                    //读取文件流
                    InputStream is = connection.getInputStream();
                    //通过BitmapFactory解码二进制字节流成Bitmap
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    Log.e(TAG, "put bitmap into memory cache");
                    cache.put(IMAGE_CACHE_KEY, bitmap);
                    //发送一个消息给Handler用于更新消息
                    handler.sendEmptyMessage(0x10);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }

}

效果图

源代码下载==>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值