LruCache缓存处理及异步加载图片类的封装
Android中的缓存处理及异步加载图片类的封装
- 流量开销:对于客户端——服务器端应用,从远程获取图片算是经常要用的一个功能,而图片资源往往会消耗比较大的流量。
- 加载速度:如果应用中图片加载速度很慢的话,那么用户体验会非常糟糕。
- 那么如何处理好图片资源的获取和管理呢?异步下载+本地缓存
- 1. 服务器的压力大大减小;
- 2. 客户端的响应速度大大变快(用户体验好);
- 3. 客户端的数据加载出错情况大大较少,大大提高了应有的稳定性(用户体验好);
- 4. 一定程度上可以支持离线浏览(或者说为离线浏览提供了技术支持)。
- 1. 提供网络服务的应用;
- 2. 数据更新不需要实时更新,即便是允许3-5分钟的延迟也建议采用缓存机制;
- 3. 缓存的过期时间是可以接受的(不会因为缓存带来的好处,导致某些数据因为更新不及时而影响产品的形象等)
- 1.下载或加载的过程中容易导致阻塞;
- 大位图Bitmap对象是png格式的图片的30至100倍;
- 2.大位图在加载到ImageView控件前的解码过程;BitmapFactory.decodeFile()会有内存消耗。
- 1.命中率;
- 2.合理分配占用的空间;
- 3.合理的缓存层级。
下图为对象层次的引用
1、强引用:(在Android中LruCache就是强引用缓存)
平时我们编程的时候例如:Object object=new Object();那object就是一个强引用了。如果一个对象具有强引用,那就类似于必不可少的生活用品,垃圾回收器绝不会回收它。当内存空间不足,Java虚拟机宁愿抛出OOM异常,使程序异常终止,也不会回收具有强引用的对象来解决内存不足问题。
2、软引用(SoftReference):
软引用类似于可有可无的生活用品。如果内存空间足够,垃圾回收器就不会回收它,如果内存空间不足了,就会回收这些对象的内存。只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可用来实现内存敏感的高速缓存。 软引用可以和一个引用队列(ReferenceQueue)联合使用,如果软引用所引用的对象被垃圾回收,Java虚拟机就会把这个软引用加入到与之关联的引用队列中。
使用软引用能防止内存泄露,增强程序的健壮性。
3、弱引用(WeakReference):
弱引用与软引用的区别在于:只具有弱引用的对象拥有更短暂的生命周期。在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存。不过,由于垃圾回收器是一个优先级很低的线程, 因此不一定会很快发现那些只具有弱引用的对象。 弱引用可以和一个引用队列(ReferenceQueue)联合使用,如果弱引用所引用的对象被垃圾回收,Java虚拟机就会把这个弱引用加入到与之关联的引用队列中。
4、虚引用(PhantomReference)
"虚引用"顾名思义,就是形同虚设,与其他几种引用都不同,虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收。 虚引用主要用来跟踪对象被垃圾回收的活动。
虚引用与软引用和弱引用的一个区别在于:虚引用必须和引用队列(ReferenceQueue)联合使用。当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在回收对象的内存之前,把这个虚引用加入到与之关联的引用队列中。程序可以通过判断引用队列中是否已经加入了虚引用,来了解被引用的对象是否将要被垃圾回收。程序如果发现某个虚引用已经被加入到引用队列,那么就可以在所引用的对象的内存被回收之前采取必要的行动。
【相关应用:】
在java.lang.ref包中提供了三个类:SoftReference类、WeakReference类和PhantomReference类,它们分别代表软引用、弱引用和虚引用。ReferenceQueue类表示引用队列,它可以和这三种引用类联合使用,以便跟踪Java虚拟机回收所引用的对 象的活动。
Lru:Least Recently Used
近期最少使用算法,是一种页面置换算法,其思想是在缓存的页面数目固定的情况下,那些最近使用次数最少的页面将被移出,对于我们的内存缓存来说,强引用缓存大小固定为4M,如果当缓存的图片大于4M的时候,有些图片就会被从强引用缓存中删除,哪些图片会被删除呢,就是那些近期使用次数最少的图片。
(四)、内存保存:
在内存中保存的话,只能保存一定的量,而不能一直往里面放,需要设置数据的过期时间、LRU等算法。这里有一个方法是把常用的数据放到一个缓存中(A),不常用的放到另外一个缓存中(B)。当要获取数据时先从A中去获取,如果A中不存在那么再去B中获取。B中的数据主要是A中LRU出来的数据,这里的内存回收主要针对B内存,从而保持A中的数据可以有效的被命中。
publicclass MainActivity extends Activity {privatefinalstatic String TAG = "MainActivity";private ImageView imageView_main;private ProgressDialog pDialog = null; private String urlString = "http://c.hiphotos.baidu.com/image/pic/item/5366d0160924ab18dd54473737fae6cd7b890b6b.jpg";// private String urlString = "http://www.baidu.com/img/bdlogo.gif"; private LruCache<String, Bitmap> lruCache = null; private LinkedHashMap<String, SoftReference<Bitmap>> softMap = new LinkedHashMap<String, SoftReference<Bitmap>>(); private Handler handler = newHandler() { publicvoid handleMessage(Message msg) { switch (msg.what) { case 0: pDialog.show(); break; case 1: Bitmap bm = (Bitmap) msg.obj; if (bm != null) { imageView_main.setImageBitmap(bm); } pDialog.dismiss(); break; default:break; } } }; @Override protectedvoid onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView_main = (ImageView) findViewById(R.id.imageView_main); pDialog = new ProgressDialog(this); pDialog.setIcon(R.drawable.ic_launcher); pDialog.setTitle("提示:"); pDialog.setMessage("数据加载中。。。"); // int memClass = ((ActivityManager) // getSystemService(Context.ACTIVITY_SERVICE)) // .getMemoryClass(); int memoryCount = (int) Runtime.getRuntime().maxMemory(); // 获取剩余内存的8分之一作为缓存 int cacheSize = memoryCount / 8; Log.i(TAG, "==" + cacheSize); lruCache = new MyLruCache(cacheSize);// 这个初始化值是如何定义的?} class MyLruCache extends LruCache<String, Bitmap> { public MyLruCache(int maxSize) { super(maxSize); } @Override protectedint sizeOf(String key, Bitmap value) { // return value.getHeight() * value.getWidth() * 4; // Bitmap图片的一个像素是4个字节 Log.i(TAG, "==" + value.getByteCount()); return value.getByteCount(); } @Override protectedvoid entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) { if (evicted) { SoftReference<Bitmap> softReference = new SoftReference<Bitmap>( oldValue); softMap.put(key, softReference); } } } publicvoid clickButton(View view) { switch (view.getId()) { case R.id.button_main_submit:Bitmap bm = getBitmapFromMemoryCache(urlString); if (bm != null) { imageView_main.setImageBitmap(bm); Log.i(TAG, "==从缓存中获取到的图片"); } else { new Thread(new Runnable() { @Override publicvoid run() { handler.sendEmptyMessage(0); HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(urlString); try { HttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200) { byte[] data = EntityUtils.toByteArray(response .getEntity()); Log.i(TAG, "==文件尺寸:" + data.length); Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length); // 放入强缓存lruCache.put(urlString, bm); Log.i(TAG, "==放入强缓存ok"); Message msg = Message.obtain(); msg.obj = bm; msg.what = 1; handler.sendMessage(msg); } } catch (IOException e) { e.printStackTrace(); } } }).start(); } break;default:break;} } public Bitmap getBitmapFromMemoryCache(String key) { // 1.先从强引用中获取 Bitmap bitmap = null; bitmap = lruCache.get(key); if (bitmap != null) { Log.i(TAG, "==从强引用中找到"); return bitmap; } else { // 2.如果强引用中没有找到的话 如果软引用中存在就将它移到强引用中 然后软引用移除 SoftReference<Bitmap> softReference = softMap.get(key); if (softReference != null) { bitmap = softReference.get(); Log.i(TAG, "==从软引用中找到"); if (bitmap != null) { // 添加到强引用中 lruCache.put(key, bitmap); Log.i(TAG, "==添加到强引用中"); // 从软引用集合中移除 softMap.remove(key); Log.i(TAG, "==从软引用中移除"); return bitmap; } else { softMap.remove(key); } } } returnnull;} @Override publicboolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.next, menu); returntrue;} }
publicclass AsynTaskHelper { privatestaticfinal String TAG = "AsynTaskHelper"; publicvoid downloadData(String url, OnDataDownloadListener downloadListener) { new MyTask(downloadListener).execute(url); } privateclass MyTask extends AsyncTask<String, Void, byte[]> { private OnDataDownloadListener downloadListener; public MyTask(OnDataDownloadListener downloadListener) { this.downloadListener = downloadListener; } @Override protectedbyte[] doInBackground(String... params) { BufferedInputStream bis = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { URL url = new URL(params[0]); HttpURLConnection httpConn = (HttpURLConnection) url .openConnection(); httpConn.setDoInput(true); httpConn.setRequestMethod("GET"); httpConn.connect(); if (httpConn.getResponseCode() == 200) { bis = new BufferedInputStream(httpConn.getInputStream()); byte[] buffer = newbyte[1024 * 8]; int c = 0; while ((c = bis.read(buffer)) != -1) { baos.write(buffer, 0, c); baos.flush(); } return baos.toByteArray(); } } catch (Exception e) { e.printStackTrace(); } returnnull; } @Override protectedvoid onPostExecute(byte[] result) { // 通过回调接口来传递数据 downloadListener.onDataDownload(result); super.onPostExecute(result); } } publicinterface OnDataDownloadListener { void onDataDownload(byte[] result); } }
publicclass ImageDownloadHelper { privatestaticfinal String TAG = "ImageDownloaderHelper"; private HashMap<String, MyAsyncTask> map = new HashMap<String, MyAsyncTask>(); private Map<String, SoftReference<Bitmap>> softCaches = new LinkedHashMap<String, SoftReference<Bitmap>>(); private LruCache<String, Bitmap> lruCache = null; public ImageDownloadHelper() { int memoryAmount = (int) Runtime.getRuntime().maxMemory(); // 获取剩余内存的8分之一作为缓存 int cacheSize = memoryAmount / 8; if (lruCache == null) { lruCache = new MyLruCache(cacheSize); } Log.i(TAG, "==LruCache尺寸:" + cacheSize); } /** * * @param context * @param url * 该mImageView对应的url * @param mImageView * @param path * 文件存储路径 * @param downloadListener * OnImageDownload回调接口,在onPostExecute()中被调用 */ publicvoid imageDownload(Context context, String url, ImageView mImageView, String path, OnImageDownloadListener downloadListener) { Bitmap bitmap = null; // 先从强引用中拿数据 if (lruCache != null) { bitmap = lruCache.get(url); } if (bitmap != null && url.equals(mImageView.getTag())) { Log.i(TAG, "==从强引用中找到数据"); mImageView.setImageBitmap(bitmap); } else { SoftReference<Bitmap> softReference = softCaches.get(url); if (softReference != null) { bitmap = softReference.get(); } // 从软引用中拿数据 if (bitmap != null && url.equals(mImageView.getTag())) { Log.i(TAG, "==从软引用中找到数据"); // 添加到强引用中 lruCache.put(url, bitmap); Log.i(TAG, "==添加到强引用中"); // 从软引用集合中移除 softCaches.remove(url); mImageView.setImageBitmap(bitmap); } else { // 从文件缓存中拿数据 String imageName = ""; if (url != null) { imageName = ImageDownloaderUtil.getInstance().getImageName( url); } bitmap = getBitmapFromFile(context, imageName, path); if (bitmap != null && url.equals(mImageView.getTag())) { Log.i(TAG, "==从文件缓存中找到数据"); // 放入强缓存 lruCache.put(url, bitmap); mImageView.setImageBitmap(bitmap); } else { // 从网络中拿数据 if (url != null && needCreateNewTask(mImageView)) { MyAsyncTask task = new MyAsyncTask(context, url, mImageView, path, downloadListener); Log.i(TAG, "==从网络中拿数据"); if (mImageView != null) { task.execute(); // 将对应的url对应的任务存起来 map.put(url, task); } } } } } } /** * 判断是否需要重新创建线程下载图片,如果需要,返回值为true。 * * @param url * @param mImageView * @return */ privateboolean needCreateNewTask(ImageView mImageView) { boolean b = true; if (mImageView != null) { String curr_task_url = (String) mImageView.getTag(); if (isTasksContains(curr_task_url)) { b = false; } } return b; } /** * 检查该url(最终反映的是当前的ImageView的tag,tag会根据position的不同而不同)对应的task是否存在 * * @param url * @return */ privateboolean isTasksContains(String url) { boolean b = false; if (map != null && map.get(url) != null) { b = true; } return b; } /** * 删除map中该url的信息,这一步很重要,不然MyAsyncTask的引用会“一直”存在于map中 * * @param url */ privatevoid removeTaskFromMap(String url) { if (url != null && map != null && map.get(url) != null) { map.remove(url); Log.i(TAG, "当前map的大小==" + map.size()); } } /** * 从文件中拿图片 * * @param mActivity * @param imageName * 图片名字 * @param path * 图片路径 * @return */ private Bitmap getBitmapFromFile(Context context, String imageName, String path) { Bitmap bitmap = null; if (imageName != null) { File file = null; String real_path = ""; try { if (ImageDownloaderUtil.getInstance().hasSDCard()) { real_path = ImageDownloaderUtil.getInstance().getExtPath() + (path != null && path.startsWith("/") ? path : "/" + path); } else { real_path = ImageDownloaderUtil.getInstance() .getPackagePath(context) + (path != null && path.startsWith("/") ? path : "/" + path); } file = new File(real_path, imageName); if (file.exists()) bitmap = BitmapFactory.decodeStream(new FileInputStream( file)); } catch (Exception e) { e.printStackTrace(); bitmap = null; } } return bitmap; } /** * 将下载好的图片存放到文件中 * * @param path * 图片路径 * @param mActivity * @param imageName * 图片名字 * @param bitmap * 图片 * @return */ privateboolean setBitmapToFile(String path, Context mActivity, String imageName, Bitmap bitmap) { File file = null; String real_path = ""; try { if (ImageDownloaderUtil.getInstance().hasSDCard()) { real_path = ImageDownloaderUtil.getInstance().getExtPath() + (path != null && path.startsWith("/") ? path : "/" + path); } else { real_path = ImageDownloaderUtil.getInstance().getPackagePath( mActivity) + (path != null && path.startsWith("/") ? path : "/" + path); } file = new File(real_path, imageName); if (!file.exists()) { File file2 = new File(real_path + "/"); file2.mkdirs(); } file.createNewFile(); FileOutputStream fos = null; if (ImageDownloaderUtil.getInstance().hasSDCard()) { fos = new FileOutputStream(file); } else { fos = mActivity.openFileOutput(imageName, Context.MODE_PRIVATE); } if (imageName != null && (imageName.contains(".png") || imageName .contains(".PNG"))) { bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos); } else { bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos); } fos.flush(); if (fos != null) { fos.close(); } returntrue; } catch (Exception e) { e.printStackTrace(); returnfalse; } } /** * 辅助方法,一般不调用 * * @param path * @param mActivity * @param imageName */ privatevoid removeBitmapFromFile(String path, Context mActivity, String imageName) { File file = null; String real_path = ""; try { if (ImageDownloaderUtil.getInstance().hasSDCard()) { real_path = ImageDownloaderUtil.getInstance().getExtPath() + (path != null && path.startsWith("/") ? path : "/" + path); } else { real_path = ImageDownloaderUtil.getInstance().getPackagePath( mActivity) + (path != null && path.startsWith("/") ? path : "/" + path); } file = new File(real_path, imageName); if (file != null) file.delete(); } catch (Exception e) { e.printStackTrace(); } }
转载于:https://www.cnblogs.com/Meowaz/p/4414669.html
LruCache缓存处理及异步加载图片类的封装相关推荐
- Android中的缓存处理及异步加载图片类的封装
一.缓存介绍: (一).Android中缓存的必要性: 智能手机的缓存管理应用非常的普遍和需要,是提高用户体验的有效手段之一. 1.没有缓存的弊端: 流量开销:对于客户端--服务器端应用,从远程获取图 ...
- android 实现异步加载图片,Android中ImageView异步加载图片类
本源码是从网络找到经修改以方便直接调用感觉用着还可以 首先在项目中添加一个专门加载图片的类AsyncImageLoaderpackage com.demo.core; import java.io.I ...
- Android实现ListView异步加载图片总结
参考自http://blog.csdn.net/wanglong0537/article/details/6334005# http://www.cnblogs.com/slider/archive/ ...
- [置顶] 异步加载图片,使用LruCache和SD卡或手机缓存,效果非常的流畅
转载请注明出处http://blog.csdn.net/xiaanming/article/details/9825113 异步加载图片的例子,网上也比较多,大部分用了HashMap<Strin ...
- Android批量图片加载经典系列——使用LruCache、AsyncTask缓存并异步加载图片
一.问题描述 使用LruCache.AsyncTask实现批量图片的加载并达到下列技术要求 1.从缓存中读取图片,若不在缓存中,则开启异步线程(AsyncTask)加载图片,并放入缓存中 2.及时移除 ...
- android异步加载图片并缓存到内存和sd卡上,Android批量图片加载经典系列——采用二级缓存、异步加载网络图片...
http://www.cnblogs.com/jerehedu/p/4560119.html 2015-06-08 09:20 by 杰瑞教育, 232 阅读, 1 评论, 收藏, 编辑一.问题描述 ...
- Android ListView异步加载图片乱序问题,原因分析及解决方案
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/45586553 在Android所有系统自带的控件当中,ListView这个控件算是 ...
- Android:异步加载图片
我们知道Android为了不阻塞UI线程(main线程),不允许在非UI线程中进行UI操作以及网络请求等操作,为了不阻塞UI,我们往往就要进行异步加载. 我们以异步加载图片为例子,来学习一下异步加载 ...
- Android开发之ListView异步加载图片
ListView这个控件对于大家肯定不会陌生,即使你是初学者相信也会用ListView.因为ListView这个控件实在是太常用,可以说基本上每一个项目开发都会用到它,今天这篇博客主要讲解,ListV ...
最新文章
- POJ 2112 Optimal Milking(二分图匹配)
- Class Activation Mapping(CAM)
- mysql 控制台全是_Mysql控制台命令大全
- 学习难吗?从画一个点开始,从点点鼠标开始
- WPF调用图片路径,或资源图片
- minikube start 使用Hyper-V
- 使用动态优先权的进程调度算法的模拟_我爱OS第12讲:系统调度
- Leetcode 199.二叉树的右视图
- hdfs--Structured Streaming--console案例
- 编程视频资源教程汇总
- 网络安全:ARP和IP协议
- 获利能力分析实际数据收集流程
- 汉芯一号、木兰语言再到天赐OS,国产基础软件十年泣血,梦想何圆?
- 将uiimageview设置成纯圆形
- 室内地图导航系统基础功能与衍生服务详解
- vue分类筛选方法,filer
- Android——Framework之Packamanager深析
- Linux系统-gzip命令 – 压缩和解压文件
- 篱笆(Fenced In)
- 女生要不要去北航学计算机,在北航读书有个女朋友是种怎样的体验?
热门文章
- b区计算机考研招不满的大学,B区又一所院校招收大量调剂!一志愿不满!
- php 显示要上传的图片格式,php判断文件上传图片格式的实例详解
- 测试linux写文件系统,linux下各主要文件系统的读写性能测试
- 智能车竞赛技术报告 | 专科基础组 - 沈阳职业技术学院 - 秋名山菜鸟队
- 乾勤科技-智能车竞赛培训计划
- 测试RDA5807收音机模块
- 炼一项专业技能c语言,C语言程序设计_安徽新华电脑专修学院
- 计算机二级c语言考完多久出成绩,计算机二级C语言的成绩什么时候出来?
- sgn matlab,matlab中.*的问题
- as工程放到源码编译_UE4 Program 类型工程的限制和解决方法