Android is a simple method for loading images asynchronously,

Source: Internet
Author: User

Android is a simple method for loading images asynchronously,

First, I have abandoned this method. I used it before and found that the loading speed is not good. I am not very careful about it.

Now I use volley. It is only critical to everyone.

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. con Tent. 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 co M. souya. seller. app. sellerApplication; public class AsyncImageLoader {private static boolean _ D = false; // AppConfig. _ D & private static final String TAG = "AsyncImageLoader"; public static String CachePath = null; private static String ThumbnailPath = null; private static boolean _ isInit = false; private static Context _ ctx; private static Bitmap _ empty = Bitmap. createBitmap (1, 1, Bitmap. config. RGB_565 ); Private static HashMap <String, SoftReference <Bitmap> imageCache = new HashMap <String, SoftReference <Bitmap> (); private static Queue <Runnable> queue = new Queue <Runnable> (); // thread pool: a maximum of 50 threads, one thread per execution, and the timeout time for Idle threads to end: 180 seconds private static ThreadPoolExecutor executor = new ThreadPoolExecutor (1, 20,300, TimeUnit. SECONDS, queue); public final static AsyncImageLoader Instance = new AsyncImageLoader (); public static Void Init (final Context context) {CachePath = SellerApplication. getInstance (). 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) message. obj, url) ;}}; // use the thread pool to download the image task executor.exe cute (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) Init (context); final String key = String. format ("% s _ % 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) message. obj, url) ;};// use a thread pool to download an image executor.exe cute (new Runnable () {@ Overridepublic void run () {Bitmap bmp = loadImageAndScale (u Rl, width, height); 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", url, width, height); releaseDrawable (key);} public static void releaseDrawable (String url) {try {log ("releaseDrawable" + url); String key = url; synchronized (imageCache) {if (imageCache. contai NsKey (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> (); public static Bitmap loadImage (String url) {log ("londImage:" + url); Object lockObj = null; synchronized (_ loadImageLocks) {if (_ loadImageLocks. containsKey (url) lockObj = _ loa DImageLocks. 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; 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, 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 loadLocalImage (url); elsereturn _ loadLocalImage (url, width, height);} private static Bitm Ap _ loadLocalImage (String url, int width, int height) {try {if (! New File (url ). exists () return null; // obtain the width and height of the screen. *** to calculate the scaling ratio, we need to obtain the size of the entire image, instead of the image * BitmapFactory. the Options class has a Boolean variable inJustDecodeBounds and sets it to true *. In this way, we get the image size instead of loading the image. When we set this value, we can start from BitmapFactory. * The outWidth and outHeight values of Options */BitmapFactory. options op = new BitmapFactory. options (); op. inJustDecodeBounds = true; Uri uri = Uri. fromFile (new File (url); // because MediaStore is used for storage, Bitmap pic = BitmapFactory is obtained based on the URI. decodeStream (_ ctx. getContentResolver (). openInputStream (uri), null, op); int wRatio = (int) Math. ceil (op. outWidth/(float) width); // calculate the width ratio of int h Ratio = (int) Math. ceil (op. outHeight/(float) height); // calculate the height Ratio if (pic! = Null &&! Pic. isRecycled () pic. recycle ();/*** next, we need to determine whether to scale and whether to scale the width or height. If not all the height and width exceed the screen, no scaling is required. * If both the height and width exceed the screen size, how can we select zoom? This requires determining the size of wRatio and hRatio * the larger one will be scaled, because when the scale is large, small ones should be scaled at the same rate automatically. The inSampleSize variable */if (wRatio> 1 & hRatio> 1) {if (wRatio> hRatio) {op. inSampleSize = wRatio;} else {op. inSampleSize = hRatio ;}} op. inJustDecodeBounds = false; // note that the value must be set to false, because we set it to true to obtain the image size. 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. ininputwritable able = true; opt. inSampleSize = inSampleSize; // obtain the resource image InputStream is = null; try {is = new FileInputStream (url); if (is! = Null) {Bitmap map = BitmapFactory. decodeStream (is, null, opt); if (map = null) return null; int height = map. getHeight (); int width = map. getWidth (); if (width> 1920 | height> 1080) {if (inSampleSize = 0) inSampleSize = 2; elseinSampleSize ++; if (is! = Null) {try {is. close () ;}catch (Exception ex) {}} map. recycle (); map = null; return loadLocalImage (url, inSampleSize);} else {return map ;}} catch (OutOfMemoryError e) {if (is! = Null) {try {is. close () ;}catch (Exception ex) {}} System. gc (); if (inSampleSize <50) {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 RuntimeExceptionEx. 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 loadLocalImage (localUrl, width, height); elsereturn null;} catch (Exception e) {String stack = runtime1_tio NEx. 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 bmp thumbnail = ImageHelper. ScaleAndSave (bmp, thumbnailUrl, width, height, true, true); if (bmp thumbnail! = Bmp &&! Bmp. isRecycled () bmp. recycle (); bmp = null; System. gc (); bmp = bmp thumbnail;} 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. lastIndexOf ("/") + 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 _ % 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 );}}





Related Article

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.