Android asynchronously loads the picture and caches it to the local implementation method

Source: Internet
Author: User

Too many pictures cause memory overflow, this is the most difficult to solve, to think of some good caching strategies, such as large images using the LRU cache policy or lazy load cache policy. Today, the first introduction of the local cache image in the Android project to access the network picture is very common thing, if we every request to access the network to get pictures, it will be very expensive, and the image takes up more memory space, too much image and not released can easily cause memory overflow. For the two problems encountered above, first consume the traffic we can cache the image for the first time, and then load it locally if locally. Too many pictures cause memory overflow, this is the most difficult to solve, to think of some good caching strategies, such as large images using the LRU cache policy or lazy load cache policy. Let's start by introducing a local cache image today.
First look at the asynchronous load cache local code:
Copy CodeThe code is as follows:
Publicclassasyncbitmaploader
{
/**
* Memory picture Soft Reference buffer
*/
privatehashmap<string,softreference<bitmap>>imagecache=null;
Publicasyncbitmaploader ()
{
Imagecache=newhashmap<string,softreference<bitmap>> ();
}
Publicbitmaploadbitmap (Finalimageviewimageview,finalstringimageurl,finalimagecallbackimagecallback)
{
In the memory cache, the bitmap object is returned
if (Imagecache.containskey (ImageURL))
{
Softreference<bitmap>reference=imagecache.get (ImageURL);
Bitmapbitmap=reference.get ();
if (bitmap!=null)
{
Returnbitmap;
}
}
Else
{
/**
* Plus a lookup to the local cache
*/
Stringbitmapname=imageurl.substring (Imageurl.lastindexof ("/") +1);
Filecachedir=newfile ("/mnt/sdcard/test/");
File[]cachefiles=cachedir.listfiles ();
inti=0;
if (null!=cachefiles) {
for (; i<cachefiles.length;i++)
{
if (Bitmapname.equals (Cachefiles[i].getname ()))
{
Break
}
}
if (i<cachefiles.length)
{
Returnbitmapfactory.decodefile ("/mnt/sdcard/test/" +bitmapname);
}
}
}
Finalhandlerhandler=newhandler ()
{
/* (Non-javadoc)
* @seeandroid. Os.handler#handlemessage (Android.os.Message)
*/
@Override
Publicvoidhandlemessage (MESSAGEMSG)
{
Todoauto-generatedmethodstub
Imagecallback.imageload (ImageView, (Bitmap) msg.obj);
}
};
If it is not in the memory cache and is not local (reclaimed by the JVM), the thread is opened to download the picture
Newthread ()
{
/* (Non-javadoc)
* @seejava. Lang.thread#run ()
*/
@Override
Publicvoidrun ()
{
Todoauto-generatedmethodstub
Inputstreambitmapis=httputils.getstreamfromurl (ImageURL);
Bitmapbitmap=bitmapfactory.decodestream (Bitmapis);
Imagecache.put (imageurl,newsoftreference<bitmap> (Bitmap));
Messagemsg=handler.obtainmessage (0,BITMAP);
Handler.sendmessage (msg);
Filedir=newfile ("/mnt/sdcard/test/");
if (!dir.exists ())
{
Dir.mkdirs ();
}
Filebitmapfile=newfile ("/mnt/sdcard/test/" +
Imageurl.substring (Imageurl.lastindexof ("/") +1));
if (!bitmapfile.exists ())
{
Try
{
Bitmapfile.createnewfile ();
}
catch (Ioexceptione)
{
Todoauto-generatedcatchblock
E.printstacktrace ();
}
}
Fileoutputstreamfos;
Try
{
Fos=newfileoutputstream (Bitmapfile);
Bitmap.compress (Bitmap.CompressFormat.PNG,
100,fos);
Fos.close ();
}
catch (Filenotfoundexceptione)
{
Todoauto-generatedcatchblock
E.printstacktrace ();
}
catch (Ioexceptione)
{
Todoauto-generatedcatchblock
E.printstacktrace ();
}
}
}.start ();
Returnnull;
}
Publicinterfaceimagecallback
{
Publicvoidimageload (IMAGEVIEWIMAGEVIEW,BITMAPBITMAP);
}
}
This is a packaged asynchronous load picture class, cached two copies, one is cached in memory using soft reference, one is cached to the local SD card, if not in memory, then from the local lookup, if not local to get pictures from the network.
Copy CodeThe code is as follows:
publicclasshttputils{
Publicstaticinputstreamgetstreamfromurl (Stringimageurl) {
Inputstreamin=null;
try{
Urlurl=newurl (ImageURL);
httpurlconnectionconnection= (HttpURLConnection) url.openconnection ();
In=connection.getinputstream ();

}catch (Exceptione) {
Todoauto-generatedcatchblock
E.printstacktrace ();
}
Returnin;

}
}
This is a access to the network get class. Don't dwell on it.
Here's a look at how to use the encapsulated class for loading pictures asynchronously:
Copy CodeThe code is as follows:
publicclassimagecacheactivityextendsactivity{
/**calledwhentheactivityisfirstcreated.*/
Privatelistviewlistview;
@Override
Publicvoidoncreate (bundlesavedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
listview= (ListView) Findviewbyid (r.id.listview_list);
Myadapteradapter=newmyadapter ();
Listview.setadapter (adapter);
}
privateclassmyadapterextendsbaseadapter{
Privateasyncbitmaploaderasyncbitmaploader;
Publicmyadapter () {
Asyncbitmaploader=newasyncbitmaploader ();
}
@Override
Publicintgetcount () {
Todoauto-generatedmethodstub
RETURN10;
}
@Override
Publicobjectgetitem (intposition) {
Todoauto-generatedmethodstub
Returnnull;
}
@Override
Publiclonggetitemid (intposition) {
Todoauto-generatedmethodstub
Return0;
}
@Override
Publicviewgetview (intposition,viewconvertview,viewgroupparent) {
Todoauto-generatedmethodstub
if (convertview==null) {
Convertview=layoutinflater.from (Getapplicationcontext ()). Inflate (R.layout.list_item,null);
}
Imageviewimage= (ImageView) Convertview.findviewbyid (R.id.addexam_list_icon);
Stringimageurl= "Http://s.ata.net.cn/4f98db46908987a21a000003/logo/2012/04/114_80aaf295c083d07a496743699aac3193.png";
Bitmapbitmap=asyncbitmaploader.loadbitmap (Image,imageurl,newimagecallback () {

@Override
Publicvoidimageload (Imageviewimageview,bitmapbitmap) {
Todoauto-generatedmethodstub
Imageview.setimagebitmap (bitmap);
}
});
if (bitmap==null)
{
Image.setimageresource (R.drawable.ic_launcher);
}
Else
{
Image.setimagebitmap (bitmap);
}

Returnconvertview;
}

}
}

Android asynchronously loads the picture and caches it to the local implementation method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.