DiskLrucCache使用Demo

DiskLrucCache使用的Demo,这个demo是从网络获取一张图片,保存到本地缓存中(sdcard和内存),当下载成功后,再打开不会重新向网络请求图片,而是世界使用本地资源。

要使用DiskLrucCache需要先下载此类.   下载地址点这里

主类:

/**
 * DiskLrucCache使用Demo
 *
 * @author pangzf
 * @date 2014年8月12日 下午2:13:26
 */
public class DemoActivity extends Activity {

    private DiskLruCache mDiskLrucache;
    private ImageView mIvShow;
    private String mBitMapUrl;
    private String mKey;
    private ProgressDialog mPd;
    private Handler mHandler = new Handler() {

        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            // 10.下载图片之后展示
            boolean isSuccess = (boolean) msg.obj;
            if (isSuccess) {
                Snapshot snapshot;
                try {
                    snapshot = mDiskLrucache.get(mKey);
                    InputStream is = snapshot.getInputStream(0);
                    mIvShow.setImageBitmap(BitmapFactory.decodeStream(is));
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if (mPd != null && mPd.isShowing()) {
                mPd.dismiss();
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo);
        mIvShow = (ImageView) findViewById(R.id.iv_show);
        mPd = new ProgressDialog(DemoActivity.this);
        try {
            // 1.存放缓存的目录
            File directory = DiskLrucacheUtils.getDiskCache(DemoActivity.this,
                    "bitmap");
            // 2.版本号
            int appVersion = DiskLrucacheUtils.getAppVersion(DemoActivity.this);
            int valueCount = 1;
            // 3.缓存的最大值,这里设置10m
            long maxSize = 10 * 1024 * 1024;
            // 4.打开disklrucache
            mDiskLrucache = DiskLruCache.open(directory, appVersion,
                    valueCount, maxSize);
            mBitMapUrl = "https://raw.githubusercontent.com/pangzaifei/LineChartView/master/LineChartView/effice_picture/a.jpg";
            if (mDiskLrucache != null) {
                // 5.如果在缓存中存在就用缓存中的bitmap,如果不存在上网上下载
                mKey = DiskLrucacheUtils.getKey(mBitMapUrl);
                Snapshot snapshot = mDiskLrucache.get(mKey);
                if (snapshot != null) {
                    InputStream is = snapshot.getInputStream(0);
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    if (bitmap != null) {
                        mIvShow.setImageBitmap(bitmap);
                    }
                } else {
                    mPd.show();
                    new Thread() {
                        public void run() {
                            // 6.下载图片
                            mPd.setMessage("正在加载数据....");
                            userDiskLrucache();
                        };
                    }.start();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void userDiskLrucache() {
        try {

            String bitMapUrl = "https://raw.githubusercontent.com/pangzaifei/LineChartView/master/LineChartView/effice_picture/a.jpg";
            String key = DiskLrucacheUtils.getKey(bitMapUrl);
            Editor edit = mDiskLrucache.edit(key);
            // 7.从服务器下载图片
            boolean isSuccess = DiskLrucacheUtils.downloadBitmap(bitMapUrl,
                    edit.newOutputStream(0));
            if (isSuccess) {
                // 8.提交到缓存
                edit.commit();
                // 9.下载成功去展示图片
                Message msg = mHandler.obtainMessage();
                msg.obj = true;
                mHandler.sendMessage(msg);
            } else {
                edit.abort();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        try {
            if (mDiskLrucache != null) {
                mDiskLrucache.flush();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        try {
            if (mDiskLrucache != null) {

                mDiskLrucache.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }
}

使用DiskLrucache自己写的工具类.

package com.pangzaifei.disklrucachedemo.libcore;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;

/**
 * diskLrucache的工具类
 *
 * @author pangzf
 * @date 2014年8月12日 上午10:58:50
 */
public class DiskLrucacheUtils {
    /**
     * 获得缓存目录,当sdcard存在的时候使用,sdcard图片缓存,如果sdcard不存在使用data/data下的图片缓存
     *
     * @param context
     * @param uniqueName
     * @return
     */
    public static File getDiskCache(Context context, String uniqueName) {
        String path;
        if (Environment.getExternalStorageDirectory().equals(
                Environment.MEDIA_MOUNTED)) {
            // 存在sdcard
            path = Environment.getExternalStorageDirectory().getPath();
        } else {
            // 不存在sdcard使用手机内存
            path = context.getCacheDir().getPath();
        }
        return new File(path + File.separator + uniqueName);
    }

    /**
     * 获得app版本号
     *
     * @param context
     * @return
     * @throws NameNotFoundException
     */
    public static int getAppVersion(Context context)
            throws NameNotFoundException {
        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
                context.getPackageName(), 0);
        return packageInfo.versionCode;

    }

    /**
     * 将图片url进行md5加密生成一个字符串,因为有的url地址里面存在特殊字符
     *
     * @param urlStr
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String getKey(String urlStr) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("md5");
        messageDigest.update(urlStr.getBytes());
        return bytesToString(messageDigest.digest());
    }

    /**
     * byte转string
     *
     * @param bytes
     */
    private static String bytesToString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 下载图片到cache
     *
     * @param imageString
     * @param ops
     * @return
     */
    public static boolean downloadBitmap(String imageString, OutputStream ops) {
        URL url;
        HttpURLConnection conn = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            url = new URL(imageString);
            conn = (HttpURLConnection) url.openConnection();

            bis = new BufferedInputStream(conn.getInputStream());
            bos = new BufferedOutputStream(ops);

            int b;
            while ((b = bis.read()) != -1) {
                bos.write(b);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
                if (bos != null) {
                    bos.close();
                }
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;

    }
}

源码下载地址

感谢guolin的博客对我的帮助。

DiskLrucCache使用Demo

时间: 2024-09-06 13:18:02

DiskLrucCache使用Demo的相关文章

微信h5支付demo微信H5支付demo非微信浏览器支付demo微信wap支付

一.首先先确定H5支付权限已经申请!(需要微信h5支付demo的可以加 851 488 243 备注:h5支付) 二.开发流程 1.用户在商户侧完成下单,使用微信支付进行支付 2.由商户后台向微信支付发起下单请求(调用统一下单接口)注:交易类型trade_type=MWEB 3.统一下单接口返回支付相关参数给商户后台,如支付跳转url(参数名"mweb_url"),商户通过mweb_url调起微信支付中间页 4.中间页进行H5权限的校验,安全性检查(此处常见错误请见下文) 5.如支付成

Maven+SpringMVC+Freemarker入门Demo

1 参考http://blog.csdn.net/haishu_zheng/article/details/51490299,用第二种方法创建一个名为mavenspringmvcfreemarker的Maven工程. 2 文件目录结构如下图所示 3 在pom.xml中添加springmvc和freemarker的依赖包,添加完之后的完整内容为 [html] view plain copy <project xmlns="http://maven.apache.org/POM/4.0.0&q

Spring Security入门Demo

一.spring Security简介 SpringSecurity,这是一种基于Spring AOP和Servlet过滤器的安全框架.它提供全面的安全性解决方案,同时在Web请求级和方法调用级处理身份确认和授权.在Spring Framework基础上,Spring Security充分利用了依赖注入(DI,Dependency Injection)和面向切面技术. 二.建立工程 参考http://blog.csdn.net/haishu_zheng/article/details/51490

沫沫金Echarts移动端demo

鄙视百度!!! 官网给的Demo支持自动大小,确不给完整的源码XXX 自己动手,丰衣足食 http://echarts.baidu.com/demo.html#bar-tick-align 用最基本的柱状图官网代码 简单两步,实现移动端自适应大小 //1.下载Echarts <script src="dep/Echarts/echarts-all-3.js"></script> //2.chart容器宽度自适应 <!-- 为ECharts准备一个具备大小(

Flask---使用Bootstrap新建第一个demo

Flask---使用Bootstrap新建第一个demo 参考自http://www.jianshu.com/p/417bcbad82fb 还有<Flask web开发> 前端用到Bootstrap开源框架,Bootstrap是客户端框架,后台当然就是Flask了. 服务器需要做的只是提供引用了Bootstrap层叠样式表(CSS)和JS文件的html响应,并且在html.css和js代码中实例化需要的组件,这些操作的最理想的执行环境就是模板 关于模板的介绍及其实现原理:https://kb.

struts2和hibernate整合的小Demo

jar包下载地址 创建一个web项目. 导入jar包 配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="

移动端上传照片 预览+draw on Canvas demo(解决iOS等设备照片旋转90度的bug)

背景: 本人的一个移动端H5项目,需求如下: 手机相册选取或拍摄照片后在页面上预览 然后绘制在canvas画布上. 这里,我们先看一个demo(http://jsfiddle.net/q3011893/83qfqpk8/embedded/) 操作步骤: 1.点击选择文件,拍摄一张照片,此时"预览:"文字下会显示你刚才拍摄的照片: 2.再点击"draw on Canvas",该按钮下的画布会绘制你刚才拍摄的照片. 正常的结果: 正文: 让input file支持拍照+

爬虫2:html页面+beautifulsoap模块+post方式+demo

爬取html页面,有时需要设置参数post方式请求,生成json,保存文件中. 1)引入模块 import requests from bs4 import BeautifulSoup url_ = 'http://www.c.....................' 2)设置参数 datas = { 'yyyy':'2014', 'mm':'-12-31', 'cwzb':"incomestatements", 'button2':"%CC%E1%BD%BB",

Nancy之基于Self Hosting的补充小Demo

前面把Hosting Nancy with ASP.NET.Self Hosting Nancy和Hosting Nancy with OWIN 以demo的形式简单描述了一下. 这篇是为Self Hosting Nancy.和Owin 下面的Self Hosting作个补充. 首先是Self Hosting Nancy的补充: 这里主要是介绍一下Topshelf 官网:http://topshelf-project.com/ GitHub地址:https://github.com/Topshe