android 缓存使用简介

点击打开链接


网络图片在开发过程中,一般都将图片缓存到本地sd卡中(经常要使用的图片),方便下次直接引用而不再次请求网络耗费资源。而如果是自己开发搜索功能里有涉及到图片的显示,可以直接Map<String, SoftReference<Drawable>>,即软引用。

软引用重要代码代码:

package com.test.load;

 

import java.lang.ref.SoftReference;

import java.net.URL;

import java.util.HashMap;

import java.util.Map;

 

import android.graphics.drawable.Drawable;

import android.os.Handler;

import android.os.Message;

 

public class ThreadImgLoader {

  private Map<String, SoftReference<Drawable>> imageCache=new HashMap<String, SoftReference<Drawable>>();

  

   public Drawable loadDrawable(final String imgUrl, final ImageCallback callback){

      if (imageCache.containsKey(imgUrl)) {

        SoftReference<Drawable> sf=imageCache.get(imgUrl);

        if (sf.get()!=null) {

           return sf.get();

        }

      }

      final Handler handler=new Handler(){

        public void handleMessage(Message msg) {

           callback.imageLoaded((Drawable) msg.obj);

        }

      };

      new Thread(){

        public void run() {

           Drawable drawable=loadImgFromUrl(imgUrl);

           if (drawable!=null) {

              imageCache.put(imgUrl, new SoftReference<Drawable>(drawable));

              Message msg=handler.obtainMessage(0, drawable);

              handler.sendMessage(msg);

           }

        }

      }.start();

      return null;

   }

  

   public Drawable loadImgFromUrl(String imgUrl) {

      try {

        return Drawable.createFromStream(new URL(imgUrl).openStream(), "src");

      } catch (Exception e) {

        return null;

      }

   }

  

   public interface ImageCallback{

      public void imageLoaded(Drawable drawable);

   }

}

 下面是缓存到SD卡的重要代码,当然你也可以搜索一下,这方面的东西很多。WeakHashMap也是使用了软引用,你可以去看它的源代码:

package com.test;

 

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStream;

import java.util.WeakHashMap;

 

import android.graphics.Bitmap;

import android.graphics.Bitmap.CompressFormat;

import android.graphics.BitmapFactory;

import android.os.Environment;

 

public class MyImgCache extends WeakHashMap<String, Bitmap> {

   private static MyImgCache myImgCache=new MyImgCache();

   private static final String CACHE_FILE="/MyXiaoCaiImg";

   public static MyImgCache getInstance(){

      return myImgCache;

   }

  

   public boolean isBitmapExist(String url) {

      boolean isexist=false;

      String name=changeUrlName(url);

      String filePath=isMakeFile();

      File file=new File(filePath, name);

      if (containsKey(url)) {

        isexist=true;

      }else if (file.exists()) {

        String path=file.getAbsolutePath();

        System.out.println(path);

        Bitmap bitmap=BitmapFactory.decodeFile(path);

        if (bitmap!=null) {

           put(url, bitmap, false);

           isexist=true;

        }

      }

      return isexist;

   }

 

   private String changeUrlName(String url) {

      String name = url.replaceAll(":", "_");

      name = name.replaceAll("//", "_");

      name = name.replaceAll("/", "_");

      name = name.replaceAll("=", "_");

      name = name.replaceAll(",", "_");

      name = name.replaceAll("&", "_");

      return name;

   }

  

   private String isMakeFile() {

      String rootpath = null;

      if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

        rootpath = Environment.getExternalStorageDirectory().toString();

      }

      String filepath = rootpath + CACHE_FILE;

      File file = new File(filepath);

      if (!file.exists()) {

        file.mkdirs();

      }

      return filepath;

   }

 

   public Bitmap put(String key, Bitmap value) {

      String name=changeUrlName(key);

      String filePath=isMakeFile();

      File file = new File(filePath, name);

      OutputStream outputStream = null;

      try {

        outputStream = new FileOutputStream(file);

        value.compress(CompressFormat.JPEG, 100, outputStream);

        outputStream.flush();

        outputStream.close();

        outputStream = null;

      } catch (Exception e) {

        e.printStackTrace();

      }

      return super.put(key, value);

   }

 

   public Bitmap put(String key, Bitmap value, boolean b) {

      if (b) {

        return this.put(key, value);

      }else {

        return super.put(key, value);

      }

   }

 

}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Android使用内存缓存图片,可以使用 LruCache 或自定义实现的内存缓存。 1. LruCache LruCache 是 Android 提供的一个可以回收不常用的 Bitmap 对象的缓存类,它的大小是通过构造函数中传入的 maxsize 来指定的。 以下是使用 LruCache 的示例代码: ``` public class ImageCache { private LruCache<String, Bitmap> mMemoryCache; public ImageCache() { int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); int cacheSize = maxMemory / 8; // 可以根据需求进行调整 mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { @Override protected int sizeOf(String key, Bitmap bitmap) { // 返回 Bitmap 对象的大小,单位为 KB return bitmap.getByteCount() / 1024; } }; } public void addToMemoryCache(String key, Bitmap bitmap) { if (getFromMemoryCache(key) == null) { mMemoryCache.put(key, bitmap); } } public Bitmap getFromMemoryCache(String key) { return mMemoryCache.get(key); } } ``` 2. 自定义实现的内存缓存 自定义实现的内存缓存可以根据需求进行调整和优化,以下是一个简单的示例代码: ``` public class ImageCache { private Map<String, Bitmap> mMemoryCache; public ImageCache() { mMemoryCache = new HashMap<String, Bitmap>(); } public void addToMemoryCache(String key, Bitmap bitmap) { if (getFromMemoryCache(key) == null) { mMemoryCache.put(key, bitmap); } } public Bitmap getFromMemoryCache(String key) { return mMemoryCache.get(key); } } ``` 使用内存缓存时,需要注意内存泄漏的问题,可以在 Activity 或 Fragment 的 onDestroy() 方法中释放缓存
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值