The recent Android image cache, just beginning to introduce open source framework, with the line, but in the development of the problems encountered, For instance Universal-image-loader-1.9.5.jar this frame, when loading the picture the custom ImageView cannot load, may have the following question, moreover the import framework causes the development the project package to be bigger and larger, based on above these kinds of situations, therefore I wanted to write oneself a picture three class The cached tool.
Brief analysis: Just start to think, the picture loading display is nothing but check the memory inside there is no, go to the file to find, if there is no file inside to open the network download, which is also in line with most of the needs of development, and efficiency must be a little higher, Loading pictures from a file in some situations, such as fast sliding ListView, does not load faster from memory. Let's take a look at the effect first!
This is the first time a picture is loaded, of course, a picture on the Web:
Picture loaded out, we want to look at the log, the log will not lie, I screenshot of the log
It was just local and not memory. Go to the network to download, all the log printing is to open the network download
But what about the second time you enter the application? Also go back to open the network download? That's not going to happen, so what's the use of it?
This is the second time you've logged into the application.
Load pictures from the file, do not need to open the network download directly from the file to get, OK, so the problem comes, read from the file is definitely inefficient ah, not directly from the memory read quickly! We call the system to maintain a good algorithm, the most recent use of algorithms, this algorithm is in my Learning operating system, when the teacher said a bit, but fortunately, can be used in the project to speak to the teacher, on this, thought that this is over? We should read the pictures in the file into memory, so as to prevent the dislocation bugs such as ListView fast sliding. Here's what I do when I'm sliding fast:
Loaded pictures are retrieved from memory, so the effect on the top of the good!
OK, so good picture level three cache, how in the end how to achieve it and how to use it? Post the code I wrote below! Let the small partners see, by the Way optimization optimization!
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;
/** * Image of the Level three cache tool class {Future project needs} * @author Double * * */public class Imagecachceuitl {public static final int succsee = 0;
public static final int FAIL = 1;
private context;
Private lrucache<string, bitmap> CACHE;//LRU algorithm collection, String is the picture's url,bitmap for the value type of the picture private File cachedir;
Handler Handler; Private Executorservice executorservice;//maintains the linear pool public imagecachceuitl (context context, Handler Handler) {This.conte Xt=conText
This.handler=handler;
Cachedir=context.getcachedir ()//Get cache Folder//maintenance Several network threads download picture Executorservice=executors.newfixedthreadpool (5); int maxsize= (int) (Runtime.getruntime (). MaxMemory ()/8);//Get the memory size of the running environment 1/8 cache=new lrucache<string, bitmap> (
MaxSize) {//TODO the size of each stored picture (for memory overflow drop picture) @Override protected int sizeOf (String key, Bitmap value) {
Returns the number of bytes in the current row * height, which is the size of the picture return Value.getrowbytes () *value.getheight ();
};//Current picture cache Total size}/** * * @param URL Download picture connection * @param position need to display a picture of the imgeview tag * @return * *
Public Bitmap Getbitmapfromurl (String url,int position) {//1 in memory gets the picture LRU algorithm Bitmap (URL);
In memory there is a specified picture if (bitmap!=null) {log.i ("Get Picture from memory", "Get Picture from Memory" +url);
return bitmap;
Get picture Bitmap=getbitmapfromfile (URL) in//2 file;
if (bitmap!=null) {log.i ("Get Picture from File", "Get Picture from File" +url);
return bitmap; //3 to open the network download LOG.I ("obtained from the networkGet picture "," Get Picture from Network "+url);
Getbitmapfromnet (url,position);
return null; /** * Network to get pictures * @param url pictures, link address * @param position need to display the ImageView tag/private void Getbitmapfromne
T (String URL, int position) {//Open task Executorservice.execute (new Runnabletask (url,position));
}//Task interface 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 () {//child thread operation, open network download picture try {URL url=new url (imageUrl);
Request Object Httpurlconnection= (httpurlconnection) url.openconnection ();
The way the network requests Httpurlconnection.setrequestmethod ("get");
Time of timeout, httpurlconnection.setconnecttimeout (5000);
Time to read timeout httpurlconnection.setreadtimeout (5000); Httpurlconnection.getreSponsecode () Get the latest data if (Httpurlconnection.getresponsecode () ==200) {//success gets data from Net;get tape
InputStream Inputstream=httpurlconnection.getinputstream ();
Convert the stream into Bitmap picture Bitmap Bitmap=bitmapfactory.decodestream (InputStream);
The handler mechanism is used to display the message Msg=new message () in the main thread.
A picture that needs to be displayed in the main thread msg.obj msg.obj=bitmap;
Msg.arg1=position;
Set the Mark Msg.what=succsee for MSG;
Handler.sendmessage (msg);
One, will download the picture after save in memory Cache.put (IMAGEURL, bitmap);
Second, the download after the picture saved to the file Writetoloce (IMAGEURL,BITMAP);
Return
} catch (Exception e) {e.printstacktrace (); //Close Request finally{//Disconnect server if (httpurlconnection!=null) {Httpurlconnection.disconnec
T ();
}//Send an empty message handler.obtainmessage (FAIL). Sendtotarget (); }/** * Picture writeOperations under the Cache folder * @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);
Write file operation (1 picture Type 2 picture quality when 100 means uncompressed 3 file stream) bitmap.compress (Compressformat.jpeg, FileOutputStream);
catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
/** * Read pictures in file * @param URL picture Connection address * @return/private Bitmap getbitmapfromfile (String URL) {
try {///Use the MD5 tool to encrypt the first 10 string bitmapefilename=md5encoder.encode (URL). substring (10); /** * Locate the specified file under the cache folder * Dir cache file storage path * Name filename/file File=new file (cachedir, Bi
Tmapefilename);
File.mkdir (); FileInputStream fiLeinputstream=new fileinputstream (file);
Bitmap Bitmap=bitmapfactory.decodefile (File.getpath ());//full file path//log.i (file path, File.getpath (). toString ());
2 after reading into memory, improve efficiency cache.put (URL, bitmap);
return bitmap;
catch (Exception e) {e.printstacktrace ();
return null;
}
}
Here is a use demo, in fact, very simple
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; /** * Picture three cache test + picture upload * @author Double River * * */public class MainActivity4 extends activity {private IMAGECACHCEUITL I
MAGECACHCEUITL;
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; Load the current Limageview ImageView imageview= (imageview) List by tagView.findviewwithtag (psition);
if (Null!=bitmap&&null!=imageview) {imageview.setimagebitmap (bitmap);
} break;
Case ImageCachceUitl.FAIL:Toast.makeText (Getapplicationcontext (), "Download Error", 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 ("Enter Port method", "Enter Port Method");
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 ("Request", envelope.bodyIn.toString ()); catch (IOException |
Xmlpullparserexception e) {e.printstacktrace ();
return arg1;
};
@SuppressLint ("Sdcardpath") public void Getimageromsdk () {log.i ("Enter Get Picture Method", "Enter Get Picture method");
try{string srcurl = "/sdcard/";//path string filename = "1.png";//filename 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));
Perform Base64 encoding String methodname = "Uploadimage"; Getimagefromandroid (Methodname,imagelist.get (i), uploadbuffer);
Call 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 a 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, Vie
W 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 () {@Overridepublic void OnClick (View v) {//urllist.get (position);
LOG.I ("Get Click Focus", "Get click Focus");
GETIMAGEROMSDK ();
Startrun ();
New Thread (New Runnable () {@Override public void run () {getimageromsdk ();
}). Start ();
}
});
return convertview; }
}
}
For everyone to introduce to this bar, we slowly digest, hope that the article has more or less help.