Android 缓存图像并加载它们

Android 缓存图像并加载它们,android,caching,image-processing,image-gallery,Android,Caching,Image Processing,Image Gallery,我使用Fedora的lazylist下载了图像并将它们缓存到缓存文件夹中,但现在,我没有将它们显示到listview中。我需要使用viewpager+touchimageview。我已经找到了这个示例,但不知道如何将它们加载到AndroidTouchGallery中。有人能给我指点吗 这是filecache.java package com.fedorvlasov.lazylist; import java.io.File; import java.net.URLEncoder; impor

我使用Fedora的lazylist下载了图像并将它们缓存到缓存文件夹中,但现在,我没有将它们显示到listview中。我需要使用viewpager+touchimageview。我已经找到了这个示例,但不知道如何将它们加载到AndroidTouchGallery中。有人能给我指点吗

这是filecache.java

package com.fedorvlasov.lazylist;

import java.io.File;
import java.net.URLEncoder;

import android.content.Context;

public class FileCache {

    private File cacheDir;

    public FileCache(Context context){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }

    public File getFile(String url){
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        //String filename=String.valueOf(url.hashCode());
        //Another possible solution (thanks to grantland)
        String filename = URLEncoder.encode(url);
        File f = new File(cacheDir, filename);
        return f;

    }

    public void clear(){
        File[] files=cacheDir.listFiles();
        if(files==null)
            return;
        for(File f:files)
            f.delete();
    }

}
内存缓存(也由fedora提供)

package com.fedorvlasov.lazylist;
导入java.util.Collections;
导入java.util.Iterator;
导入java.util.LinkedHashMap;
导入java.util.Map;
导入java.util.Map.Entry;
导入android.graphics.Bitmap;
导入android.util.Log;
公共类内存缓存{
私有静态最终字符串TAG=“MemoryCache”;
私有映射缓存=Collections.synchronizedMap(
新LinkedHashMap(10,1.5f,true));//LRU排序的最后一个参数true
私有长大小=0;//当前分配的大小
private long limit=1000000;//最大内存(字节)
公共内存缓存(){
//使用可用堆大小的25%
setLimit(Runtime.getRuntime().maxMemory()/4);
}
公共无效设置限制(长新限制){
限制=新的限制;
Log.i(标记“MemoryCache将使用最多”+限制/1024./1024.+“MB”);
}
公共位图获取(字符串id){
试一试{
如果(!cache.containsKey(id))
返回null;
//NullPointerException有时发生在这里http://code.google.com/p/osmdroid/issues/detail?id=78 
返回cache.get(id);
}捕获(NullPointerException ex){
例如printStackTrace();
返回null;
}
}
公共void put(字符串id、位图){
试一试{
if(cache.containsKey(id))
size-=getSizeInBytes(cache.get(id));
cache.put(id,位图);
size+=getSizeInBytes(位图);
checkSize();
}捕获(可丢弃){
th.printStackTrace();
}
}
私有void checkSize(){
Log.i(标记“cache size=“+size+”length=“+cache.size());
如果(大小>限制){
迭代器iter=cache.entrySet().Iterator();//最近访问最少的项将是第一个迭代的项
while(iter.hasNext()){
Entry=iter.next();
size-=getSizeInBytes(entry.getValue());
iter.remove();

如果(大小我建议您使用此库


在这里,您可以浏览以下示例:
package com.fedorvlasov.lazylist;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import android.graphics.Bitmap;
import android.util.Log;

public class MemoryCache {

    private static final String TAG = "MemoryCache";
    private Map<String, Bitmap> cache=Collections.synchronizedMap(
            new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
    private long size=0;//current allocated size
    private long limit=1000000;//max memory in bytes

    public MemoryCache(){
        //use 25% of available heap size
        setLimit(Runtime.getRuntime().maxMemory()/4);
    }

    public void setLimit(long new_limit){
        limit=new_limit;
        Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
    }

    public Bitmap get(String id){
        try{
            if(!cache.containsKey(id))
                return null;
            //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
            return cache.get(id);
        }catch(NullPointerException ex){
            ex.printStackTrace();
            return null;
        }
    }

    public void put(String id, Bitmap bitmap){
        try{
            if(cache.containsKey(id))
                size-=getSizeInBytes(cache.get(id));
            cache.put(id, bitmap);
            size+=getSizeInBytes(bitmap);
            checkSize();
        }catch(Throwable th){
            th.printStackTrace();
        }
    }

    private void checkSize() {
        Log.i(TAG, "cache size="+size+" length="+cache.size());
        if(size>limit){
            Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated  
            while(iter.hasNext()){
                Entry<String, Bitmap> entry=iter.next();
                size-=getSizeInBytes(entry.getValue());
                iter.remove();
                if(size<=limit)
                    break;
            }
            Log.i(TAG, "Clean cache. New size "+cache.size());
        }
    }

    public void clear() {
        try{
            //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
            cache.clear();
            size=0;
        }catch(NullPointerException ex){
            ex.printStackTrace();
        }
    }

    long getSizeInBytes(Bitmap bitmap) {
        if(bitmap==null)
            return 0;
        return bitmap.getRowBytes() * bitmap.getHeight();
    }
}
public class UrlTouchImageView extends RelativeLayout {
    protected ProgressBar mProgressBar;
    protected TouchImageView mImageView;

    protected Context mContext;
    UrlPagerAdapter pagerAdapter;
    String[] mImageIds;
    Bitmap bm;
    ArrayList<String>  mStringList= new ArrayList<String>();


    public UrlTouchImageView(Context ctx, UrlPagerAdapter pagerAdapter)
    {
        super(ctx);
        mContext = ctx;
        this.pagerAdapter = pagerAdapter;

        init();

    }
    public UrlTouchImageView(Context ctx, AttributeSet attrs)
    {
        super(ctx, attrs);
        mContext = ctx;
        init();
    }

    public TouchImageView getImageView() 
    { 
        return mImageView; 
    }


    protected void init() {

        mImageView = new TouchImageView(mContext);
        LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        mImageView.setLayoutParams(params);
        this.addView(mImageView);
        mImageView.setVisibility(GONE);


        mProgressBar = new ProgressBar(mContext, null, android.R.attr.progressBarStyleHorizontal);
        params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.CENTER_VERTICAL);
        params.setMargins(30, 0, 30, 0);
        mProgressBar.setLayoutParams(params);
        mProgressBar.setIndeterminate(true);
        this.addView(mProgressBar);
    }

    public void setUrl(String imageUrl)
    {
        new ImageLoadTask().execute(imageUrl);
    }

    //No caching load
    public class ImageLoadTask extends AsyncTask<String, Integer, Bitmap>
    {
        //RETRIEVES LINK FROM GALLERYACTIVITY
        //READ MNT/SDCARD/....

        @Override
        protected Bitmap doInBackground(String... strings) {
            bm = null;
            String url = strings[0];
            //Log.d("url",url);

            bm = BitmapFactory.decodeFile(url);
            return bm;

        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {

            mImageView.setImageBitmap(bm);
            mImageView.setVisibility(VISIBLE);
            mProgressBar.setVisibility(GONE);
        }
    }
}