1。之前因为做一个项目的过程中遇到要频繁重复下载的文件比如图片等,需要在本地缓存,除了用户体验也保证了省流量。

这个demo是用下载网络图片来演示。

一共有六张网络图片,加载图片时,会判断图片是否下载到本地的文件夹中,如果下载了,直接从文件中读取,如果没有就会去下载,下载完之后通过一个handler通知adapter的notifyDataSetChanged()方法,来对listActivity进行通知,来显示对应的列表。

具体代码如下;

public class CatheAdapter extends BaseAdapter {
    private List<String> mUrl = new ArrayList<String>();
    private LayoutInflater mInflater;
    private Context context;

    public CatheAdapter(Context context) {
        mUrl.add("http://papercut.jd-app.com/learn/Goat_8/2.png");
        mUrl.add("http://papercut.jd-app.com/learn/Goat_8/3.png");
        mUrl.add("http://papercut.jd-app.com/learn/Goat_8/4.png");
        mUrl.add("http://papercut.jd-app.com/learn/Goat_8/5.png");
        mUrl.add("http://papercut.jd-app.com/learn/Goat_8/6.png");
        mUrl.add("http://papercut.jd-app.com/learn/Goat_8/7.png");
        this.context = context;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return mUrl.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.item,null);
        }
        ImageView image = (ImageView) convertView.findViewById(R.id.image);
        image.setImageBitmap(getBitmap(position));
        return convertView;
    }
    private Bitmap getBitmap(int position){
        Bitmap bitmap = null;
        //File dir = Environment.getExternalStorageDirectory();
        String fileName = File.separator+"sdcard"+File.separator+mUrl.get(position).hashCode();
        if (new File(fileName).exists()) {
            bitmap = BitmapFactory.decodeFile(fileName);
        }else {
            bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
            new DownLoadImage(this, mUrl.get(position)).start();
        }
        return bitmap;
    }
}

这是adaopter类的代码。

