直接应用项目中的Android图片缓存技术
前不久搞的android图片缓存,刚开始引入开源的框架,用着还行,但是在开发中遇到问题,就比如universal-image-loader-1.9.5.jar这个框架吧,在加载图片的时候自定义imageview无法加载,可能是存在以下问题吧,况且导入框架导致开发的项目包越来越大,基于上面的这几种情况,于是我就想自己写一个图片三级缓存的工具。
简要分析:刚开始想,图片的加载显示无非是先检查内存里面有没有,没就去文件里面找,若是文件里面没有的话就去开启网络下载,这样也符合开发中的大部分需求,而且效率肯定要高一点,在某些场合如快速滑动listview时从文件中加载图片就没有从内存中加载得快。先来看看效果吧!
这是第一次加载出来的图片,当然是网上的一张图片:
图片加载出来了,我们要看看日志,日志不会说谎,我截图的日志
刚才是本地和内存都没有那就的去网络下载了,所有日志打印的是开启网络下载
然而第二次进入应用的时候呢?还回去开启网络下载吗?那肯定不会的,要不这样要它有啥用呢?
看看吧这就是第二次进入应用的时候的日志
从文件中加载图片,不在需要开启网络下载直接从文件中获取,好了,这样问题就来了,从文件中读取肯定效率不好呀,没有直接从内存中读取快吧!我们调用系统维护好的一个算法,最近最少使用算法,这个算法是在我学操作系统的时候学到的,当时老师讲了一下,不过还好,能在项目中用到老师讲的东西,对此,以为就这个就完了?我们应该把文件中的图片读取到内存中,这样防止像listview这样的快速滑动产生的错位bug。下面看看我在快速滑动时的效果:
加载的图片都是从内存中获取,这样在效果上面就很好的啦!
好的,这么好的图片三级缓存,那到底怎么实现的呢以及到底怎么用的呢?下面就贴出我写的代码吧!让小伙伴看看,顺便优化优化!
package com.example.util; import java.io.file; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.inputstream; import java.net.httpurlconnection; import java.net.url; import java.util.concurrent.executorservice; import java.util.concurrent.executors; import android.content.context; import android.graphics.bitmap; import android.graphics.bitmap.compressformat; import android.graphics.bitmapfactory; import android.os.handler; import android.os.message; import android.support.v4.util.lrucache; import android.util.log; /** * 图片的三级缓存工具类{日后项目需要} * @author double 江 * */ public class imagecachceuitl { public static final int succsee = 0; public static final int fail = 1; private context context; private lrucache<string, bitmap> cache;//lru算法集合,string是图片的url,bitmap为图片的值类型 private file cachedir; handler handler; private executorservice executorservice;//维护线性池 public imagecachceuitl(context context ,handler handler){ this.context=context; this.handler=handler; cachedir=context.getcachedir();//获得cache文件夹 //维护几个网络线程下载图片 executorservice=executors.newfixedthreadpool(5); int maxsize=(int) (runtime.getruntime().maxmemory()/8);//获得运行环境的内存大小的1/8 cache=new lrucache<string, bitmap>(maxsize){ // todo 每存储一张图片的大小(作用于内存溢出丢图片) @override protected int sizeof(string key, bitmap value) { //返回当前一行所占的字节数*高度,就是图片的大小 return value.getrowbytes()*value.getheight(); } };//当前图片缓存总数的大小 } /** * * @param url 下载图片的连接 * @param position 需要显示图片的imgeview的tag * @return */ public bitmap getbitmapfromurl(string url,int position){ //1内存中获取图片lru算法 bitmap bitmap=cache.get(url); //内存中有指定图片 if (bitmap!=null) { log.i("从内存中获得图片", "从内存中获得图片"+url); return bitmap; } //2文件中获取图片 bitmap=getbitmapfromfile(url); if (bitmap!=null) { log.i("从文件中获得图片", "从文件中获得图片"+url); return bitmap; } //3开启网络下载 log.i("从网络中获得图片", "从网络中获得图片"+url); getbitmapfromnet(url,position); return null; } /** * 网络获取图片 * @param url 图片的;链接地址 * @param position 需要显示的imageview的tag */ private void getbitmapfromnet(string url, int position) { //开启任务 executorservice.execute(new runnabletask(url,position)); } //任务接口 class runnabletask implements runnable{ string imageurl; int position; private httpurlconnection httpurlconnection; public runnabletask(string imageurl, int position) { this.position=position; this.imageurl=imageurl; } @override public void run() { //子线程的操作,开启网络下载图片 try { url url=new url(imageurl); //请求对象 httpurlconnection=(httpurlconnection) url.openconnection(); //网络请求的方式 httpurlconnection.setrequestmethod("get"); //超时的时间, httpurlconnection.setconnecttimeout(5000); //读取超时的时间 httpurlconnection.setreadtimeout(5000); //httpurlconnection.getresponsecode()拿到最新数据 if (httpurlconnection.getresponsecode()==200) { //success get data from net;get tape inputstream inputstream=httpurlconnection.getinputstream(); //将流转化成bitmap图片 bitmap bitmap=bitmapfactory.decodestream(inputstream); //利用handler机制放入主线程中显示 message msg=new message(); //需要在主线程中显示的图片msg.obj msg.obj=bitmap; msg.arg1=position; //为msg设置标记 msg.what=succsee; handler.sendmessage(msg); //一,将下载完后的图片保存到内存中 cache.put(imageurl, bitmap); //二,将下载完后的图片保存到文件中 writetoloce(imageurl,bitmap); return; } } catch (exception e) { e.printstacktrace(); } //关闭请求 finally{ //断开服务器 if (httpurlconnection!=null) { httpurlconnection.disconnect(); } } //发送一个空消息 handler.obtainmessage(fail).sendtotarget(); } } /** * 图片写入cache文件夹下面的操作 * @param imageurl * @param bitmap */ private void writetoloce(string imageurl, bitmap bitmap) { try { string bitmapefilename=md5encoder.encode(imageurl).substring(10); log.i("bitmapefilename", bitmapefilename); file file=new file(cachedir, bitmapefilename); fileoutputstream fileoutputstream =new fileoutputstream(file); //写入文件的操作(1图片类型2图片质量当为100时表示不压缩3文件流) bitmap.compress(compressformat.jpeg, 100, fileoutputstream); } catch (exception e) { // todo auto-generated catch block e.printstacktrace(); } } /** * 读取文件中图片的操作 * @param url 图片的连接地址 * @return */ private bitmap getbitmapfromfile(string url) { try { //使用md5工具加密截取前10个字符串 string bitmapefilename=md5encoder.encode(url).substring(10); /** * 在cache文件夹下面找到指定文件 * dir cache文件存储路径 * name 文件名称 */ file file=new file(cachedir, bitmapefilename); // file.mkdir(); //fileinputstream fileinputstream=new fileinputstream(file); bitmap bitmap=bitmapfactory.decodefile(file.getpath());//完整文件路径 //log.i("文件路径", file.getpath().tostring()); //2读取之后放入内存,提高效率 cache.put(url, bitmap); return bitmap; } catch (exception e) { e.printstacktrace(); } return null; } }
下面就是一个使用demo了,其实很简单
package com.example.do0me;
import java.io.bytearrayoutputstream; import java.io.file; import java.io.fileinputstream; import java.io.ioexception; import java.security.publickey; import java.util.arraylist; import java.util.list; import java.util.concurrent.executorservice; import java.util.concurrent.executors; import org.ksoap2.soapenvelope; import org.ksoap2.serialization.marshalbase64; import org.ksoap2.serialization.soapobject; import org.ksoap2.serialization.soapserializationenvelope; import org.ksoap2.transport.httptransportse; import org.xmlpull.v1.xmlpullparserexception; import android.annotation.suppresslint; import android.app.activity; import android.graphics.bitmap; import android.graphics.bitmapfactory; import android.graphics.canvas; import android.graphics.paint; import android.graphics.drawable.bitmapdrawable; import android.os.bundle; import android.os.handler; import android.util.base64; import android.util.log; import android.view.layoutinflater; import android.view.view; import android.view.view.onclicklistener; import android.view.viewgroup; import android.view.viewtreeobserver.onpredrawlistener; import android.widget.baseadapter; import android.widget.button; import android.widget.imageview; import android.widget.listview; import android.widget.toast; import com.example.util.agbcapi; import com.example.util.clippingpicture; import com.example.util.fastblur; import com.example.util.imagecachceuitl; import com.tencent.connect.avatar.c; /** * 图片三级缓存的测试+图片上传 * @author double 江 * */ public class mainactivity4 extends activity { private imagecachceuitl imagecachceuitl; private list<string> urllist=new arraylist<string>(); private runnable runnable; private handler handler =new handler(){ public void handlemessage(android.os.message msg) { switch (msg.what) { case imagecachceuitl.succsee: bitmap bitmap=(bitmap) msg.obj; int psition=msg.arg1; //通过tag加载当前的limageview imageview imageview=(imageview) listview.findviewwithtag(psition); if (null!=bitmap&&null!=imageview) { imageview.setimagebitmap(bitmap); } break; case imagecachceuitl.fail: toast.maketext(getapplicationcontext(), "下载错误", toast.length_long).show(); default: break; } }; }; private listview listview; private soapobject request; private executorservice executorservice; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main4); listview=(listview) findviewbyid(r.id.imageviewlist); imagecachceuitl=new imagecachceuitl(getapplicationcontext(), handler); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg");urllist.add("http://ww4.sinaimg.cn/large/90bd89ffjw1eqvmd6o8r6j20go0p5ju2.jpg"); listview.setadapter(new mylistadapt()); executorservice=executors.newfixedthreadpool(5); executorservice.execute(new runnable() { @override public void run() { getimageromsdk(); } }); } public string getimagefromandroid(string arg0,string arg1, string arg2){ log.i("进入端口方法", "进入端口方法"); final string methodname="getimagefromandroid"; final string soapaction=agbcapi.namespace+methodname; request = new soapobject(agbcapi.namespace, methodname); request.addproperty("arg0",arg1); request.addproperty("arg1",arg2); soapserializationenvelope envelope = new soapserializationenvelope(soapenvelope.ver11); (new marshalbase64()).register(envelope); envelope.bodyout = request; envelope.dotnet=false; envelope.setoutputsoapobject(request); httptransportse ht = new httptransportse(agbcapi.taskserviceurl); ht.debug=true; try { ht.call(soapaction, envelope); log.i("请求", envelope.bodyin.tostring()); } catch (ioexception | xmlpullparserexception e) { e.printstacktrace(); } return arg1; }; @suppresslint("sdcardpath") public void getimageromsdk(){ log.i("进入获取图片方法", "进入获取图片方法"); try{ string srcurl = "/sdcard/"; //路径 string filename = "1.png"; //文件名 string filrname2="2.jpg"; list<string>imagelist=new arraylist<>(); imagelist.add(filename); imagelist.add(filrname2); for (int i = 0; i < imagelist.size(); i++) { fileinputstream fis = new fileinputstream(srcurl + imagelist.get(i)); bytearrayoutputstream baos = new bytearrayoutputstream(); byte[] buffer = new byte[4096]; int count = 0; while((count = fis.read(buffer)) >= 0){ baos.write(buffer, 0, count); } string uploadbuffer = new string(base64.encode(baos.tobytearray(), base64.default)); //进行base64编码 string methodname = "uploadimage"; getimagefromandroid(methodname,imagelist.get(i), uploadbuffer); //调用webservice log.i("connectwebservice", "start"); fis.close(); } }catch(exception e){ e.printstacktrace(); } } class mylistadapt extends baseadapter{ private layoutinflater layoutinflater; imageview list_imag; button list_but; @override public int getcount() { // todo auto-generated method stub return urllist.size(); } @override public object getitem(int position) { // todo auto-generated method stub return urllist.get(position); } @override public long getitemid(int position) { // todo auto-generated method stub return position; } @suppresslint({ "inflateparams", "viewholder" }) @override public view getview(final int position, view convertview, viewgroup parent) { layoutinflater=layoutinflater.from(getapplication()); //if (layoutinflater==null) { convertview = layoutinflater.inflate(r.layout.image_list_item, null); // } list_but=(button) convertview.findviewbyid(r.id.list_but); list_imag=(imageview) convertview.findviewbyid(r.id.list_imag); list_imag.settag(position); final bitmap bitmap=imagecachceuitl.getbitmapfromurl(urllist.get(position), position); if (null!=bitmap) { list_imag.setimagebitmap(bitmap); } list_imag.setvisibility(view.visible); list_but.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { //urllist.get(position); log.i("获取点击焦点", "获取点击焦点"); // getimageromsdk(); //startrun(); new thread(new runnable() { @override public void run() { getimageromsdk(); } }).start(); } }); return convertview; } } }
就为大家介绍到这吧,大家慢慢消化,希望文章对大家有或多或少的帮助。