The first explanation is that the method has been abandoned by me. Before using it, found that loading speed is not good. Not very careful to see.
Now I'm using the volley. Take it out just for everyone to criticize.
Package Com.souya.seller.util.ex;import Java.io.file;import Java.io.fileinputstream;import java.io.InputStream; Import Java.lang.ref.softreference;import Java.util.hashmap;import Java.util.concurrent.threadpoolexecutor;import Java.util.concurrent.timeunit;import Axlib.utility.console;import Axlib.utility.httpclient;import Axlib.utility.queue;import Axlib.utility.runtimeexceptionex;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import android.graphics.drawable.BitmapDrawable; Import Android.graphics.drawable.drawable;import Android.media.thumbnailutils;import Android.net.Uri;import Android.os.handler;import Android.os.message;import Android.provider.mediastore.video.thumbnails;import Android.util.log;import Android.widget.imageview;import Com.souya.seller.app.sellerapplication;public Class Asyncimageloader {private static Boolean _d = False;//appconfig._d &&private static final String TAG = "Asyncimag Eloader ";p ublic static String CachePath = null;private static String Thumbnailpath = Null;private static Boolean _isinit = False;private static Conte XT _ctx;private static Bitmap _empty = Bitmap.createbitmap (1, 1, Bitmap.Config.RGB_565);p rivate static hashmap<string , softreference<bitmap>> Imagecache = new hashmap<string, softreference<bitmap>> ();p rivate static queue<runnable> Queue = new queue<runnable> ();//thread pool: Max 50, each execution: 1, Idle thread end timeout: 180 seconds private static Threadpoolexecutor executor = new Threadpoolexecutor (1, timeunit.seconds, queue);p ublic final static Asyncimagel Oader Instance = new Asyncimageloader ();p ublic static void Init (final context context) {CachePath = Sellerapplication.geti Nstance (). Mappcachedir + ""; Thumbnailpath = CachePath + "/thumbnails"; if (!new file (Thumbnailpath). Exists ()) New File (Thumbnailpath). Mkdirs (); _ctx = Context;_isinit = true;} public static drawable Loaddrawable (final context context, final String URL, final imagecallback imagecallback) {iF (!_isinit) Init (context), final String key = url;synchronized (Imagecache) {if (Imagecache.containskey (key)) { softreference<bitmap> softreference = Imagecache.get (key); Bitmap bmp = Softreference.get (); if (BMP! = null &&!bmp.isrecycled ()) {if (bmp = = _empty) {bmp = BMP;} elsereturn New Bitmapdrawable (BMP);}} else {imagecache.put (key, New softreference<bitmap> (_empty));}} Final Handler Handler = new Handler () {public void Handlemessage (Message message) {imagecallback.imageloaded ((drawable) m Essage.obj, URL);}};/ /use thread pool to do the task of downloading pictures executor.execute (new Runnable () {@Overridepublic void run () {Bitmap bmp = LoadImage (URL); if (BMP! = null) { Synchronized (Imagecache) {if (Imagecache.containskey (key)) {Imagecache.put (Key, new softreference<bitmap> (BMP )); Message message = Handler.obtainmessage (0, New bitmapdrawable (BMP)); handler.sendmessage (message);} else {if (!bmp.isrecycled ()) bmp.recycle (); bmp = null; System.GC ();}}}}); return null;} public static drawable loaddrawable (FINAL context context, final String URL, final int width, final int height, final imagecallback imagecallback) {if (!_isinit) I NIT (context); final String key = String.Format ("%s_%d_%d", url, width, height); if (Imagecache.containskey (key)) { softreference<bitmap> softreference = Imagecache.get (key); Bitmap bmp = Softreference.get (); if (BMP! = null &&!bmp.isrecycled ()) {if (bmp = = _empty) {bmp = BMP;} elsereturn New Bitmapdrawable (BMP);}} else {imagecache.put (key, New softreference<bitmap> (_empty));} Final Handler Handler = new Handler () {public void Handlemessage (Message message) {imagecallback.imageloaded ((drawable) m Essage.obj, URL);}};/ /use thread pool to do the task of downloading pictures executor.execute (new Runnable () {@Overridepublic void run () {Bitmap bmp = Loadimageandscale (URL, width, he ight), if (Imagecache.containskey (key)) {Imagecache.put (Key, New softreference<bitmap> (BMP)); Message message = Handler.obtainmessage (0, New bitmapdrawable (BMP)); handler.sendmessage (message);} else {if (!bmp.isrecycleD ()) bmp.recycle (); bmp = null; System.GC ();}}); return null;} public static void releasedrawable (String url, int width, int height) {log ("releasedrawable" + URL); String key = String.Format ("%s_%d_%d", url, width, height); releasedrawable (key);} public static void releasedrawable (String url) {try {log ("releasedrawable" + URL); String key = url;synchronized (Imagecache) {if (Imagecache.containskey (key)) {softreference<bitmap> SoftReference = Imagecache.get (key); Imagecache.remove (key); Bitmap bmp = Softreference.get (); if (BMP! = NULL && BMP! = _empty &&!bmp.isrecycled ()) {bmp.recycle (); BMP = null;} System.GC ();}}} catch (Exception e) {String stack = runtimeexceptionex.getstacktracestring (e);}} private static hashmap<string, object> _loadimagelocks = new hashmap<string, object> ();p ublic static Bitmap L Oadimage (String URL) {log ("Londimage:" + URL); Object lockobj = null;synchronized (_loadimagelocks) {if (_ Loadimagelocks.containskey (URL)) Lockobj = _LOADIMAGELOCKS.GET (URL), else {lockobj = new Object (); _loadimagelocks.put (URL, lockobj);}} Synchronized (lockobj) {if (Islocalimage (URL)) return loadlocalimage (URL); else {String localurl = getcachefilename (URL) ; Bitmap bmp = Null;if (new File (Localurl). Exists ()) BMP = Loadlocalimage (localurl), try {if (BMP = = null) BMP = Loadhttpimage ( URL, 0, 0);} catch (Throwable e) {if (_d) throw runtimeexceptionex.create (e);} return bmp;}}} public static Bitmap loadimage (String url, int width, int height) {log ("Londimage:" + URL); Object lockobj = Null;synchroni Zed (_loadimagelocks) {if (_loadimagelocks.containskey (URL)) lockobj = _loadimagelocks.get (URL); else {lockobj = new Object (); _loadimagelocks.put (URL, lockobj);}} Synchronized (lockobj) {if (Islocalimage (URL)) return Loadlocalimage (URL, width, height); else {String Localurl = Getcachefilename (URL); Bitmap bmp = Null;if (new File (Localurl). Exists ()) BMP = Loadlocalimage (localurl, width, height); try {if (BMP = = null) BMP = Loadhttpimage (URL, width, height);} catch (Throwable e){if (_d) throw runtimeexceptionex.create (e);} return bmp;}}} private static Bitmap loadlocalimagebyvideo (String url) {log ("Loadlocalimagebyvideo:" + URL), if (!new File (URL). Exists ( )) return null; Bitmap bmp = Thumbnailutils.createvideothumbnail (URL, thumbnails.mini_kind); return bmp;} private static Bitmap loadlocalimage (String URL) {return loadlocalimage (URL, 0);} private static Bitmap loadlocalimage (String url, int width, int height) {if (width = = 0 && height = = 0) return load Localimage (URL); elsereturn _loadlocalimage (url, width, height);} private static Bitmap _loadlocalimage (String url, int width, int height) {try {if (!new File (URL). Exists ()) return null;// Get the width and height of the screen/** * in order to calculate the scale of the zoom, we need to get the entire picture size, not the picture * Bitmapfactory.options class has a Boolean variable injustdecodebounds, set it to true * this way, What we get is the size of the picture, without loading the image. When we set this value, we can then go from bitmapfactory. * Options in Outwidth and Outheight get the value */bitmapfactory.options op = new bitmapfactory.options (); op.injustdecodebounds = True Uri uri = uri.fromfile (new File (URL));//ByThe Mediastore storage is used, which takes the form of the input stream according to the URI bitmap pic = Bitmapfactory.decodestream (_ctx.getcontentresolver (). Openinputstream (URI), null, OP), int wratio = (int) Math.ceil (Op.outwidth/(float) width); Calculates the width ratio int hratio = (int) Math.ceil (Op.outheight/(float) height); Calculate the height ratio if (pic! = null &&!pic.isrecycled ())) pic.recycle ();/** * Next, we need to determine whether scaling is required and how wide or high it is. If the height and width are not all beyond the screen, then no scaling is required. * If the height and width are beyond the screen size, then how to choose the scale it is necessary to determine the size of the wratio and Hratio * Large one will be scaled, because when zoomed in, small should be automatically scaled to the same ratio. Insamplesize variable */if (wratio > 1 && hratio > 1) {if (Wratio > Hratio) {op.insamplesize = Wratio;} LSE {op.insamplesize = Hratio;}} Op.injustdecodebounds = false; Note here, be sure to set to false, because above we set it to true to get the picture size of try {pic = Bitmapfactory.decodestream (_ctx.getcontentresolver (). Openinputstream (URI), null, OP);} catch (OutOfMemoryError e) {loadlocalimage (URL, 1);} return pic;} catch (Throwable e) {throw runtimeexceptionex.create (e);}} private static Bitmap loadlocalimage (String url, int insamplesize) {log ("LoadlocaLimage: "+ url"), if (!new File (URL). Exists ()) return null;if (Url.endswith (". mp4") | | Url.endswith (". 3gp")) {return loadlocalimagebyvideo (URL);} Bitmapfactory.options opt = new bitmapfactory.options ();//Opt.inpreferredconfig = bitmap.config.rgb_565;// opt.inpurgeable = true;//opt.ininputshareable = true;opt.insamplesize = insamplesize;//Get resource picture InputStream is = null;try { is = new FileInputStream (the URL); if (is! = null) {Bitmap map = Bitmapfactory.decodestream (is, null, opt); if (map = = null) retu RN Null;int height = map.getheight (); int width = Map.getwidth (); if (Width > 1920x1080 | | height >) {if (insamplesize = = 0) Insamplesize = 2;elseinsamplesize++;if (is = null) {try {is.close ()} catch (Exception ex) {}}map.recycle (); map = n Ull;return loadlocalimage (URL, insamplesize);} else {return map;}}} catch (OutOfMemoryError e) {if (is = = null) {try {is.close ();} catch (Exception ex) {}}SYSTEM.GC (); if (Insamplesize < 5 0) {if (insamplesize = = 0) insamplesize = 2;elseinsamplesize++;return LoaDlocalimage (URL, insamplesize);} Elsereturn null;} catch (Throwable e) {String stack = runtimeexceptionex.getstacktracestring (e);//cllog.error (e);//if (_d)//throw Runtim Eexceptionex.create (e);} Finally {if (is = null) {try {is.close ()} catch (Exception e) {}}system.gc ();} return null;} private static Bitmap loadhttpimage (String url, int width, int height) {log ("Loadhttpimage:" + URL); String localurl = getcachefilename (URL), try {HttpClient HC = new HttpClient (), if (Hc.downfile (URL, localurl)) return LOADL Ocalimage (localurl, width, height); elsereturn null;} catch (Exception e) {String stack = runtimeexceptionex.getstacktracestring (e);//cllog.error (e);//if (_d)//throw Runtimeexceptionex.create (e);} return null;} public static Bitmap loadimageandscale (String url, int width, int height) {log ("Loadimageandscale:" + URL); String thumbnailurl = getthumbnailfilename (url, width, height); Bitmap bmp = Loadlocalimage (URL, width, height), if (BMP = = null) {try {bmp = LoadImage (URL, width, height);} CAtch (Exception e) {String stack = runtimeexceptionex.getstacktracestring (e);} if (BMP! = null) {Bitmap Bmpthumbnail = imagehelper.scaleandsave (BMP, Thumbnailurl, width, height, true, true); if (Bmpthum Bnail! = BMP &&!bmp.isrecycled ()) bmp.recycle (); bmp = null; System.GC (); bmp = Bmpthumbnail;}} return bmp;} private static Boolean islocalimage (String URL) {return new File (URL). exists (); private static string Getcachefilename (string url) {if (Islocalimage (URL)) return URL; String localurl = null;if (URL! = null && url.length ()! = 0) {Localurl = CachePath + "/" + url.substring (url.lasti Ndexof ("/") + 1);} return localurl;} private static string Getthumbnailfilename (string url, int width, int height) {string thumbnailurl = null;if (URL! = NULL && url.length ()! = 0) {Thumbnailurl = String.Format ("%s/%d_%d_%s", thumbnailpath, width, height, url.substring ( Url.lastindexof ("/") + 1));} return thumbnailurl;} private static void log (String msg) {//CONSOLE.D ("Asyncimageloader", msg);}Public interface Imagecallback {public void imageloaded (drawable imagedrawable, String imageUrl);}}
A simple asynchronous loading image method for Android development