public class DownLoadImage extends Thread{
    private CatheAdapter catheAdapter;
    private String mUrl;
    private String fileName;
    private File dir;
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            catheAdapter.notifyDataSetChanged();
        }
    };

    public DownLoadImage(CatheAdapter catheAdapter, String mUrl) {
        this.catheAdapter = catheAdapter;
        this.mUrl = mUrl;
        //dir = Environment.getExternalStorageDirectory();
        fileName = File.separator+"sdcard"+File.separator+mUrl.hashCode();
    }

    @Override
    public void run() {
        URL url;
        try {
            url = new URL(mUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            conn.setUseCaches(false);
            InputStream is = conn.getInputStream();
            FileOutputStream fos = new FileOutputStream(fileName);
            byte[] buffer = new byte[8192];
            int count = 0;
            while ((count = is.read(buffer))>-1) {
                fos.write(buffer,0,count);
            }
            fos.flush();
            fos.close();
            is.close();
            conn.disconnect();
            handler.sendEmptyMessage(0);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

这是下载图片的类,图片放在了sdcard的下面,因为是演示所以这么写了。建议大家如果要新建一个文件。

最后是主要的类。

public class MainActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.setListAdapter(new CatheAdapter(this));
    }
}

布局代码如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="liu.example.cathetest.MainActivity" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</RelativeLayout>

这是每一个item的布局代码;

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="liu.example.cathetest.MainActivity" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</RelativeLayout>

最后主要权限,除了Internet权限还有访问sdcard的权限。

android 缓存实现的更多相关文章

  1. Android 缓存

    1.Android缓存机制&一个缓存框架推荐 http://blog.csdn.net/shakespeare001/article/details/51695358 2.ASimpleCac ...

  2. Android缓存处理

    Android缓存: 採用缓存,能够进一步大大缓解数据交互的压力,又能提供一定的离线浏览.下边我简略列举一下缓存管理的适用环境: 1. 提供网络服务的应用 2. 数据更新不须要实时更新.哪怕是3-5分 ...

  3. android缓存具体解释

    Android缓存: 採用缓存,能够进一步大大缓解数据交互的压力.又能提供一定的离线浏览.下边我简略列举一下缓存管理的适用环境: 1. 提供网络服务的应用 2. 数据更新不须要实时更新,哪怕是3-5分 ...

  4. 【转】彻底解析Android缓存机制——LruCache

    彻底解析Android缓存机制——LruCache 关于Android的三级缓存,其中主要的就是内存缓存和硬盘缓存.这两种缓存机制的实现都应用到了LruCache算法,今天我们就从使用到源码解析,来彻 ...

  5. Android缓存学习入门(二)

    本文主要包括以下内容 内存缓存策略 文件缓存策略 内存缓存策略 当有一个图片要去从网络下载的时候,我们并不会直接去从网络下载,因为在这个时代,用户的流量是宝贵的,耗流量的应用是不会得到用户的青睐的.那 ...

  6. Android缓存学习入门

    本文主要包括以下内容 利用LruCache实现内存缓存 利用DiskLruCache实现磁盘缓存 LruCache与DiskLruCache结合实例 利用了缓存机制的瀑布流实例 内存缓存的实现 pub ...

  7. Android 缓存目录 Context.getExternalFilesDir()和Context.getExternalCacheDir()方法

    一.基础知识 应用程序在运行的过程中如果需要向手机上保存数据,一般是把数据保存在SDcard中的.大部分应用是直接在SDCard的根目录下创建一个文件夹,然后把数据保存在该文件夹中.这样当该应用被卸载 ...

  8. Android缓存技术

    android应用程序中 1. 尽可能的把文件缓存到本地.可以是 memory,cache dir,甚至是放进 SD 卡中(比如大的图片和音视频).    可以设置双重缓冲,较大的图片或者音频放到SD ...

  9. android 缓存Bitmap - 开发文档翻译

    由于本人英文能力实在有限,不足之初敬请谅解 本博客只要没有注明“转”,那么均为原创,转贴请注明本博客链接链接 Loading a single bitmap into your user interf ...

  10. android缓存之Lrucache 和LinkedHashMap

    两者的区别 网上有很多人使用软引用加载图片的多 ,但是现在已经不再推荐使用这种方式了,(1)因为从 Android 2.3 (API Level 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的 ...

随机推荐

  1. 毕业回馈--89C51keil工程的创建

    声明:毕业回馈类博客均为大学毕业前夕同同学共享内容.为了给大学做一个总结,报答母校的栽培,才发起这样一个活动. ******************************************** ...

  2. jdk 动态代理源码分析

    闲来无事,撸撸源码 使用方法 直接看代码吧.. package com.test.demo.proxy; import java.lang.reflect.InvocationHandler; imp ...

  3. react-router 4实现代码分割(code spliting)

    官方一开始推荐的使用bundle-loader来做代码分割的方式感觉有点麻烦,而且代码看起来有点不舒服.而且需要一直依赖bunder-loader 一开始我想为什么不能像vue一样,直接使用ES的新特 ...

  4. [Awson原创]修水渠(canal)

    Description Awson是某国际学校信竞组的一只菜鸡.他们班主任F老师喜欢带他们去爬爬唷喽山.登顶后,Awson有了个奇怪的发现. 山腰上有N(1<=N<=100)个村庄,这些村 ...

  5. 李耀于NOIP2010集训出的题 Dvalue

    此题模型比较明显,求无向图的一棵生成树,使得最大边减去最小边的值最小,这是最小生成树的一个变式 设计出此题的算法需要利用Kruskal贪心的性质,首先枚举一条最小边,接着求原图的一棵最小生成树,根据k ...

  6. 计蒜客NOIP2017提高组模拟赛(三)day2-小区划分

    传送门 dp,注意边界 #include<cstdio> #include<cstdlib> #include<algorithm> #include<cst ...

  7. hdu 5437Alisha’s Party(优先队列)

    题意:邀请k个朋友,每个朋友带有礼物价值不一,m次开门,每次开门让一定人数p(如果门外人数少于p,全都进去)进来,当所有人到时会再开一次,每次都是礼物价值高的人先进. /*小伙伴最开始gg了,结果发现 ...

  8. [bzoj1041][HAOI2008]圆上的整点

    我能想得出怎么做才奇怪好吗 题解:http://blog.csdn.net/csyzcyj/article/details/10044629 #include<iostream> #inc ...

  9. 关于Miller-Rabbin的一点想法

    在好久之后终于搞完了miller-rabbin素性测试,谈谈自己的理解 要判断的数设为 a, 主要思想就是运用费马小定理来搞,随机几个数x(x<=a-1),判断x^(a-1)=1(mod a)是 ...

  10. Cookie 和 Session的基本使用

    cookie: 放在客户端上的键值对. 1.设置cookie obj = render(request,'index.html') obj.set_cookie('key','value') retu ...