android 缓存实现
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 缓存实现的更多相关文章
- Android 缓存
1.Android缓存机制&一个缓存框架推荐 http://blog.csdn.net/shakespeare001/article/details/51695358 2.ASimpleCac ...
- Android缓存处理
Android缓存: 採用缓存,能够进一步大大缓解数据交互的压力,又能提供一定的离线浏览.下边我简略列举一下缓存管理的适用环境: 1. 提供网络服务的应用 2. 数据更新不须要实时更新.哪怕是3-5分 ...
- android缓存具体解释
Android缓存: 採用缓存,能够进一步大大缓解数据交互的压力.又能提供一定的离线浏览.下边我简略列举一下缓存管理的适用环境: 1. 提供网络服务的应用 2. 数据更新不须要实时更新,哪怕是3-5分 ...
- 【转】彻底解析Android缓存机制——LruCache
彻底解析Android缓存机制——LruCache 关于Android的三级缓存,其中主要的就是内存缓存和硬盘缓存.这两种缓存机制的实现都应用到了LruCache算法,今天我们就从使用到源码解析,来彻 ...
- Android缓存学习入门(二)
本文主要包括以下内容 内存缓存策略 文件缓存策略 内存缓存策略 当有一个图片要去从网络下载的时候,我们并不会直接去从网络下载,因为在这个时代,用户的流量是宝贵的,耗流量的应用是不会得到用户的青睐的.那 ...
- Android缓存学习入门
本文主要包括以下内容 利用LruCache实现内存缓存 利用DiskLruCache实现磁盘缓存 LruCache与DiskLruCache结合实例 利用了缓存机制的瀑布流实例 内存缓存的实现 pub ...
- Android 缓存目录 Context.getExternalFilesDir()和Context.getExternalCacheDir()方法
一.基础知识 应用程序在运行的过程中如果需要向手机上保存数据,一般是把数据保存在SDcard中的.大部分应用是直接在SDCard的根目录下创建一个文件夹,然后把数据保存在该文件夹中.这样当该应用被卸载 ...
- Android缓存技术
android应用程序中 1. 尽可能的把文件缓存到本地.可以是 memory,cache dir,甚至是放进 SD 卡中(比如大的图片和音视频). 可以设置双重缓冲,较大的图片或者音频放到SD ...
- android 缓存Bitmap - 开发文档翻译
由于本人英文能力实在有限,不足之初敬请谅解 本博客只要没有注明“转”,那么均为原创,转贴请注明本博客链接链接 Loading a single bitmap into your user interf ...
- android缓存之Lrucache 和LinkedHashMap
两者的区别 网上有很多人使用软引用加载图片的多 ,但是现在已经不再推荐使用这种方式了,(1)因为从 Android 2.3 (API Level 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的 ...
随机推荐
- Python默认版本切换
Mac上自带python2.7 版本,但是我又下了一个3.7版本(下载的版本默认安装在 /Library/Frameworks/Python.framework/Versions/3.7/bin/py ...
- [JLOI2015]装备购买
题目描述 脸哥最近在玩一款神奇的游戏,这个游戏里有 n 件装备,每件装备有 m 个属性,用向量zi(aj ,.....,am) 表示 (1 <= i <= n; 1 <= j < ...
- 计蒜客NOIP模拟赛(2) D2T2紫色百合
[问题描述] “牵着你的手的是她,路边开满了紫色的百合花……” 你从梦中醒来,却依然忘不了梦中的她百合花,每朵百合花都有一个权值,在二进制下写成一行‘1’,第i朵紫色百合的权值在二进制下写成i个‘1’ ...
- [USACO13DEC]假期计划(黄金)Vacation Planning (gold)
题目翻译不好,这里给出一份 题目背景 Awson是某国际学校信竞组的一只大佬.由于他太大佬了,于是干脆放弃了考前最后的集训,开车(他可是老司机)去度假.离开学校前,他打开地图,打算做些规划. 题目描述 ...
- Hello,World!!----来自半个新OIer的问候
为了记录OI生涯的点点滴滴故申请此博客,说是半个新OIer,其实我的OI生涯并不算很短了吧...现在也算是初三下学期了...也算是混迹NOIP第5个年头了.文化课上也没什么临考压力,那就好好准备第5场 ...
- [BZOJ]4199: [Noi2015]品酒大会(后缀数组+笛卡尔树)
Time Limit: 10 Sec Memory Limit: 512 MB Description Input Output Sample Input 10 ponoiiipoi 2 1 4 7 ...
- 【USACO】股票市场
题目描述 尽管奶牛天生谨慎,它们仍然在住房抵押信贷市场中大受打击,现在它们准备在股市上碰碰运 气.贝西有内部消息,她知道 S 只股票在今后 D 天内的价格. 假设在一开始,她筹集了 M 元钱,那么她该 ...
- poj 2425 AChessGame(博弈)
A Chess Game Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 3791 Accepted: 1549 Desc ...
- ●BZOJ 4361 isn
题链: http://www.lydsy.com/JudgeOnline/problem.php?id=4361 题解: 容斥,DP,树状数组 注意题意:一旦变成了非降序列,就停止操作.即对非降序列进 ...
- *hdu 5536(字典树的运用)
Input The first line of input contains an integer T indicating the total number of test cases. The f ...