图片的缓存与下载

来源:互联网 发布:淘宝客淘口令怎么设置 编辑:程序博客网 时间:2024/04/30 23:45

       图片的缓存与下载,其中包括四个部分内存的缓存、SD卡缓存、内存和SD卡的双缓存以及自定义图片缓存实现这四种选中代码如下:

MainActivity:

public class MainActivity extends AppCompatActivity {    private ImageView mImageView;    private String url = "http://www.qqpk.cn/Article/UploadFiles/201310/20131027143421776.jpg";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mImageView = (ImageView) findViewById(R.id.image_view);         ImageLoader imageLoader =new ImageLoader();         //使用内存缓存图片        imageLoader.setImageCache(new MemoryCache());        //使用SD卡缓存图片//        imageLoader.setImageCache(new DiskCache() );        //使用双缓存缓存图片//        imageLoader.setImageCache(new DoubleCache());          //使用自定义的图片缓存实现//        imageLoader.setImageCache(new ImageCache() {//            @Override//            public Bitmap get(String url) {//                return null;//            }////            @Override//            public void put(String url, Bitmap bitmap) {////            }//        });        imageLoader.displayImage(url,mImageView);    }}

activity_main:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    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:gravity="center"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin"    tools:context="com.example.picturetext.MainActivity">    <ImageView        android:id="@+id/image_view"        android:layout_width="match_parent"        android:layout_height="match_parent"        /></RelativeLayout>
ImageLoader:

public class ImageLoader {    //图片缓存    ImageCache mImageCache = new MemoryCache();    //线程池,线程的数量为CPU的数量    ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());    //注入缓存实现(想用哪一种缓存,就有这个方法添加)    public void setImageCache(ImageCache imageCache){        mImageCache = imageCache;    }    public void  displayImage(final String url,final ImageView imageView){        Bitmap bitmap =mImageCache.get(url);        if (bitmap != null) {            imageView.setImageBitmap(bitmap);            return;        }        //图片没有缓存,提交到线程池中下载图片        submitLoadRequest(url,imageView);    }    private void submitLoadRequest(final String url, final ImageView imageView) {        imageView.setTag(url);        mExecutorService.submit(new Runnable() {            @Override            public void run() {           Bitmap bitmap = downImage(url);                if (bitmap == null) {                    return;                }                if (imageView.getTag().equals(url)){                    imageView.setImageBitmap(bitmap);                }                mImageCache.put(url,bitmap);            }        });    }    private Bitmap downImage(String imageUrl) {        Bitmap bitmap = null;        try {            URL url = new URL(imageUrl);            final HttpURLConnection connection = (HttpURLConnection) url.openConnection();            bitmap = BitmapFactory.decodeStream(connection.getInputStream());            connection.disconnect();        } catch (Exception e) {            e.printStackTrace();        }        return bitmap;    }}

ImageCache:

public interface ImageCache {    public Bitmap get(String url);    public void put(String url,Bitmap bitmap);}

MemoryCache:

/** * 内存缓存MemoryCache */public class MemoryCache implements ImageCache {    private LruCache<String,Bitmap> mMemoryCache;    public MemoryCache() {        initMemoryCache();    }    private void initMemoryCache() {        //计算可使用的最大内存        final int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);        //取四分之一的卡用内存用作图片缓存        final int cacheSize = maxMemory/4;        mMemoryCache = new LruCache<String,Bitmap>(cacheSize){            @Override            protected int sizeOf(String key, Bitmap bitmap) {                return bitmap.getRowBytes()*bitmap.getHeight()/1024;            }        };    }    @Override    public Bitmap get(String url) {         return mMemoryCache.get(url);    }    @Override    public void put(String url, Bitmap bitmap) {        mMemoryCache.put(url,bitmap);    }}
DiskCache:

/** * SD卡缓存类 */public class DiskCache implements ImageCache{    static String cachaDir = "sdcard/cache";    //从缓存中获取图片    public Bitmap get(String url){        return BitmapFactory.decodeFile(cachaDir+url);    }    //将图片缓存到内存中    public void put(String url,Bitmap bitmap){        FileOutputStream fileOutputStream = null;        try {            fileOutputStream = new FileOutputStream(cachaDir+url);            bitmap.compress(Bitmap.CompressFormat.PNG,100,fileOutputStream);        } catch (FileNotFoundException e) {            e.printStackTrace();        }finally {            CloseUtils.closeQuietly(fileOutputStream            );        }    }}
DoubleCache:

/** * 双缓存,获取图片实现从内存中获取,如果内存中没有还缓存图片,再从SD卡    中获取 * 双缓存图片也就是在内存和SD卡中都缓存一份 */public class DoubleCache implements ImageCache{    ImageCache mImageCache = new MemoryCache();    DiskCache mDiskCache = new DiskCache();    //先从缓存中获取图片,如果没有,再从SD卡中获取    public Bitmap get(String url){        Bitmap bitmap = mImageCache.get(url);        if (bitmap == null) {            bitmap = mDiskCache.get(url);        }        return bitmap;    }    //将图片缓存的内存和SD卡中    public  void  put(String url,Bitmap bitmap){        mImageCache.put(url,bitmap);        mDiskCache.put(url,bitmap);    }}
CloseUtils:

/** * 创建此类是为了减少代码的复用,是代码更加简洁 */public final class CloseUtils {    public CloseUtils() {    }    /**     * 关闭Closeable 对象     * @param closeable     */    public static void closeQuietly(Closeable closeable){        if (closeable != null) {            try {                closeable.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}
AndroidManifest:中的权限

<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

点击该链接会到我这个项目:http://download.csdn.net/detail/zgy621101/9691867



0 0